Search is not available for this dataset
repo
stringlengths
2
152
file
stringlengths
15
239
code
stringlengths
0
58.4M
file_length
int64
0
58.4M
avg_line_length
float64
0
1.81M
max_line_length
int64
0
12.7M
extension_type
stringclasses
364 values
AMG
AMG-master/parcsr_ls/par_rap.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ #include "_hypre_parcsr_ls.h" #include "_hypre_utilities.h" #include "hypre_hopscotch_hash.h" /*-------------------------------------------------------------------------- * OLD NOTES: * Sketch of John's code to build RAP * * Uses two integer arrays icg and ifg as marker arrays * * icg needs to be of size n_fine; size of ia. * A negative value of icg(i) indicates i is a f-point, otherwise * icg(i) is the converts from fine to coarse grid orderings. * Note that I belive the code assumes that if i<j and both are * c-points, then icg(i) < icg(j). * ifg needs to be of size n_coarse; size of irap * I don't think it has meaning as either input or output. * * In the code, both the interpolation and restriction operator * are stored row-wise in the array b. If i is a f-point, * ib(i) points the row of the interpolation operator for point * i. If i is a c-point, ib(i) points the row of the restriction * operator for point i. * * In the CSR storage for rap, its guaranteed that the rows will * be ordered ( i.e. ic<jc -> irap(ic) < irap(jc)) but I don't * think there is a guarantee that the entries within a row will * be ordered in any way except that the diagonal entry comes first. * * As structured now, the code requires that the size of rap be * predicted up front. To avoid this, one could execute the code * twice, the first time would only keep track of icg ,ifg and ka. * Then you would know how much memory to allocate for rap and jrap. * The second time would fill in these arrays. Actually you might * be able to include the filling in of jrap into the first pass; * just overestimate its size (its an integer array) and cut it * back before the second time through. This would avoid some if tests * in the second pass. * * Questions * 1) parallel (PetSc) version? * 2) what if we don't store R row-wise and don't * even want to store a copy of it in this form * temporarily? *--------------------------------------------------------------------------*/ hypre_CSRMatrix * hypre_ExchangeRAPData( hypre_CSRMatrix *RAP_int, hypre_ParCSRCommPkg *comm_pkg_RT) { HYPRE_Int *RAP_int_i; HYPRE_Int *RAP_int_j = NULL; HYPRE_Real *RAP_int_data = NULL; HYPRE_Int num_cols = 0; MPI_Comm comm = hypre_ParCSRCommPkgComm(comm_pkg_RT); HYPRE_Int num_recvs = hypre_ParCSRCommPkgNumRecvs(comm_pkg_RT); HYPRE_Int *recv_procs = hypre_ParCSRCommPkgRecvProcs(comm_pkg_RT); HYPRE_Int *recv_vec_starts = hypre_ParCSRCommPkgRecvVecStarts(comm_pkg_RT); HYPRE_Int num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg_RT); HYPRE_Int *send_procs = hypre_ParCSRCommPkgSendProcs(comm_pkg_RT); HYPRE_Int *send_map_starts = hypre_ParCSRCommPkgSendMapStarts(comm_pkg_RT); hypre_CSRMatrix *RAP_ext; HYPRE_Int *RAP_ext_i; HYPRE_Int *RAP_ext_j = NULL; HYPRE_Real *RAP_ext_data = NULL; hypre_ParCSRCommHandle *comm_handle = NULL; hypre_ParCSRCommPkg *tmp_comm_pkg; HYPRE_Int *jdata_recv_vec_starts; HYPRE_Int *jdata_send_map_starts; HYPRE_Int num_rows; HYPRE_Int num_nonzeros; HYPRE_Int i, j; HYPRE_Int num_procs; hypre_MPI_Comm_size(comm,&num_procs); RAP_ext_i = hypre_CTAlloc(HYPRE_Int, send_map_starts[num_sends]+1); jdata_recv_vec_starts = hypre_TAlloc(HYPRE_Int, num_recvs+1); jdata_send_map_starts = hypre_TAlloc(HYPRE_Int, num_sends+1); /*-------------------------------------------------------------------------- * recompute RAP_int_i so that RAP_int_i[j+1] contains the number of * elements of row j (to be determined through send_map_elmnts on the * receiving end) *--------------------------------------------------------------------------*/ if (num_recvs) { RAP_int_i = hypre_CSRMatrixI(RAP_int); RAP_int_j = hypre_CSRMatrixJ(RAP_int); RAP_int_data = hypre_CSRMatrixData(RAP_int); num_cols = hypre_CSRMatrixNumCols(RAP_int); } jdata_recv_vec_starts[0] = 0; for (i=0; i < num_recvs; i++) { jdata_recv_vec_starts[i+1] = RAP_int_i[recv_vec_starts[i+1]]; } for (i=num_recvs; i > 0; i--) for (j = recv_vec_starts[i]; j > recv_vec_starts[i-1]; j--) RAP_int_i[j] -= RAP_int_i[j-1]; /*-------------------------------------------------------------------------- * initialize communication *--------------------------------------------------------------------------*/ if (num_recvs && num_sends) comm_handle = hypre_ParCSRCommHandleCreate(12,comm_pkg_RT, &RAP_int_i[1], &RAP_ext_i[1]); else if (num_recvs) comm_handle = hypre_ParCSRCommHandleCreate(12,comm_pkg_RT, &RAP_int_i[1], NULL); else if (num_sends) comm_handle = hypre_ParCSRCommHandleCreate(12,comm_pkg_RT, NULL, &RAP_ext_i[1]); tmp_comm_pkg = hypre_CTAlloc(hypre_ParCSRCommPkg, 1); hypre_ParCSRCommPkgComm(tmp_comm_pkg) = comm; hypre_ParCSRCommPkgNumSends(tmp_comm_pkg) = num_recvs; hypre_ParCSRCommPkgNumRecvs(tmp_comm_pkg) = num_sends; hypre_ParCSRCommPkgSendProcs(tmp_comm_pkg) = recv_procs; hypre_ParCSRCommPkgRecvProcs(tmp_comm_pkg) = send_procs; hypre_ParCSRCommHandleDestroy(comm_handle); comm_handle = NULL; /*-------------------------------------------------------------------------- * compute num_nonzeros for RAP_ext *--------------------------------------------------------------------------*/ for (i=0; i < num_sends; i++) for (j = send_map_starts[i]; j < send_map_starts[i+1]; j++) RAP_ext_i[j+1] += RAP_ext_i[j]; num_rows = send_map_starts[num_sends]; num_nonzeros = RAP_ext_i[num_rows]; if (num_nonzeros) { RAP_ext_j = hypre_TAlloc(HYPRE_Int, num_nonzeros); RAP_ext_data = hypre_TAlloc(HYPRE_Real, num_nonzeros); } for (i=0; i < num_sends+1; i++) { jdata_send_map_starts[i] = RAP_ext_i[send_map_starts[i]]; } hypre_ParCSRCommPkgRecvVecStarts(tmp_comm_pkg) = jdata_send_map_starts; hypre_ParCSRCommPkgSendMapStarts(tmp_comm_pkg) = jdata_recv_vec_starts; comm_handle = hypre_ParCSRCommHandleCreate(1,tmp_comm_pkg,RAP_int_data, RAP_ext_data); hypre_ParCSRCommHandleDestroy(comm_handle); comm_handle = NULL; comm_handle = hypre_ParCSRCommHandleCreate(11,tmp_comm_pkg,RAP_int_j, RAP_ext_j); RAP_ext = hypre_CSRMatrixCreate(num_rows,num_cols,num_nonzeros); hypre_CSRMatrixI(RAP_ext) = RAP_ext_i; if (num_nonzeros) { hypre_CSRMatrixJ(RAP_ext) = RAP_ext_j; hypre_CSRMatrixData(RAP_ext) = RAP_ext_data; } hypre_ParCSRCommHandleDestroy(comm_handle); comm_handle = NULL; hypre_TFree(jdata_recv_vec_starts); hypre_TFree(jdata_send_map_starts); hypre_TFree(tmp_comm_pkg); return RAP_ext; } /*-------------------------------------------------------------------------- * hypre_BoomerAMGBuildCoarseOperator *--------------------------------------------------------------------------*/ HYPRE_Int hypre_BoomerAMGBuildCoarseOperator( hypre_ParCSRMatrix *RT, hypre_ParCSRMatrix *A, hypre_ParCSRMatrix *P, hypre_ParCSRMatrix **RAP_ptr ) { hypre_BoomerAMGBuildCoarseOperatorKT( RT, A, P, 0, RAP_ptr); return hypre_error_flag; } HYPRE_Int hypre_BoomerAMGBuildCoarseOperatorKT( hypre_ParCSRMatrix *RT, hypre_ParCSRMatrix *A, hypre_ParCSRMatrix *P, HYPRE_Int keepTranspose, hypre_ParCSRMatrix **RAP_ptr ) { #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_RAP] -= hypre_MPI_Wtime(); #endif MPI_Comm comm = hypre_ParCSRMatrixComm(A); hypre_CSRMatrix *RT_diag = hypre_ParCSRMatrixDiag(RT); hypre_CSRMatrix *RT_offd = hypre_ParCSRMatrixOffd(RT); HYPRE_Int num_cols_diag_RT = hypre_CSRMatrixNumCols(RT_diag); HYPRE_Int num_cols_offd_RT = hypre_CSRMatrixNumCols(RT_offd); HYPRE_Int num_rows_offd_RT = hypre_CSRMatrixNumRows(RT_offd); hypre_ParCSRCommPkg *comm_pkg_RT = hypre_ParCSRMatrixCommPkg(RT); HYPRE_Int num_recvs_RT = 0; HYPRE_Int num_sends_RT = 0; HYPRE_Int *send_map_starts_RT; HYPRE_Int *send_map_elmts_RT; hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); HYPRE_Real *A_diag_data = hypre_CSRMatrixData(A_diag); HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag); HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag); hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); HYPRE_Real *A_offd_data = hypre_CSRMatrixData(A_offd); HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd); HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd); HYPRE_Int num_cols_diag_A = hypre_CSRMatrixNumCols(A_diag); HYPRE_Int num_cols_offd_A = hypre_CSRMatrixNumCols(A_offd); hypre_CSRMatrix *P_diag = hypre_ParCSRMatrixDiag(P); HYPRE_Real *P_diag_data = hypre_CSRMatrixData(P_diag); HYPRE_Int *P_diag_i = hypre_CSRMatrixI(P_diag); HYPRE_Int *P_diag_j = hypre_CSRMatrixJ(P_diag); hypre_CSRMatrix *P_offd = hypre_ParCSRMatrixOffd(P); HYPRE_Int *col_map_offd_P = hypre_ParCSRMatrixColMapOffd(P); HYPRE_Real *P_offd_data = hypre_CSRMatrixData(P_offd); HYPRE_Int *P_offd_i = hypre_CSRMatrixI(P_offd); HYPRE_Int *P_offd_j = hypre_CSRMatrixJ(P_offd); HYPRE_Int first_col_diag_P = hypre_ParCSRMatrixFirstColDiag(P); HYPRE_Int last_col_diag_P; HYPRE_Int num_cols_diag_P = hypre_CSRMatrixNumCols(P_diag); HYPRE_Int num_cols_offd_P = hypre_CSRMatrixNumCols(P_offd); HYPRE_Int *coarse_partitioning = hypre_ParCSRMatrixColStarts(P); HYPRE_Int *RT_partitioning = hypre_ParCSRMatrixColStarts(RT); hypre_ParCSRMatrix *RAP; HYPRE_Int *col_map_offd_RAP = NULL; HYPRE_Int *new_col_map_offd_RAP = NULL; hypre_CSRMatrix *RAP_int = NULL; HYPRE_Real *RAP_int_data; HYPRE_Int *RAP_int_i; HYPRE_Int *RAP_int_j; hypre_CSRMatrix *RAP_ext; HYPRE_Real *RAP_ext_data = NULL; HYPRE_Int *RAP_ext_i = NULL; HYPRE_Int *RAP_ext_j = NULL; hypre_CSRMatrix *RAP_diag; HYPRE_Real *RAP_diag_data; HYPRE_Int *RAP_diag_i; HYPRE_Int *RAP_diag_j; hypre_CSRMatrix *RAP_offd; HYPRE_Real *RAP_offd_data = NULL; HYPRE_Int *RAP_offd_i = NULL; HYPRE_Int *RAP_offd_j = NULL; HYPRE_Int RAP_size; HYPRE_Int RAP_ext_size; HYPRE_Int RAP_diag_size; HYPRE_Int RAP_offd_size; HYPRE_Int P_ext_diag_size; HYPRE_Int P_ext_offd_size; HYPRE_Int first_col_diag_RAP; HYPRE_Int last_col_diag_RAP; HYPRE_Int num_cols_offd_RAP = 0; hypre_CSRMatrix *R_diag; HYPRE_Real *R_diag_data; HYPRE_Int *R_diag_i; HYPRE_Int *R_diag_j; hypre_CSRMatrix *R_offd; HYPRE_Real *R_offd_data; HYPRE_Int *R_offd_i; HYPRE_Int *R_offd_j; HYPRE_Real *RA_diag_data_array = NULL; HYPRE_Int *RA_diag_j_array = NULL; HYPRE_Real *RA_offd_data_array = NULL; HYPRE_Int *RA_offd_j_array = NULL; hypre_CSRMatrix *Ps_ext; HYPRE_Real *Ps_ext_data; HYPRE_Int *Ps_ext_i; HYPRE_Int *Ps_ext_j; HYPRE_Real *P_ext_diag_data = NULL; HYPRE_Int *P_ext_diag_i = NULL; HYPRE_Int *P_ext_diag_j = NULL; HYPRE_Real *P_ext_offd_data = NULL; HYPRE_Int *P_ext_offd_i = NULL; HYPRE_Int *P_ext_offd_j = NULL; HYPRE_Int *col_map_offd_Pext; HYPRE_Int *map_P_to_Pext = NULL; HYPRE_Int *map_P_to_RAP = NULL; HYPRE_Int *map_Pext_to_RAP = NULL; HYPRE_Int *P_marker; HYPRE_Int **P_mark_array; HYPRE_Int **A_mark_array; HYPRE_Int *A_marker; HYPRE_Int *temp; HYPRE_Int n_coarse, n_coarse_RT; HYPRE_Int square = 1; HYPRE_Int num_cols_offd_Pext = 0; HYPRE_Int ic, i, j, k; HYPRE_Int i1, i2, i3, ii, ns, ne, size, rest; HYPRE_Int cnt = 0; /*value; */ HYPRE_Int jj1, jj2, jj3, jcol; HYPRE_Int *jj_count, *jj_cnt_diag, *jj_cnt_offd; HYPRE_Int jj_counter, jj_count_diag, jj_count_offd; HYPRE_Int jj_row_begining, jj_row_begin_diag, jj_row_begin_offd; HYPRE_Int start_indexing = 0; /* start indexing for RAP_data at 0 */ HYPRE_Int num_nz_cols_A; HYPRE_Int num_procs; HYPRE_Int num_threads; HYPRE_Real r_entry; HYPRE_Real r_a_product; HYPRE_Real r_a_p_product; HYPRE_Real zero = 0.0; HYPRE_Int *prefix_sum_workspace; /*----------------------------------------------------------------------- * Copy ParCSRMatrix RT into CSRMatrix R so that we have row-wise access * to restriction . *-----------------------------------------------------------------------*/ hypre_MPI_Comm_size(comm,&num_procs); num_threads = hypre_NumThreads(); if (comm_pkg_RT) { num_recvs_RT = hypre_ParCSRCommPkgNumRecvs(comm_pkg_RT); num_sends_RT = hypre_ParCSRCommPkgNumSends(comm_pkg_RT); send_map_starts_RT =hypre_ParCSRCommPkgSendMapStarts(comm_pkg_RT); send_map_elmts_RT = hypre_ParCSRCommPkgSendMapElmts(comm_pkg_RT); } else if (num_procs > 1) { hypre_MatvecCommPkgCreate(RT); comm_pkg_RT = hypre_ParCSRMatrixCommPkg(RT); num_recvs_RT = hypre_ParCSRCommPkgNumRecvs(comm_pkg_RT); num_sends_RT = hypre_ParCSRCommPkgNumSends(comm_pkg_RT); send_map_starts_RT =hypre_ParCSRCommPkgSendMapStarts(comm_pkg_RT); send_map_elmts_RT = hypre_ParCSRCommPkgSendMapElmts(comm_pkg_RT); } hypre_CSRMatrixTranspose(RT_diag,&R_diag,1); if (num_cols_offd_RT) { hypre_CSRMatrixTranspose(RT_offd,&R_offd,1); R_offd_data = hypre_CSRMatrixData(R_offd); R_offd_i = hypre_CSRMatrixI(R_offd); R_offd_j = hypre_CSRMatrixJ(R_offd); } /*----------------------------------------------------------------------- * Access the CSR vectors for R. Also get sizes of fine and * coarse grids. *-----------------------------------------------------------------------*/ R_diag_data = hypre_CSRMatrixData(R_diag); R_diag_i = hypre_CSRMatrixI(R_diag); R_diag_j = hypre_CSRMatrixJ(R_diag); n_coarse = hypre_ParCSRMatrixGlobalNumCols(P); num_nz_cols_A = num_cols_diag_A + num_cols_offd_A; n_coarse_RT = hypre_ParCSRMatrixGlobalNumCols(RT); if (n_coarse != n_coarse_RT) square = 0; /*----------------------------------------------------------------------- * Generate Ps_ext, i.e. portion of P that is stored on neighbor procs * and needed locally for triple matrix product *-----------------------------------------------------------------------*/ #ifdef HYPRE_CONCURRENT_HOPSCOTCH hypre_UnorderedIntMap send_map_elmts_RT_inverse_map; HYPRE_Int *send_map_elmts_starts_RT_aggregated = NULL; HYPRE_Int *send_map_elmts_RT_aggregated = NULL; HYPRE_Int send_map_elmts_RT_inverse_map_initialized = num_sends_RT > 0 && send_map_starts_RT[num_sends_RT] - send_map_starts_RT[0] > 0; if (send_map_elmts_RT_inverse_map_initialized) { hypre_UnorderedIntSet send_map_elmts_set; hypre_UnorderedIntSetCreate(&send_map_elmts_set, 2*(send_map_starts_RT[num_sends_RT] - send_map_starts_RT[0]), 16*hypre_NumThreads()); #pragma omp parallel for HYPRE_SMP_SCHEDULE for (i = send_map_starts_RT[0]; i < send_map_starts_RT[num_sends_RT]; i++) { HYPRE_Int key = send_map_elmts_RT[i]; hypre_UnorderedIntSetPut(&send_map_elmts_set, key); } HYPRE_Int send_map_elmts_unique_size; HYPRE_Int *send_map_elmts_unique = hypre_UnorderedIntSetCopyToArray(&send_map_elmts_set, &send_map_elmts_unique_size); hypre_UnorderedIntSetDestroy(&send_map_elmts_set); hypre_UnorderedIntMapCreate(&send_map_elmts_RT_inverse_map, 2*send_map_elmts_unique_size, 16*hypre_NumThreads()); #pragma omp parallel for HYPRE_SMP_SCHEDULE for (i = 0; i < send_map_elmts_unique_size; i++) { hypre_UnorderedIntMapPutIfAbsent(&send_map_elmts_RT_inverse_map, send_map_elmts_unique[i], i); } hypre_TFree(send_map_elmts_unique); send_map_elmts_starts_RT_aggregated = hypre_TAlloc(HYPRE_Int, send_map_elmts_unique_size + 1); send_map_elmts_RT_aggregated = hypre_TAlloc(HYPRE_Int, send_map_starts_RT[num_sends_RT]); #pragma omp parallel for HYPRE_SMP_SCHEDULE for (i = 0; i < send_map_elmts_unique_size; i++) { send_map_elmts_starts_RT_aggregated[i] = 0; } #pragma omp parallel for HYPRE_SMP_SCHEDULE for (i = send_map_starts_RT[0]; i < send_map_starts_RT[num_sends_RT]; i++) { HYPRE_Int idx = hypre_UnorderedIntMapGet(&send_map_elmts_RT_inverse_map, send_map_elmts_RT[i]); #pragma omp atomic send_map_elmts_starts_RT_aggregated[idx]++; } for (i = 0; i < send_map_elmts_unique_size - 1; i++) { send_map_elmts_starts_RT_aggregated[i + 1] += send_map_elmts_starts_RT_aggregated[i]; } send_map_elmts_starts_RT_aggregated[send_map_elmts_unique_size] = send_map_starts_RT[num_sends_RT]; #pragma omp parallel for HYPRE_SMP_SCHEDULE for (i = send_map_starts_RT[num_sends_RT] - 1; i >= send_map_starts_RT[0]; i--) { HYPRE_Int idx = hypre_UnorderedIntMapGet(&send_map_elmts_RT_inverse_map, send_map_elmts_RT[i]); HYPRE_Int offset = hypre_fetch_and_add(send_map_elmts_starts_RT_aggregated + idx, -1) - 1; send_map_elmts_RT_aggregated[offset] = i; } } #endif /* HYPRE_CONCURRENT_HOPSCOTCH */ #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_RENUMBER_COLIDX] -= hypre_MPI_Wtime(); hypre_profile_times[HYPRE_TIMER_ID_RENUMBER_COLIDX_RAP] -= hypre_MPI_Wtime(); #endif if (num_procs > 1) { Ps_ext = hypre_ParCSRMatrixExtractBExt(P,A,1); Ps_ext_data = hypre_CSRMatrixData(Ps_ext); Ps_ext_i = hypre_CSRMatrixI(Ps_ext); Ps_ext_j = hypre_CSRMatrixJ(Ps_ext); } P_ext_diag_i = hypre_TAlloc(HYPRE_Int,num_cols_offd_A+1); P_ext_offd_i = hypre_TAlloc(HYPRE_Int,num_cols_offd_A+1); P_ext_diag_i[0] = 0; P_ext_offd_i[0] = 0; P_ext_diag_size = 0; P_ext_offd_size = 0; last_col_diag_P = first_col_diag_P + num_cols_diag_P - 1; /*HYPRE_Int prefix_sum_workspace[2*(num_threads + 1)];*/ prefix_sum_workspace = hypre_TAlloc(HYPRE_Int, 2*(num_threads + 1)); #ifdef HYPRE_USING_OPENMP #pragma omp parallel private(i,j) #endif { HYPRE_Int i_begin, i_end; hypre_GetSimpleThreadPartition(&i_begin, &i_end, num_cols_offd_A); HYPRE_Int P_ext_diag_size_private = 0; HYPRE_Int P_ext_offd_size_private = 0; for (i = i_begin; i < i_end; i++) { for (j=Ps_ext_i[i]; j < Ps_ext_i[i+1]; j++) if (Ps_ext_j[j] < first_col_diag_P || Ps_ext_j[j] > last_col_diag_P) P_ext_offd_size_private++; else P_ext_diag_size_private++; } hypre_prefix_sum_pair(&P_ext_diag_size_private, &P_ext_diag_size, &P_ext_offd_size_private, &P_ext_offd_size, prefix_sum_workspace); #ifdef HYPRE_USING_OPENMP #pragma omp master #endif { if (P_ext_diag_size) { P_ext_diag_j = hypre_CTAlloc(HYPRE_Int, P_ext_diag_size); P_ext_diag_data = hypre_CTAlloc(HYPRE_Real, P_ext_diag_size); } if (P_ext_offd_size) { P_ext_offd_j = hypre_CTAlloc(HYPRE_Int, P_ext_offd_size); P_ext_offd_data = hypre_CTAlloc(HYPRE_Real, P_ext_offd_size); } } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif for (i = i_begin; i < i_end; i++) { for (j=Ps_ext_i[i]; j < Ps_ext_i[i+1]; j++) { if (Ps_ext_j[j] < first_col_diag_P || Ps_ext_j[j] > last_col_diag_P) { P_ext_offd_j[P_ext_offd_size_private] = Ps_ext_j[j]; P_ext_offd_data[P_ext_offd_size_private++] = Ps_ext_data[j]; } else { P_ext_diag_j[P_ext_diag_size_private] = Ps_ext_j[j] - first_col_diag_P; P_ext_diag_data[P_ext_diag_size_private++] = Ps_ext_data[j]; } } P_ext_diag_i[i+1] = P_ext_diag_size_private; P_ext_offd_i[i+1] = P_ext_offd_size_private; } } /* omp parallel */ hypre_TFree(prefix_sum_workspace); if (num_procs > 1) { hypre_CSRMatrixDestroy(Ps_ext); Ps_ext = NULL; } #ifdef HYPRE_CONCURRENT_HOPSCOTCH if (P_ext_offd_size || num_cols_offd_P) { hypre_UnorderedIntSet found_set; hypre_UnorderedIntSetCreate(&found_set, P_ext_offd_size + num_cols_offd_P, 16*hypre_NumThreads()); #pragma omp parallel private(i) { #pragma omp for HYPRE_SMP_SCHEDULE for (i = 0; i < P_ext_offd_size; i++) { hypre_UnorderedIntSetPut(&found_set, P_ext_offd_j[i]); } #pragma omp for HYPRE_SMP_SCHEDULE for (i = 0; i < num_cols_offd_P; i++) { hypre_UnorderedIntSetPut(&found_set, col_map_offd_P[i]); } } /* omp parallel */ temp = hypre_UnorderedIntSetCopyToArray(&found_set, &num_cols_offd_Pext); hypre_UnorderedIntSetDestroy(&found_set); hypre_UnorderedIntMap col_map_offd_Pext_inverse; hypre_sort_and_create_inverse_map(temp, num_cols_offd_Pext, &col_map_offd_Pext, &col_map_offd_Pext_inverse); #pragma omp parallel for HYPRE_SMP_SCHEDULE for (i=0 ; i < P_ext_offd_size; i++) P_ext_offd_j[i] = hypre_UnorderedIntMapGet(&col_map_offd_Pext_inverse, P_ext_offd_j[i]); if (num_cols_offd_Pext) hypre_UnorderedIntMapDestroy(&col_map_offd_Pext_inverse); } #else /* !HYPRE_CONCURRENT_HOPSCOTCH */ if (P_ext_offd_size || num_cols_offd_P) { temp = hypre_CTAlloc(HYPRE_Int, P_ext_offd_size+num_cols_offd_P); for (i=0; i < P_ext_offd_size; i++) temp[i] = P_ext_offd_j[i]; cnt = P_ext_offd_size; for (i=0; i < num_cols_offd_P; i++) temp[cnt++] = col_map_offd_P[i]; } if (cnt) { HYPRE_Int value; hypre_qsort0(temp, 0, cnt-1); num_cols_offd_Pext = 1; value = temp[0]; for (i=1; i < cnt; i++) { if (temp[i] > value) { value = temp[i]; temp[num_cols_offd_Pext++] = value; } } } if (num_cols_offd_Pext) col_map_offd_Pext = hypre_CTAlloc(HYPRE_Int,num_cols_offd_Pext); for (i=0; i < num_cols_offd_Pext; i++) col_map_offd_Pext[i] = temp[i]; if (P_ext_offd_size || num_cols_offd_P) hypre_TFree(temp); for (i=0 ; i < P_ext_offd_size; i++) P_ext_offd_j[i] = hypre_BinarySearch(col_map_offd_Pext, P_ext_offd_j[i], num_cols_offd_Pext); #endif /* !HYPRE_CONCURRENT_HOPSCOTCH */ if (num_cols_offd_P) { map_P_to_Pext = hypre_CTAlloc(HYPRE_Int,num_cols_offd_P); cnt = 0; for (i=0; i < num_cols_offd_Pext; i++) if (col_map_offd_Pext[i] == col_map_offd_P[cnt]) { map_P_to_Pext[cnt++] = i; if (cnt == num_cols_offd_P) break; } } #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_RENUMBER_COLIDX] += hypre_MPI_Wtime(); hypre_profile_times[HYPRE_TIMER_ID_RENUMBER_COLIDX_RAP] += hypre_MPI_Wtime(); #endif /*----------------------------------------------------------------------- * First Pass: Determine size of RAP_int and set up RAP_int_i if there * are more than one processor and nonzero elements in R_offd *-----------------------------------------------------------------------*/ P_mark_array = hypre_CTAlloc(HYPRE_Int *, num_threads); A_mark_array = hypre_CTAlloc(HYPRE_Int *, num_threads); if (num_cols_offd_RT) { jj_count = hypre_CTAlloc(HYPRE_Int, num_threads); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,ii,ic,i1,i2,i3,jj1,jj2,jj3,ns,ne,size,rest,jj_counter,jj_row_begining,A_marker,P_marker) HYPRE_SMP_SCHEDULE #endif for (ii = 0; ii < num_threads; ii++) { size = num_cols_offd_RT/num_threads; rest = num_cols_offd_RT - size*num_threads; if (ii < rest) { ns = ii*size+ii; ne = (ii+1)*size+ii+1; } else { ns = ii*size+rest; ne = (ii+1)*size+rest; } /*----------------------------------------------------------------------- * Allocate marker arrays. *-----------------------------------------------------------------------*/ if (num_cols_offd_Pext || num_cols_diag_P) { P_mark_array[ii] = hypre_CTAlloc(HYPRE_Int, num_cols_diag_P+num_cols_offd_Pext); P_marker = P_mark_array[ii]; } A_mark_array[ii] = hypre_CTAlloc(HYPRE_Int, num_nz_cols_A); A_marker = A_mark_array[ii]; /*----------------------------------------------------------------------- * Initialize some stuff. *-----------------------------------------------------------------------*/ jj_counter = start_indexing; for (ic = 0; ic < num_cols_diag_P+num_cols_offd_Pext; ic++) { P_marker[ic] = -1; } for (i = 0; i < num_nz_cols_A; i++) { A_marker[i] = -1; } /*----------------------------------------------------------------------- * Loop over exterior c-points *-----------------------------------------------------------------------*/ for (ic = ns; ic < ne; ic++) { jj_row_begining = jj_counter; /*-------------------------------------------------------------------- * Loop over entries in row ic of R_offd. *--------------------------------------------------------------------*/ for (jj1 = R_offd_i[ic]; jj1 < R_offd_i[ic+1]; jj1++) { i1 = R_offd_j[jj1]; /*----------------------------------------------------------------- * Loop over entries in row i1 of A_offd. *-----------------------------------------------------------------*/ for (jj2 = A_offd_i[i1]; jj2 < A_offd_i[i1+1]; jj2++) { i2 = A_offd_j[jj2]; /*-------------------------------------------------------------- * Check A_marker to see if point i2 has been previously * visited. New entries in RAP only occur from unmarked points. *--------------------------------------------------------------*/ if (A_marker[i2] != ic) { /*----------------------------------------------------------- * Mark i2 as visited. *-----------------------------------------------------------*/ A_marker[i2] = ic; /*----------------------------------------------------------- * Loop over entries in row i2 of P_ext. *-----------------------------------------------------------*/ for (jj3 = P_ext_diag_i[i2]; jj3 < P_ext_diag_i[i2+1]; jj3++) { i3 = P_ext_diag_j[jj3]; /*-------------------------------------------------------- * Check P_marker to see that RAP_{ic,i3} has not already * been accounted for. If it has not, mark it and increment * counter. *--------------------------------------------------------*/ if (P_marker[i3] < jj_row_begining) { P_marker[i3] = jj_counter; jj_counter++; } } for (jj3 = P_ext_offd_i[i2]; jj3 < P_ext_offd_i[i2+1]; jj3++) { i3 = P_ext_offd_j[jj3] + num_cols_diag_P; /*-------------------------------------------------------- * Check P_marker to see that RAP_{ic,i3} has not already * been accounted for. If it has not, mark it and increment * counter. *--------------------------------------------------------*/ if (P_marker[i3] < jj_row_begining) { P_marker[i3] = jj_counter; jj_counter++; } } } } /*----------------------------------------------------------------- * Loop over entries in row i1 of A_diag. *-----------------------------------------------------------------*/ for (jj2 = A_diag_i[i1]; jj2 < A_diag_i[i1+1]; jj2++) { i2 = A_diag_j[jj2]; /*-------------------------------------------------------------- * Check A_marker to see if point i2 has been previously * visited. New entries in RAP only occur from unmarked points. *--------------------------------------------------------------*/ if (A_marker[i2+num_cols_offd_A] != ic) { /*----------------------------------------------------------- * Mark i2 as visited. *-----------------------------------------------------------*/ A_marker[i2+num_cols_offd_A] = ic; /*----------------------------------------------------------- * Loop over entries in row i2 of P_diag. *-----------------------------------------------------------*/ for (jj3 = P_diag_i[i2]; jj3 < P_diag_i[i2+1]; jj3++) { i3 = P_diag_j[jj3]; /*-------------------------------------------------------- * Check P_marker to see that RAP_{ic,i3} has not already * been accounted for. If it has not, mark it and increment * counter. *--------------------------------------------------------*/ if (P_marker[i3] < jj_row_begining) { P_marker[i3] = jj_counter; jj_counter++; } } /*----------------------------------------------------------- * Loop over entries in row i2 of P_offd. *-----------------------------------------------------------*/ for (jj3 = P_offd_i[i2]; jj3 < P_offd_i[i2+1]; jj3++) { i3 = map_P_to_Pext[P_offd_j[jj3]] + num_cols_diag_P; /*-------------------------------------------------------- * Check P_marker to see that RAP_{ic,i3} has not already * been accounted for. If it has not, mark it and increment * counter. *--------------------------------------------------------*/ if (P_marker[i3] < jj_row_begining) { P_marker[i3] = jj_counter; jj_counter++; } } } } } } jj_count[ii] = jj_counter; } /*----------------------------------------------------------------------- * Allocate RAP_int_data and RAP_int_j arrays. *-----------------------------------------------------------------------*/ for (i = 0; i < num_threads-1; i++) jj_count[i+1] += jj_count[i]; RAP_size = jj_count[num_threads-1]; RAP_int_i = hypre_CTAlloc(HYPRE_Int, num_cols_offd_RT+1); RAP_int_data = hypre_CTAlloc(HYPRE_Real, RAP_size); RAP_int_j = hypre_CTAlloc(HYPRE_Int, RAP_size); RAP_int_i[num_cols_offd_RT] = RAP_size; /*----------------------------------------------------------------------- * Second Pass: Fill in RAP_int_data and RAP_int_j. *-----------------------------------------------------------------------*/ #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,ii,ic,i1,i2,i3,jj1,jj2,jj3,ns,ne,size,rest,jj_counter,jj_row_begining,A_marker,P_marker,r_entry,r_a_product,r_a_p_product) HYPRE_SMP_SCHEDULE #endif for (ii = 0; ii < num_threads; ii++) { size = num_cols_offd_RT/num_threads; rest = num_cols_offd_RT - size*num_threads; if (ii < rest) { ns = ii*size+ii; ne = (ii+1)*size+ii+1; } else { ns = ii*size+rest; ne = (ii+1)*size+rest; } /*----------------------------------------------------------------------- * Initialize some stuff. *-----------------------------------------------------------------------*/ if (num_cols_offd_Pext || num_cols_diag_P) P_marker = P_mark_array[ii]; A_marker = A_mark_array[ii]; jj_counter = start_indexing; if (ii > 0) jj_counter = jj_count[ii-1]; for (ic = 0; ic < num_cols_diag_P+num_cols_offd_Pext; ic++) { P_marker[ic] = -1; } for (i = 0; i < num_nz_cols_A; i++) { A_marker[i] = -1; } /*----------------------------------------------------------------------- * Loop over exterior c-points. *-----------------------------------------------------------------------*/ for (ic = ns; ic < ne; ic++) { jj_row_begining = jj_counter; RAP_int_i[ic] = jj_counter; /*-------------------------------------------------------------------- * Loop over entries in row ic of R_offd. *--------------------------------------------------------------------*/ for (jj1 = R_offd_i[ic]; jj1 < R_offd_i[ic+1]; jj1++) { i1 = R_offd_j[jj1]; r_entry = R_offd_data[jj1]; /*----------------------------------------------------------------- * Loop over entries in row i1 of A_offd. *-----------------------------------------------------------------*/ for (jj2 = A_offd_i[i1]; jj2 < A_offd_i[i1+1]; jj2++) { i2 = A_offd_j[jj2]; r_a_product = r_entry * A_offd_data[jj2]; /*-------------------------------------------------------------- * Check A_marker to see if point i2 has been previously * visited. New entries in RAP only occur from unmarked points. *--------------------------------------------------------------*/ if (A_marker[i2] != ic) { /*----------------------------------------------------------- * Mark i2 as visited. *-----------------------------------------------------------*/ A_marker[i2] = ic; /*----------------------------------------------------------- * Loop over entries in row i2 of P_ext. *-----------------------------------------------------------*/ for (jj3 = P_ext_diag_i[i2]; jj3 < P_ext_diag_i[i2+1]; jj3++) { i3 = P_ext_diag_j[jj3]; r_a_p_product = r_a_product * P_ext_diag_data[jj3]; /*-------------------------------------------------------- * Check P_marker to see that RAP_{ic,i3} has not already * been accounted for. If it has not, create a new entry. * If it has, add new contribution. *--------------------------------------------------------*/ if (P_marker[i3] < jj_row_begining) { P_marker[i3] = jj_counter; RAP_int_data[jj_counter] = r_a_p_product; RAP_int_j[jj_counter] = i3 + first_col_diag_P; jj_counter++; } else { RAP_int_data[P_marker[i3]] += r_a_p_product; } } for (jj3 = P_ext_offd_i[i2]; jj3 < P_ext_offd_i[i2+1]; jj3++) { i3 = P_ext_offd_j[jj3] + num_cols_diag_P; r_a_p_product = r_a_product * P_ext_offd_data[jj3]; /*-------------------------------------------------------- * Check P_marker to see that RAP_{ic,i3} has not already * been accounted for. If it has not, create a new entry. * If it has, add new contribution. *--------------------------------------------------------*/ if (P_marker[i3] < jj_row_begining) { P_marker[i3] = jj_counter; RAP_int_data[jj_counter] = r_a_p_product; RAP_int_j[jj_counter] = col_map_offd_Pext[i3-num_cols_diag_P]; jj_counter++; } else { RAP_int_data[P_marker[i3]] += r_a_p_product; } } } /*-------------------------------------------------------------- * If i2 is previously visited ( A_marker[12]=ic ) it yields * no new entries in RAP and can just add new contributions. *--------------------------------------------------------------*/ else { for (jj3 = P_ext_diag_i[i2]; jj3 < P_ext_diag_i[i2+1]; jj3++) { i3 = P_ext_diag_j[jj3]; r_a_p_product = r_a_product * P_ext_diag_data[jj3]; RAP_int_data[P_marker[i3]] += r_a_p_product; } for (jj3 = P_ext_offd_i[i2]; jj3 < P_ext_offd_i[i2+1]; jj3++) { i3 = P_ext_offd_j[jj3] + num_cols_diag_P; r_a_p_product = r_a_product * P_ext_offd_data[jj3]; RAP_int_data[P_marker[i3]] += r_a_p_product; } } } /*----------------------------------------------------------------- * Loop over entries in row i1 of A_diag. *-----------------------------------------------------------------*/ for (jj2 = A_diag_i[i1]; jj2 < A_diag_i[i1+1]; jj2++) { i2 = A_diag_j[jj2]; r_a_product = r_entry * A_diag_data[jj2]; /*-------------------------------------------------------------- * Check A_marker to see if point i2 has been previously * visited. New entries in RAP only occur from unmarked points. *--------------------------------------------------------------*/ if (A_marker[i2+num_cols_offd_A] != ic) { /*----------------------------------------------------------- * Mark i2 as visited. *-----------------------------------------------------------*/ A_marker[i2+num_cols_offd_A] = ic; /*----------------------------------------------------------- * Loop over entries in row i2 of P_diag. *-----------------------------------------------------------*/ for (jj3 = P_diag_i[i2]; jj3 < P_diag_i[i2+1]; jj3++) { i3 = P_diag_j[jj3]; r_a_p_product = r_a_product * P_diag_data[jj3]; /*-------------------------------------------------------- * Check P_marker to see that RAP_{ic,i3} has not already * been accounted for. If it has not, create a new entry. * If it has, add new contribution. *--------------------------------------------------------*/ if (P_marker[i3] < jj_row_begining) { P_marker[i3] = jj_counter; RAP_int_data[jj_counter] = r_a_p_product; RAP_int_j[jj_counter] = i3 + first_col_diag_P; jj_counter++; } else { RAP_int_data[P_marker[i3]] += r_a_p_product; } } for (jj3 = P_offd_i[i2]; jj3 < P_offd_i[i2+1]; jj3++) { i3 = map_P_to_Pext[P_offd_j[jj3]] + num_cols_diag_P; r_a_p_product = r_a_product * P_offd_data[jj3]; /*-------------------------------------------------------- * Check P_marker to see that RAP_{ic,i3} has not already * been accounted for. If it has not, create a new entry. * If it has, add new contribution. *--------------------------------------------------------*/ if (P_marker[i3] < jj_row_begining) { P_marker[i3] = jj_counter; RAP_int_data[jj_counter] = r_a_p_product; RAP_int_j[jj_counter] = col_map_offd_Pext[i3-num_cols_diag_P]; jj_counter++; } else { RAP_int_data[P_marker[i3]] += r_a_p_product; } } } /*-------------------------------------------------------------- * If i2 is previously visited ( A_marker[12]=ic ) it yields * no new entries in RAP and can just add new contributions. *--------------------------------------------------------------*/ else { for (jj3 = P_diag_i[i2]; jj3 < P_diag_i[i2+1]; jj3++) { i3 = P_diag_j[jj3]; r_a_p_product = r_a_product * P_diag_data[jj3]; RAP_int_data[P_marker[i3]] += r_a_p_product; } for (jj3 = P_offd_i[i2]; jj3 < P_offd_i[i2+1]; jj3++) { i3 = map_P_to_Pext[P_offd_j[jj3]] + num_cols_diag_P; r_a_p_product = r_a_product * P_offd_data[jj3]; RAP_int_data[P_marker[i3]] += r_a_p_product; } } } } } if (num_cols_offd_Pext || num_cols_diag_P) hypre_TFree(P_mark_array[ii]); hypre_TFree(A_mark_array[ii]); } RAP_int = hypre_CSRMatrixCreate(num_cols_offd_RT,num_rows_offd_RT,RAP_size); hypre_CSRMatrixI(RAP_int) = RAP_int_i; hypre_CSRMatrixJ(RAP_int) = RAP_int_j; hypre_CSRMatrixData(RAP_int) = RAP_int_data; hypre_TFree(jj_count); } #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_RENUMBER_COLIDX] -= hypre_MPI_Wtime(); hypre_profile_times[HYPRE_TIMER_ID_RENUMBER_COLIDX_RAP] -= hypre_MPI_Wtime(); #endif RAP_ext_size = 0; if (num_sends_RT || num_recvs_RT) { RAP_ext = hypre_ExchangeRAPData(RAP_int,comm_pkg_RT); RAP_ext_i = hypre_CSRMatrixI(RAP_ext); RAP_ext_j = hypre_CSRMatrixJ(RAP_ext); RAP_ext_data = hypre_CSRMatrixData(RAP_ext); RAP_ext_size = RAP_ext_i[hypre_CSRMatrixNumRows(RAP_ext)]; } if (num_cols_offd_RT) { hypre_CSRMatrixDestroy(RAP_int); RAP_int = NULL; } RAP_diag_i = hypre_TAlloc(HYPRE_Int, num_cols_diag_RT+1); RAP_offd_i = hypre_TAlloc(HYPRE_Int, num_cols_diag_RT+1); first_col_diag_RAP = first_col_diag_P; last_col_diag_RAP = first_col_diag_P + num_cols_diag_P - 1; /*----------------------------------------------------------------------- * check for new nonzero columns in RAP_offd generated through RAP_ext *-----------------------------------------------------------------------*/ #ifdef HYPRE_CONCURRENT_HOPSCOTCH hypre_UnorderedIntMap col_map_offd_RAP_inverse; if (RAP_ext_size || num_cols_offd_Pext) { hypre_UnorderedIntSet found_set; hypre_UnorderedIntSetCreate(&found_set, 2*(RAP_ext_size + num_cols_offd_Pext), 16*hypre_NumThreads()); cnt = 0; #pragma omp parallel private(i) { #pragma omp for HYPRE_SMP_SCHEDULE for (i = 0; i < RAP_ext_size; i++) { if (RAP_ext_j[i] < first_col_diag_RAP || RAP_ext_j[i] > last_col_diag_RAP) hypre_UnorderedIntSetPut(&found_set, RAP_ext_j[i]); } #pragma omp for HYPRE_SMP_SCHEDULE for (i = 0; i < num_cols_offd_Pext; i++) { hypre_UnorderedIntSetPut(&found_set, col_map_offd_Pext[i]); } } /* omp parallel */ temp = hypre_UnorderedIntSetCopyToArray(&found_set, &num_cols_offd_RAP); hypre_UnorderedIntSetDestroy(&found_set); hypre_sort_and_create_inverse_map(temp, num_cols_offd_RAP, &col_map_offd_RAP, &col_map_offd_RAP_inverse); // num_cols_offd_RAP <= RAP_ext_size + num_cols_offd_Pext } #else /* !HYPRE_CONCURRENT_HOPSCOTCH */ if (RAP_ext_size || num_cols_offd_Pext) { temp = hypre_CTAlloc(HYPRE_Int,RAP_ext_size+num_cols_offd_Pext); cnt = 0; for (i=0; i < RAP_ext_size; i++) if (RAP_ext_j[i] < first_col_diag_RAP || RAP_ext_j[i] > last_col_diag_RAP) temp[cnt++] = RAP_ext_j[i]; for (i=0; i < num_cols_offd_Pext; i++) temp[cnt++] = col_map_offd_Pext[i]; if (cnt) { HYPRE_Int value; hypre_qsort0(temp,0,cnt-1); value = temp[0]; num_cols_offd_RAP = 1; for (i=1; i < cnt; i++) { if (temp[i] > value) { value = temp[i]; temp[num_cols_offd_RAP++] = value; } } } /* now evaluate col_map_offd_RAP */ if (num_cols_offd_RAP) col_map_offd_RAP = hypre_CTAlloc(HYPRE_Int, num_cols_offd_RAP); for (i=0 ; i < num_cols_offd_RAP; i++) col_map_offd_RAP[i] = temp[i]; hypre_TFree(temp); } #endif /* !HYPRE_CONCURRENT_HOPSCOTCH */ if (num_cols_offd_P) { map_P_to_RAP = hypre_TAlloc(HYPRE_Int,num_cols_offd_P); cnt = 0; for (i=0; i < num_cols_offd_RAP; i++) if (col_map_offd_RAP[i] == col_map_offd_P[cnt]) { map_P_to_RAP[cnt++] = i; if (cnt == num_cols_offd_P) break; } } if (num_cols_offd_Pext) { map_Pext_to_RAP = hypre_TAlloc(HYPRE_Int,num_cols_offd_Pext); cnt = 0; for (i=0; i < num_cols_offd_RAP; i++) if (col_map_offd_RAP[i] == col_map_offd_Pext[cnt]) { map_Pext_to_RAP[cnt++] = i; if (cnt == num_cols_offd_Pext) break; } } /*----------------------------------------------------------------------- * Convert RAP_ext column indices *-----------------------------------------------------------------------*/ #ifdef HYPRE_USING_OPENMP #pragma omp parallel for HYPRE_SMP_SCHEDULE #endif for (i=0; i < RAP_ext_size; i++) if (RAP_ext_j[i] < first_col_diag_RAP || RAP_ext_j[i] > last_col_diag_RAP) RAP_ext_j[i] = num_cols_diag_P #ifdef HYPRE_CONCURRENT_HOPSCOTCH + hypre_UnorderedIntMapGet(&col_map_offd_RAP_inverse, RAP_ext_j[i]); #else + hypre_BinarySearch(col_map_offd_RAP, RAP_ext_j[i],num_cols_offd_RAP); #endif else RAP_ext_j[i] -= first_col_diag_RAP; #ifdef HYPRE_CONCURRENT_HOPSCOTCH if (num_cols_offd_RAP) hypre_UnorderedIntMapDestroy(&col_map_offd_RAP_inverse); #endif #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_RENUMBER_COLIDX] += hypre_MPI_Wtime(); hypre_profile_times[HYPRE_TIMER_ID_RENUMBER_COLIDX_RAP] += hypre_MPI_Wtime(); #endif /* need to allocate new P_marker etc. and make further changes */ /*----------------------------------------------------------------------- * Initialize some stuff. *-----------------------------------------------------------------------*/ jj_cnt_diag = hypre_CTAlloc(HYPRE_Int, num_threads); jj_cnt_offd = hypre_CTAlloc(HYPRE_Int, num_threads); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,j,k,jcol,ii,ic,i1,i2,i3,jj1,jj2,jj3,ns,ne,size,rest,jj_count_diag,jj_count_offd,jj_row_begin_diag,jj_row_begin_offd,A_marker,P_marker) HYPRE_SMP_SCHEDULE #endif for (ii = 0; ii < num_threads; ii++) { size = num_cols_diag_RT/num_threads; rest = num_cols_diag_RT - size*num_threads; if (ii < rest) { ns = ii*size+ii; ne = (ii+1)*size+ii+1; } else { ns = ii*size+rest; ne = (ii+1)*size+rest; } P_mark_array[ii] = hypre_CTAlloc(HYPRE_Int, num_cols_diag_P+num_cols_offd_RAP); A_mark_array[ii] = hypre_CTAlloc(HYPRE_Int, num_nz_cols_A); P_marker = P_mark_array[ii]; A_marker = A_mark_array[ii]; jj_count_diag = start_indexing; jj_count_offd = start_indexing; for (ic = 0; ic < num_cols_diag_P+num_cols_offd_RAP; ic++) { P_marker[ic] = -1; } for (i = 0; i < num_nz_cols_A; i++) { A_marker[i] = -1; } /*----------------------------------------------------------------------- * Loop over interior c-points. *-----------------------------------------------------------------------*/ for (ic = ns; ic < ne; ic++) { /*-------------------------------------------------------------------- * Set marker for diagonal entry, RAP_{ic,ic}. and for all points * being added to row ic of RAP_diag and RAP_offd through RAP_ext *--------------------------------------------------------------------*/ jj_row_begin_diag = jj_count_diag; jj_row_begin_offd = jj_count_offd; if (square) P_marker[ic] = jj_count_diag++; #ifdef HYPRE_CONCURRENT_HOPSCOTCH if (send_map_elmts_RT_inverse_map_initialized) { HYPRE_Int i = hypre_UnorderedIntMapGet(&send_map_elmts_RT_inverse_map, ic); if (i != -1) { for (j = send_map_elmts_starts_RT_aggregated[i]; j < send_map_elmts_starts_RT_aggregated[i + 1]; j++) { HYPRE_Int jj = send_map_elmts_RT_aggregated[j]; for (k=RAP_ext_i[jj]; k < RAP_ext_i[jj+1]; k++) { jcol = RAP_ext_j[k]; if (jcol < num_cols_diag_P) { if (P_marker[jcol] < jj_row_begin_diag) { P_marker[jcol] = jj_count_diag; jj_count_diag++; } } else { if (P_marker[jcol] < jj_row_begin_offd) { P_marker[jcol] = jj_count_offd; jj_count_offd++; } } } } } // if (set) } #else /* !HYPRE_CONCURRENT_HOPSCOTCH */ for (i=0; i < num_sends_RT; i++) for (j = send_map_starts_RT[i]; j < send_map_starts_RT[i+1]; j++) if (send_map_elmts_RT[j] == ic) { for (k=RAP_ext_i[j]; k < RAP_ext_i[j+1]; k++) { jcol = RAP_ext_j[k]; if (jcol < num_cols_diag_P) { if (P_marker[jcol] < jj_row_begin_diag) { P_marker[jcol] = jj_count_diag; jj_count_diag++; } } else { if (P_marker[jcol] < jj_row_begin_offd) { P_marker[jcol] = jj_count_offd; jj_count_offd++; } } } break; } #endif /* !HYPRE_CONCURRENT_HOPSCOTCH */ /*-------------------------------------------------------------------- * Loop over entries in row ic of R_diag. *--------------------------------------------------------------------*/ for (jj1 = R_diag_i[ic]; jj1 < R_diag_i[ic+1]; jj1++) { i1 = R_diag_j[jj1]; /*----------------------------------------------------------------- * Loop over entries in row i1 of A_offd. *-----------------------------------------------------------------*/ if (num_cols_offd_A) { for (jj2 = A_offd_i[i1]; jj2 < A_offd_i[i1+1]; jj2++) { i2 = A_offd_j[jj2]; /*-------------------------------------------------------------- * Check A_marker to see if point i2 has been previously * visited. New entries in RAP only occur from unmarked points. *--------------------------------------------------------------*/ if (A_marker[i2] != ic) { /*----------------------------------------------------------- * Mark i2 as visited. *-----------------------------------------------------------*/ A_marker[i2] = ic; /*----------------------------------------------------------- * Loop over entries in row i2 of P_ext. *-----------------------------------------------------------*/ for (jj3 = P_ext_diag_i[i2]; jj3 < P_ext_diag_i[i2+1]; jj3++) { i3 = P_ext_diag_j[jj3]; /*-------------------------------------------------------- * Check P_marker to see that RAP_{ic,i3} has not already * been accounted for. If it has not, mark it and increment * counter. *--------------------------------------------------------*/ if (P_marker[i3] < jj_row_begin_diag) { P_marker[i3] = jj_count_diag; jj_count_diag++; } } for (jj3 = P_ext_offd_i[i2]; jj3 < P_ext_offd_i[i2+1]; jj3++) { i3 = map_Pext_to_RAP[P_ext_offd_j[jj3]]+num_cols_diag_P; /*-------------------------------------------------------- * Check P_marker to see that RAP_{ic,i3} has not already * been accounted for. If it has not, mark it and increment * counter. *--------------------------------------------------------*/ if (P_marker[i3] < jj_row_begin_offd) { P_marker[i3] = jj_count_offd; jj_count_offd++; } } } } } /*----------------------------------------------------------------- * Loop over entries in row i1 of A_diag. *-----------------------------------------------------------------*/ for (jj2 = A_diag_i[i1]; jj2 < A_diag_i[i1+1]; jj2++) { i2 = A_diag_j[jj2]; /*-------------------------------------------------------------- * Check A_marker to see if point i2 has been previously * visited. New entries in RAP only occur from unmarked points. *--------------------------------------------------------------*/ if (A_marker[i2+num_cols_offd_A] != ic) { /*----------------------------------------------------------- * Mark i2 as visited. *-----------------------------------------------------------*/ A_marker[i2+num_cols_offd_A] = ic; /*----------------------------------------------------------- * Loop over entries in row i2 of P_diag. *-----------------------------------------------------------*/ for (jj3 = P_diag_i[i2]; jj3 < P_diag_i[i2+1]; jj3++) { i3 = P_diag_j[jj3]; /*-------------------------------------------------------- * Check P_marker to see that RAP_{ic,i3} has not already * been accounted for. If it has not, mark it and increment * counter. *--------------------------------------------------------*/ if (P_marker[i3] < jj_row_begin_diag) { P_marker[i3] = jj_count_diag; jj_count_diag++; } } /*----------------------------------------------------------- * Loop over entries in row i2 of P_offd. *-----------------------------------------------------------*/ if (num_cols_offd_P) { for (jj3 = P_offd_i[i2]; jj3 < P_offd_i[i2+1]; jj3++) { i3 = map_P_to_RAP[P_offd_j[jj3]] + num_cols_diag_P; /*-------------------------------------------------------- * Check P_marker to see that RAP_{ic,i3} has not already * been accounted for. If it has not, mark it and increment * counter. *--------------------------------------------------------*/ if (P_marker[i3] < jj_row_begin_offd) { P_marker[i3] = jj_count_offd; jj_count_offd++; } } } } } } /*-------------------------------------------------------------------- * Set RAP_diag_i and RAP_offd_i for this row. *--------------------------------------------------------------------*/ /* RAP_diag_i[ic] = jj_row_begin_diag; RAP_offd_i[ic] = jj_row_begin_offd; */ } jj_cnt_diag[ii] = jj_count_diag; jj_cnt_offd[ii] = jj_count_offd; } for (i=0; i < num_threads-1; i++) { jj_cnt_diag[i+1] += jj_cnt_diag[i]; jj_cnt_offd[i+1] += jj_cnt_offd[i]; } jj_count_diag = jj_cnt_diag[num_threads-1]; jj_count_offd = jj_cnt_offd[num_threads-1]; RAP_diag_i[num_cols_diag_RT] = jj_count_diag; RAP_offd_i[num_cols_diag_RT] = jj_count_offd; /*----------------------------------------------------------------------- * Allocate RAP_diag_data and RAP_diag_j arrays. * Allocate RAP_offd_data and RAP_offd_j arrays. *-----------------------------------------------------------------------*/ RAP_diag_size = jj_count_diag; if (RAP_diag_size) { RAP_diag_data = hypre_CTAlloc(HYPRE_Real, RAP_diag_size); RAP_diag_j = hypre_CTAlloc(HYPRE_Int, RAP_diag_size); } RAP_offd_size = jj_count_offd; if (RAP_offd_size) { RAP_offd_data = hypre_CTAlloc(HYPRE_Real, RAP_offd_size); RAP_offd_j = hypre_CTAlloc(HYPRE_Int, RAP_offd_size); } if (RAP_offd_size == 0 && num_cols_offd_RAP != 0) { num_cols_offd_RAP = 0; hypre_TFree(col_map_offd_RAP); } RA_diag_data_array = hypre_TAlloc(HYPRE_Real, num_cols_diag_A*num_threads); RA_diag_j_array = hypre_TAlloc(HYPRE_Int, num_cols_diag_A*num_threads); if (num_cols_offd_A) { RA_offd_data_array = hypre_TAlloc(HYPRE_Real, num_cols_offd_A*num_threads); RA_offd_j_array = hypre_TAlloc(HYPRE_Int, num_cols_offd_A*num_threads); } /*----------------------------------------------------------------------- * Second Pass: Fill in RAP_diag_data and RAP_diag_j. * Second Pass: Fill in RAP_offd_data and RAP_offd_j. *-----------------------------------------------------------------------*/ #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,j,k,jcol,ii,ic,i1,i2,i3,jj1,jj2,jj3,ns,ne,size,rest,jj_count_diag,jj_count_offd,jj_row_begin_diag,jj_row_begin_offd,A_marker,P_marker,r_entry,r_a_product,r_a_p_product) HYPRE_SMP_SCHEDULE #endif for (ii = 0; ii < num_threads; ii++) { size = num_cols_diag_RT/num_threads; rest = num_cols_diag_RT - size*num_threads; if (ii < rest) { ns = ii*size+ii; ne = (ii+1)*size+ii+1; } else { ns = ii*size+rest; ne = (ii+1)*size+rest; } /*----------------------------------------------------------------------- * Initialize some stuff. *-----------------------------------------------------------------------*/ P_marker = P_mark_array[ii]; A_marker = A_mark_array[ii]; for (ic = 0; ic < num_cols_diag_P+num_cols_offd_RAP; ic++) { P_marker[ic] = -1; } for (i = 0; i < num_nz_cols_A ; i++) { A_marker[i] = -1; } jj_count_diag = start_indexing; jj_count_offd = start_indexing; if (ii > 0) { jj_count_diag = jj_cnt_diag[ii-1]; jj_count_offd = jj_cnt_offd[ii-1]; } // temporal matrix RA = R*A // only need to store one row per thread because R*A and (R*A)*P are fused // into one loop. hypre_CSRMatrix RA_diag, RA_offd; RA_diag.data = RA_diag_data_array + num_cols_diag_A*ii; RA_diag.j = RA_diag_j_array + num_cols_diag_A*ii; RA_diag.num_nonzeros = 0; RA_offd.num_nonzeros = 0; if (num_cols_offd_A) { RA_offd.data = RA_offd_data_array + num_cols_offd_A*ii; RA_offd.j = RA_offd_j_array + num_cols_offd_A*ii; } /*----------------------------------------------------------------------- * Loop over interior c-points. *-----------------------------------------------------------------------*/ for (ic = ns; ic < ne; ic++) { /*-------------------------------------------------------------------- * Create diagonal entry, RAP_{ic,ic} and add entries of RAP_ext *--------------------------------------------------------------------*/ jj_row_begin_diag = jj_count_diag; jj_row_begin_offd = jj_count_offd; RAP_diag_i[ic] = jj_row_begin_diag; RAP_offd_i[ic] = jj_row_begin_offd; HYPRE_Int ra_row_begin_diag = RA_diag.num_nonzeros; HYPRE_Int ra_row_begin_offd = RA_offd.num_nonzeros; if (square) { P_marker[ic] = jj_count_diag; RAP_diag_data[jj_count_diag] = zero; RAP_diag_j[jj_count_diag] = ic; jj_count_diag++; } #ifdef HYPRE_CONCURRENT_HOPSCOTCH if (send_map_elmts_RT_inverse_map_initialized) { HYPRE_Int i = hypre_UnorderedIntMapGet(&send_map_elmts_RT_inverse_map, ic); if (i != -1) { for (j = send_map_elmts_starts_RT_aggregated[i]; j < send_map_elmts_starts_RT_aggregated[i + 1]; j++) { HYPRE_Int jj = send_map_elmts_RT_aggregated[j]; for (k=RAP_ext_i[jj]; k < RAP_ext_i[jj+1]; k++) { jcol = RAP_ext_j[k]; if (jcol < num_cols_diag_P) { if (P_marker[jcol] < jj_row_begin_diag) { P_marker[jcol] = jj_count_diag; RAP_diag_data[jj_count_diag] = RAP_ext_data[k]; RAP_diag_j[jj_count_diag] = jcol; jj_count_diag++; } else RAP_diag_data[P_marker[jcol]] += RAP_ext_data[k]; } else { if (P_marker[jcol] < jj_row_begin_offd) { P_marker[jcol] = jj_count_offd; RAP_offd_data[jj_count_offd] = RAP_ext_data[k]; RAP_offd_j[jj_count_offd] = jcol-num_cols_diag_P; jj_count_offd++; } else RAP_offd_data[P_marker[jcol]] += RAP_ext_data[k]; } } } } // if (set) } #else /* !HYPRE_CONCURRENT_HOPSCOTCH */ for (i=0; i < num_sends_RT; i++) for (j = send_map_starts_RT[i]; j < send_map_starts_RT[i+1]; j++) if (send_map_elmts_RT[j] == ic) { for (k=RAP_ext_i[j]; k < RAP_ext_i[j+1]; k++) { jcol = RAP_ext_j[k]; if (jcol < num_cols_diag_P) { if (P_marker[jcol] < jj_row_begin_diag) { P_marker[jcol] = jj_count_diag; RAP_diag_data[jj_count_diag] = RAP_ext_data[k]; RAP_diag_j[jj_count_diag] = jcol; jj_count_diag++; } else RAP_diag_data[P_marker[jcol]] += RAP_ext_data[k]; } else { if (P_marker[jcol] < jj_row_begin_offd) { P_marker[jcol] = jj_count_offd; RAP_offd_data[jj_count_offd] = RAP_ext_data[k]; RAP_offd_j[jj_count_offd] = jcol-num_cols_diag_P; jj_count_offd++; } else RAP_offd_data[P_marker[jcol]] += RAP_ext_data[k]; } } break; } #endif /* !HYPRE_CONCURRENT_HOPSCOTCH */ /*-------------------------------------------------------------------- * Loop over entries in row ic of R_diag and compute row ic of RA. *--------------------------------------------------------------------*/ for (jj1 = R_diag_i[ic]; jj1 < R_diag_i[ic+1]; jj1++) { i1 = R_diag_j[jj1]; r_entry = R_diag_data[jj1]; /*----------------------------------------------------------------- * Loop over entries in row i1 of A_offd. *-----------------------------------------------------------------*/ if (num_cols_offd_A) { for (jj2 = A_offd_i[i1]; jj2 < A_offd_i[i1+1]; jj2++) { i2 = A_offd_j[jj2]; HYPRE_Real a_entry = A_offd_data[jj2]; HYPRE_Int marker = A_marker[i2]; /*-------------------------------------------------------------- * Check A_marker to see if point i2 has been previously * visited. New entries in RAP only occur from unmarked points. *--------------------------------------------------------------*/ if (marker < ra_row_begin_offd) { /*----------------------------------------------------------- * Mark i2 as visited. *-----------------------------------------------------------*/ A_marker[i2] = RA_offd.num_nonzeros; RA_offd.data[RA_offd.num_nonzeros - ra_row_begin_offd] = r_entry * a_entry; RA_offd.j[RA_offd.num_nonzeros - ra_row_begin_offd] = i2; RA_offd.num_nonzeros++; } /*-------------------------------------------------------------- * If i2 is previously visited ( A_marker[12]=ic ) it yields * no new entries in RA and can just add new contributions. *--------------------------------------------------------------*/ else { RA_offd.data[marker - ra_row_begin_offd] += r_entry * a_entry; // JSP: compiler will more likely to generate FMA instructions // when we don't eliminate common subexpressions of // r_entry * A_offd_data[jj2] manually. } } // loop over entries in row i1 of A_offd } // num_cols_offd_A /*----------------------------------------------------------------- * Loop over entries in row i1 of A_diag. *-----------------------------------------------------------------*/ for (jj2 = A_diag_i[i1]; jj2 < A_diag_i[i1+1]; jj2++) { i2 = A_diag_j[jj2]; HYPRE_Real a_entry = A_diag_data[jj2]; HYPRE_Int marker = A_marker[i2+num_cols_offd_A]; /*-------------------------------------------------------------- * Check A_marker to see if point i2 has been previously * visited. New entries in RAP only occur from unmarked points. *--------------------------------------------------------------*/ if (marker < ra_row_begin_diag) { /*----------------------------------------------------------- * Mark i2 as visited. *-----------------------------------------------------------*/ A_marker[i2+num_cols_offd_A] = RA_diag.num_nonzeros; RA_diag.data[RA_diag.num_nonzeros - ra_row_begin_diag] = r_entry * a_entry; RA_diag.j[RA_diag.num_nonzeros - ra_row_begin_diag] = i2; RA_diag.num_nonzeros++; } /*-------------------------------------------------------------- * If i2 is previously visited ( A_marker[12]=ic ) it yields * no new entries in RA and can just add new contributions. *--------------------------------------------------------------*/ else { RA_diag.data[marker - ra_row_begin_diag] += r_entry * a_entry; } } // loop over entries in row i1 of A_diag } // loop over entries in row ic of R_diag /*-------------------------------------------------------------------- * Loop over entries in row ic of RA_offd. *--------------------------------------------------------------------*/ for (jj1 = ra_row_begin_offd; jj1 < RA_offd.num_nonzeros; jj1++) { i1 = RA_offd.j[jj1 - ra_row_begin_offd]; r_a_product = RA_offd.data[jj1 - ra_row_begin_offd]; /*----------------------------------------------------------- * Loop over entries in row i1 of P_ext. *-----------------------------------------------------------*/ for (jj2 = P_ext_diag_i[i1]; jj2 < P_ext_diag_i[i1+1]; jj2++) { i2 = P_ext_diag_j[jj2]; HYPRE_Real p_entry = P_ext_diag_data[jj2]; HYPRE_Int marker = P_marker[i2]; /*-------------------------------------------------------- * Check P_marker to see that RAP_{ic,i2} has not already * been accounted for. If it has not, create a new entry. * If it has, add new contribution. *--------------------------------------------------------*/ if (marker < jj_row_begin_diag) { P_marker[i2] = jj_count_diag; RAP_diag_data[jj_count_diag] = r_a_product * p_entry; RAP_diag_j[jj_count_diag] = i2; jj_count_diag++; } else RAP_diag_data[marker] += r_a_product * p_entry; } for (jj2 = P_ext_offd_i[i1]; jj2 < P_ext_offd_i[i1+1]; jj2++) { i2 = map_Pext_to_RAP[P_ext_offd_j[jj2]] + num_cols_diag_P; HYPRE_Real p_entry = P_ext_offd_data[jj2]; HYPRE_Int marker = P_marker[i2]; /*-------------------------------------------------------- * Check P_marker to see that RAP_{ic,i2} has not already * been accounted for. If it has not, create a new entry. * If it has, add new contribution. *--------------------------------------------------------*/ if (marker < jj_row_begin_offd) { P_marker[i2] = jj_count_offd; RAP_offd_data[jj_count_offd] = r_a_product * p_entry; RAP_offd_j[jj_count_offd] = i2 - num_cols_diag_P; jj_count_offd++; } else RAP_offd_data[marker] += r_a_product * p_entry; } } // loop over entries in row ic of RA_offd /*-------------------------------------------------------------------- * Loop over entries in row ic of RA_diag. *--------------------------------------------------------------------*/ for (jj1 = ra_row_begin_diag; jj1 < RA_diag.num_nonzeros; jj1++) { HYPRE_Int i1 = RA_diag.j[jj1 - ra_row_begin_diag]; HYPRE_Real r_a_product = RA_diag.data[jj1 - ra_row_begin_diag]; /*----------------------------------------------------------------- * Loop over entries in row i1 of P_diag. *-----------------------------------------------------------------*/ for (jj2 = P_diag_i[i1]; jj2 < P_diag_i[i1+1]; jj2++) { i2 = P_diag_j[jj2]; HYPRE_Real p_entry = P_diag_data[jj2]; HYPRE_Int marker = P_marker[i2]; /*-------------------------------------------------------- * Check P_marker to see that RAP_{ic,i2} has not already * been accounted for. If it has not, create a new entry. * If it has, add new contribution. *--------------------------------------------------------*/ if (marker < jj_row_begin_diag) { P_marker[i2] = jj_count_diag; RAP_diag_data[jj_count_diag] = r_a_product * p_entry; RAP_diag_j[jj_count_diag] = i2; jj_count_diag++; } else { RAP_diag_data[marker] += r_a_product * p_entry; } } if (num_cols_offd_P) { for (jj2 = P_offd_i[i1]; jj2 < P_offd_i[i1+1]; jj2++) { i2 = map_P_to_RAP[P_offd_j[jj2]] + num_cols_diag_P; HYPRE_Real p_entry = P_offd_data[jj2]; HYPRE_Int marker = P_marker[i2]; /*-------------------------------------------------------- * Check P_marker to see that RAP_{ic,i2} has not already * been accounted for. If it has not, create a new entry. * If it has, add new contribution. *--------------------------------------------------------*/ if (marker < jj_row_begin_offd) { P_marker[i2] = jj_count_offd; RAP_offd_data[jj_count_offd] = r_a_product * p_entry; RAP_offd_j[jj_count_offd] = i2 - num_cols_diag_P; jj_count_offd++; } else { RAP_offd_data[marker] += r_a_product * p_entry; } } } // num_cols_offd_P } // loop over entries in row ic of RA_diag. } // Loop over interior c-points. hypre_TFree(P_mark_array[ii]); hypre_TFree(A_mark_array[ii]); } // omp parallel for /* check if really all off-diagonal entries occurring in col_map_offd_RAP are represented and eliminate if necessary */ P_marker = hypre_CTAlloc(HYPRE_Int,num_cols_offd_RAP); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for HYPRE_SMP_SCHEDULE #endif for (i=0; i < num_cols_offd_RAP; i++) P_marker[i] = -1; jj_count_offd = 0; #ifdef HYPRE_USING_ATOMIC #pragma omp parallel for private(i3) reduction(+:jj_count_offd) HYPRE_SMP_SCHEDULE #endif for (i=0; i < RAP_offd_size; i++) { i3 = RAP_offd_j[i]; #ifdef HYPRE_USING_ATOMIC if (hypre_compare_and_swap(P_marker + i3, -1, 0) == -1) { jj_count_offd++; } #else if (P_marker[i3]) { P_marker[i3] = 0; jj_count_offd++; } #endif } if (jj_count_offd < num_cols_offd_RAP) { new_col_map_offd_RAP = hypre_CTAlloc(HYPRE_Int,jj_count_offd); jj_counter = 0; for (i=0; i < num_cols_offd_RAP; i++) if (!P_marker[i]) { P_marker[i] = jj_counter; new_col_map_offd_RAP[jj_counter++] = col_map_offd_RAP[i]; } #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i3) HYPRE_SMP_SCHEDULE #endif for (i=0; i < RAP_offd_size; i++) { i3 = RAP_offd_j[i]; RAP_offd_j[i] = P_marker[i3]; } num_cols_offd_RAP = jj_count_offd; hypre_TFree(col_map_offd_RAP); col_map_offd_RAP = new_col_map_offd_RAP; } hypre_TFree(P_marker); RAP = hypre_ParCSRMatrixCreate(comm, n_coarse_RT, n_coarse, RT_partitioning, coarse_partitioning, num_cols_offd_RAP, RAP_diag_size, RAP_offd_size); /* Have RAP own coarse_partitioning instead of P */ hypre_ParCSRMatrixSetColStartsOwner(P,0); hypre_ParCSRMatrixSetColStartsOwner(RT,0); RAP_diag = hypre_ParCSRMatrixDiag(RAP); hypre_CSRMatrixI(RAP_diag) = RAP_diag_i; if (RAP_diag_size) { hypre_CSRMatrixData(RAP_diag) = RAP_diag_data; hypre_CSRMatrixJ(RAP_diag) = RAP_diag_j; } RAP_offd = hypre_ParCSRMatrixOffd(RAP); hypre_CSRMatrixI(RAP_offd) = RAP_offd_i; if (num_cols_offd_RAP) { hypre_CSRMatrixData(RAP_offd) = RAP_offd_data; hypre_CSRMatrixJ(RAP_offd) = RAP_offd_j; hypre_ParCSRMatrixColMapOffd(RAP) = col_map_offd_RAP; } if (num_procs > 1) { /* hypre_GenerateRAPCommPkg(RAP, A); */ hypre_MatvecCommPkgCreate(RAP); } *RAP_ptr = RAP; /*----------------------------------------------------------------------- * Free R, P_ext and marker arrays. *-----------------------------------------------------------------------*/ if (keepTranspose) { hypre_ParCSRMatrixDiagT(RT) = R_diag; } else { hypre_CSRMatrixDestroy(R_diag); } R_diag = NULL; if (num_cols_offd_RT) { if (keepTranspose) { hypre_ParCSRMatrixOffdT(RT) = R_offd; } else { hypre_CSRMatrixDestroy(R_offd); } R_offd = NULL; } if (num_sends_RT || num_recvs_RT) { hypre_CSRMatrixDestroy(RAP_ext); RAP_ext = NULL; } hypre_TFree(P_mark_array); hypre_TFree(A_mark_array); hypre_TFree(P_ext_diag_i); hypre_TFree(P_ext_offd_i); hypre_TFree(jj_cnt_diag); hypre_TFree(jj_cnt_offd); if (num_cols_offd_P) { hypre_TFree(map_P_to_Pext); hypre_TFree(map_P_to_RAP); } if (num_cols_offd_Pext) { hypre_TFree(col_map_offd_Pext); hypre_TFree(map_Pext_to_RAP); } if (P_ext_diag_size) { hypre_TFree(P_ext_diag_data); hypre_TFree(P_ext_diag_j); } if (P_ext_offd_size) { hypre_TFree(P_ext_offd_data); hypre_TFree(P_ext_offd_j); } hypre_TFree(RA_diag_data_array); hypre_TFree(RA_diag_j_array); if (num_cols_offd_A) { hypre_TFree(RA_offd_data_array); hypre_TFree(RA_offd_j_array); } #ifdef HYPRE_CONCURRENT_HOPSCOTCH if (send_map_elmts_RT_inverse_map_initialized) { hypre_UnorderedIntMapDestroy(&send_map_elmts_RT_inverse_map); } hypre_TFree(send_map_elmts_starts_RT_aggregated); hypre_TFree(send_map_elmts_RT_aggregated); #endif #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_RAP] += hypre_MPI_Wtime(); #endif return(0); }
82,221
36.356656
222
c
AMG
AMG-master/parcsr_ls/par_rap_communication.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ #include "_hypre_parcsr_ls.h" HYPRE_Int hypre_GetCommPkgRTFromCommPkgA( hypre_ParCSRMatrix *RT, hypre_ParCSRMatrix *A, HYPRE_Int *fine_to_coarse_offd) { MPI_Comm comm = hypre_ParCSRMatrixComm(RT); hypre_ParCSRCommPkg *comm_pkg_A = hypre_ParCSRMatrixCommPkg(A); HYPRE_Int num_recvs_A = hypre_ParCSRCommPkgNumRecvs(comm_pkg_A); HYPRE_Int *recv_procs_A = hypre_ParCSRCommPkgRecvProcs(comm_pkg_A); HYPRE_Int *recv_vec_starts_A = hypre_ParCSRCommPkgRecvVecStarts(comm_pkg_A); HYPRE_Int num_sends_A = hypre_ParCSRCommPkgNumSends(comm_pkg_A); HYPRE_Int *send_procs_A = hypre_ParCSRCommPkgSendProcs(comm_pkg_A); hypre_ParCSRCommPkg *comm_pkg; HYPRE_Int num_recvs_RT; HYPRE_Int *recv_procs_RT; HYPRE_Int *recv_vec_starts_RT; HYPRE_Int num_sends_RT; HYPRE_Int *send_procs_RT; HYPRE_Int *send_map_starts_RT; HYPRE_Int *send_map_elmts_RT; HYPRE_Int *col_map_offd_RT = hypre_ParCSRMatrixColMapOffd(RT); HYPRE_Int num_cols_offd_RT = hypre_CSRMatrixNumCols( hypre_ParCSRMatrixOffd(RT)); HYPRE_Int first_col_diag = hypre_ParCSRMatrixFirstColDiag(RT); HYPRE_Int i, j; HYPRE_Int vec_len, vec_start; HYPRE_Int num_procs, my_id; HYPRE_Int ierr = 0; HYPRE_Int num_requests; HYPRE_Int offd_col, proc_num; HYPRE_Int *proc_mark; HYPRE_Int *change_array; hypre_MPI_Request *requests; hypre_MPI_Status *status; hypre_MPI_Comm_size(comm,&num_procs); hypre_MPI_Comm_rank(comm,&my_id); /*-------------------------------------------------------------------------- * determine num_recvs, recv_procs and recv_vec_starts for RT *--------------------------------------------------------------------------*/ proc_mark = hypre_CTAlloc(HYPRE_Int, num_recvs_A); for (i=0; i < num_recvs_A; i++) proc_mark[i] = 0; proc_num = 0; num_recvs_RT = 0; if (num_cols_offd_RT) { for (i=0; i < num_recvs_A; i++) { for (j=recv_vec_starts_A[i]; j<recv_vec_starts_A[i+1]; j++) { offd_col = col_map_offd_RT[proc_num]; if (offd_col == j) { proc_mark[i]++; proc_num++; if (proc_num == num_cols_offd_RT) break; } } if (proc_mark[i]) num_recvs_RT++; if (proc_num == num_cols_offd_RT) break; } } for (i=0; i < num_cols_offd_RT; i++) col_map_offd_RT[i] = fine_to_coarse_offd[col_map_offd_RT[i]]; recv_procs_RT = hypre_CTAlloc(HYPRE_Int,num_recvs_RT); recv_vec_starts_RT = hypre_CTAlloc(HYPRE_Int, num_recvs_RT+1); j = 0; recv_vec_starts_RT[0] = 0; for (i=0; i < num_recvs_A; i++) if (proc_mark[i]) { recv_procs_RT[j] = recv_procs_A[i]; recv_vec_starts_RT[j+1] = recv_vec_starts_RT[j]+proc_mark[i]; j++; } /*-------------------------------------------------------------------------- * send num_changes to recv_procs_A and receive change_array from send_procs_A *--------------------------------------------------------------------------*/ num_requests = num_recvs_A+num_sends_A; requests = hypre_CTAlloc(hypre_MPI_Request, num_requests); status = hypre_CTAlloc(hypre_MPI_Status, num_requests); change_array = hypre_CTAlloc(HYPRE_Int, num_sends_A); j = 0; for (i=0; i < num_sends_A; i++) hypre_MPI_Irecv(&change_array[i],1,HYPRE_MPI_INT,send_procs_A[i],0,comm, &requests[j++]); for (i=0; i < num_recvs_A; i++) hypre_MPI_Isend(&proc_mark[i],1,HYPRE_MPI_INT,recv_procs_A[i],0,comm, &requests[j++]); hypre_MPI_Waitall(num_requests,requests,status); hypre_TFree(proc_mark); /*-------------------------------------------------------------------------- * if change_array[i] is 0 , omit send_procs_A[i] in send_procs_RT *--------------------------------------------------------------------------*/ num_sends_RT = 0; for (i=0; i < num_sends_A; i++) if (change_array[i]) { num_sends_RT++; } send_procs_RT = hypre_CTAlloc(HYPRE_Int, num_sends_RT); send_map_starts_RT = hypre_CTAlloc(HYPRE_Int, num_sends_RT+1); j = 0; send_map_starts_RT[0] = 0; for (i=0; i < num_sends_A; i++) if (change_array[i]) { send_procs_RT[j] = send_procs_A[i]; send_map_starts_RT[j+1] = send_map_starts_RT[j]+change_array[i]; j++; } /*-------------------------------------------------------------------------- * generate send_map_elmts *--------------------------------------------------------------------------*/ send_map_elmts_RT = hypre_CTAlloc(HYPRE_Int,send_map_starts_RT[num_sends_RT]); j = 0; for (i=0; i < num_sends_RT; i++) { vec_start = send_map_starts_RT[i]; vec_len = send_map_starts_RT[i+1]-vec_start; hypre_MPI_Irecv(&send_map_elmts_RT[vec_start],vec_len,HYPRE_MPI_INT, send_procs_RT[i],0,comm,&requests[j++]); } for (i=0; i < num_recvs_RT; i++) { vec_start = recv_vec_starts_RT[i]; vec_len = recv_vec_starts_RT[i+1] - vec_start; hypre_MPI_Isend(&col_map_offd_RT[vec_start],vec_len,HYPRE_MPI_INT, recv_procs_RT[i],0,comm,&requests[j++]); } hypre_MPI_Waitall(j,requests,status); for (i=0; i < send_map_starts_RT[num_sends_RT]; i++) send_map_elmts_RT[i] -= first_col_diag; comm_pkg = hypre_CTAlloc(hypre_ParCSRCommPkg,1); hypre_ParCSRCommPkgComm(comm_pkg) = comm; hypre_ParCSRCommPkgNumSends(comm_pkg) = num_sends_RT; hypre_ParCSRCommPkgNumRecvs(comm_pkg) = num_recvs_RT; hypre_ParCSRCommPkgSendProcs(comm_pkg) = send_procs_RT; hypre_ParCSRCommPkgRecvProcs(comm_pkg) = recv_procs_RT; hypre_ParCSRCommPkgRecvVecStarts(comm_pkg) = recv_vec_starts_RT; hypre_ParCSRCommPkgSendMapStarts(comm_pkg) = send_map_starts_RT; hypre_ParCSRCommPkgSendMapElmts(comm_pkg) = send_map_elmts_RT; hypre_TFree(status); hypre_TFree(requests); hypre_ParCSRMatrixCommPkg(RT) = comm_pkg; hypre_TFree(change_array); return ierr; } HYPRE_Int hypre_GenerateSendMapAndCommPkg(MPI_Comm comm, HYPRE_Int num_sends, HYPRE_Int num_recvs, HYPRE_Int *recv_procs, HYPRE_Int *send_procs, HYPRE_Int *recv_vec_starts, hypre_ParCSRMatrix *A) { HYPRE_Int *send_map_starts; HYPRE_Int *send_map_elmts; HYPRE_Int i, j; HYPRE_Int num_requests = num_sends+num_recvs; hypre_MPI_Request *requests; hypre_MPI_Status *status; HYPRE_Int vec_len, vec_start; hypre_ParCSRCommPkg *comm_pkg; HYPRE_Int *col_map_offd = hypre_ParCSRMatrixColMapOffd(A); HYPRE_Int first_col_diag = hypre_ParCSRMatrixFirstColDiag(A); /*-------------------------------------------------------------------------- * generate send_map_starts and send_map_elmts *--------------------------------------------------------------------------*/ requests = hypre_CTAlloc(hypre_MPI_Request,num_requests); status = hypre_CTAlloc(hypre_MPI_Status,num_requests); send_map_starts = hypre_CTAlloc(HYPRE_Int, num_sends+1); j = 0; for (i=0; i < num_sends; i++) hypre_MPI_Irecv(&send_map_starts[i+1],1,HYPRE_MPI_INT,send_procs[i],0,comm, &requests[j++]); for (i=0; i < num_recvs; i++) { vec_len = recv_vec_starts[i+1] - recv_vec_starts[i]; hypre_MPI_Isend(&vec_len,1,HYPRE_MPI_INT, recv_procs[i],0,comm,&requests[j++]); } hypre_MPI_Waitall(j,requests,status); send_map_starts[0] = 0; for (i=0; i < num_sends; i++) send_map_starts[i+1] += send_map_starts[i]; send_map_elmts = hypre_CTAlloc(HYPRE_Int,send_map_starts[num_sends]); j = 0; for (i=0; i < num_sends; i++) { vec_start = send_map_starts[i]; vec_len = send_map_starts[i+1]-vec_start; hypre_MPI_Irecv(&send_map_elmts[vec_start],vec_len,HYPRE_MPI_INT, send_procs[i],0,comm,&requests[j++]); } for (i=0; i < num_recvs; i++) { vec_start = recv_vec_starts[i]; vec_len = recv_vec_starts[i+1] - vec_start; hypre_MPI_Isend(&col_map_offd[vec_start],vec_len,HYPRE_MPI_INT, recv_procs[i],0,comm,&requests[j++]); } hypre_MPI_Waitall(j,requests,status); for (i=0; i < send_map_starts[num_sends]; i++) send_map_elmts[i] -= first_col_diag; comm_pkg = hypre_CTAlloc(hypre_ParCSRCommPkg,1); hypre_ParCSRCommPkgComm(comm_pkg) = comm; hypre_ParCSRCommPkgNumSends(comm_pkg) = num_sends; hypre_ParCSRCommPkgNumRecvs(comm_pkg) = num_recvs; hypre_ParCSRCommPkgSendProcs(comm_pkg) = send_procs; hypre_ParCSRCommPkgRecvProcs(comm_pkg) = recv_procs; hypre_ParCSRCommPkgRecvVecStarts(comm_pkg) = recv_vec_starts; hypre_ParCSRCommPkgSendMapStarts(comm_pkg) = send_map_starts; hypre_ParCSRCommPkgSendMapElmts(comm_pkg) = send_map_elmts; hypre_TFree(status); hypre_TFree(requests); hypre_ParCSRMatrixCommPkg(A) = comm_pkg; return 0; }
9,654
32.641115
88
c
AMG
AMG-master/parcsr_ls/par_relax.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /****************************************************************************** * * Relaxation scheme * *****************************************************************************/ #include "_hypre_parcsr_ls.h" /*-------------------------------------------------------------------------- * hypre_BoomerAMGRelax *--------------------------------------------------------------------------*/ HYPRE_Int hypre_BoomerAMGRelax( hypre_ParCSRMatrix *A, hypre_ParVector *f, HYPRE_Int *cf_marker, HYPRE_Int relax_type, HYPRE_Int relax_points, HYPRE_Real relax_weight, HYPRE_Real omega, HYPRE_Real *l1_norms, hypre_ParVector *u, hypre_ParVector *Vtemp, hypre_ParVector *Ztemp ) { MPI_Comm comm = hypre_ParCSRMatrixComm(A); hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); HYPRE_Real *A_diag_data = hypre_CSRMatrixData(A_diag); HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag); HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag); hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd); HYPRE_Real *A_offd_data = hypre_CSRMatrixData(A_offd); HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd); hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A); hypre_ParCSRCommHandle *comm_handle; HYPRE_Int n_global= hypre_ParCSRMatrixGlobalNumRows(A); HYPRE_Int n = hypre_CSRMatrixNumRows(A_diag); HYPRE_Int num_cols_offd = hypre_CSRMatrixNumCols(A_offd); HYPRE_Int first_index = hypre_ParVectorFirstIndex(u); hypre_Vector *u_local = hypre_ParVectorLocalVector(u); HYPRE_Real *u_data = hypre_VectorData(u_local); hypre_Vector *f_local = hypre_ParVectorLocalVector(f); HYPRE_Real *f_data = hypre_VectorData(f_local); hypre_Vector *Vtemp_local = hypre_ParVectorLocalVector(Vtemp); HYPRE_Real *Vtemp_data = hypre_VectorData(Vtemp_local); HYPRE_Real *Vext_data = NULL; HYPRE_Real *v_buf_data; HYPRE_Real *tmp_data; hypre_Vector *Ztemp_local; HYPRE_Real *Ztemp_data; hypre_CSRMatrix *A_CSR; HYPRE_Int *A_CSR_i; HYPRE_Int *A_CSR_j; HYPRE_Real *A_CSR_data; hypre_Vector *f_vector; HYPRE_Real *f_vector_data; HYPRE_Int i, j, jr; HYPRE_Int ii, jj; HYPRE_Int ns, ne, size, rest; HYPRE_Int column; HYPRE_Int relax_error = 0; HYPRE_Int num_sends; HYPRE_Int num_recvs; HYPRE_Int index, start; HYPRE_Int num_procs, num_threads, my_id, ip, p; HYPRE_Int vec_start, vec_len; hypre_MPI_Status *status; hypre_MPI_Request *requests; HYPRE_Real *A_mat; HYPRE_Real *b_vec; HYPRE_Real zero = 0.0; HYPRE_Real res, res0, res2; HYPRE_Real one_minus_weight; HYPRE_Real one_minus_omega; HYPRE_Real prod; one_minus_weight = 1.0 - relax_weight; one_minus_omega = 1.0 - omega; hypre_MPI_Comm_size(comm,&num_procs); hypre_MPI_Comm_rank(comm,&my_id); num_threads = hypre_NumThreads(); /*----------------------------------------------------------------------- * Switch statement to direct control based on relax_type: * relax_type = 0 -> Jacobi or CF-Jacobi * relax_type = 1 -> Gauss-Seidel <--- very slow, sequential * relax_type = 2 -> Gauss_Seidel: interior points in parallel , * boundary sequential * relax_type = 3 -> hybrid: SOR-J mix off-processor, SOR on-processor * with outer relaxation parameters (forward solve) * relax_type = 4 -> hybrid: SOR-J mix off-processor, SOR on-processor * with outer relaxation parameters (backward solve) * relax_type = 5 -> hybrid: GS-J mix off-processor, chaotic GS on-node * relax_type = 6 -> hybrid: SSOR-J mix off-processor, SSOR on-processor * with outer relaxation parameters * relax_type = 7 -> Jacobi (uses Matvec), only needed in CGNR * relax_type = 19-> Direct Solve, (old version) * relax_type = 29-> Direct solve: use gaussian elimination & BLAS * (with pivoting) (old version) *-----------------------------------------------------------------------*/ switch (relax_type) { case 0: /* Weighted Jacobi */ { if (num_procs > 1) { num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); v_buf_data = hypre_CTAlloc(HYPRE_Real, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends)); Vext_data = hypre_CTAlloc(HYPRE_Real,num_cols_offd); if (num_cols_offd) { A_offd_j = hypre_CSRMatrixJ(A_offd); A_offd_data = hypre_CSRMatrixData(A_offd); } index = 0; for (i = 0; i < num_sends; i++) { start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j=start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++) v_buf_data[index++] = u_data[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)]; } comm_handle = hypre_ParCSRCommHandleCreate( 1, comm_pkg, v_buf_data, Vext_data); } /*----------------------------------------------------------------- * Copy current approximation into temporary vector. *-----------------------------------------------------------------*/ #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) { Vtemp_data[i] = u_data[i]; } if (num_procs > 1) { hypre_ParCSRCommHandleDestroy(comm_handle); comm_handle = NULL; } /*----------------------------------------------------------------- * Relax all points. *-----------------------------------------------------------------*/ if (relax_points == 0) { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,ii,jj,res) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (A_diag_data[A_diag_i[i]] != zero) { res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res -= A_diag_data[jj] * Vtemp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] *= one_minus_weight; u_data[i] += relax_weight * res / A_diag_data[A_diag_i[i]]; } } } /*----------------------------------------------------------------- * Relax only C or F points as determined by relax_points. *-----------------------------------------------------------------*/ else { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,ii,jj,res) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && A_diag_data[A_diag_i[i]] != zero) { res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res -= A_diag_data[jj] * Vtemp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] *= one_minus_weight; u_data[i] += relax_weight * res / A_diag_data[A_diag_i[i]]; } } } if (num_procs > 1) { hypre_TFree(Vext_data); hypre_TFree(v_buf_data); } } break; case 5: /* Hybrid: Jacobi off-processor, chaotic Gauss-Seidel on-processor */ { if (num_procs > 1) { num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); v_buf_data = hypre_CTAlloc(HYPRE_Real, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends)); Vext_data = hypre_CTAlloc(HYPRE_Real,num_cols_offd); if (num_cols_offd) { A_offd_j = hypre_CSRMatrixJ(A_offd); A_offd_data = hypre_CSRMatrixData(A_offd); } index = 0; for (i = 0; i < num_sends; i++) { start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j=start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg,i+1); j++) v_buf_data[index++] = u_data[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)]; } comm_handle = hypre_ParCSRCommHandleCreate( 1, comm_pkg, v_buf_data, Vext_data); /*----------------------------------------------------------------- * Copy current approximation into temporary vector. *-----------------------------------------------------------------*/ hypre_ParCSRCommHandleDestroy(comm_handle); comm_handle = NULL; } /*----------------------------------------------------------------- * Relax all points. *-----------------------------------------------------------------*/ if (relax_points == 0) { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,ii,jj,res) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) /* interior points first */ { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( A_diag_data[A_diag_i[i]] != zero) { res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res -= A_diag_data[jj] * u_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] = res / A_diag_data[A_diag_i[i]]; } } } /*----------------------------------------------------------------- * Relax only C or F points as determined by relax_points. *-----------------------------------------------------------------*/ else { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,ii,jj,res) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) /* relax interior points */ { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && A_diag_data[A_diag_i[i]] != zero) { res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res -= A_diag_data[jj] * u_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] = res / A_diag_data[A_diag_i[i]]; } } } if (num_procs > 1) { hypre_TFree(Vext_data); hypre_TFree(v_buf_data); } } break; case 3: /* Hybrid: Jacobi off-processor, Gauss-Seidel on-processor (forward loop) */ { if (num_threads > 1) { Ztemp_local = hypre_ParVectorLocalVector(Ztemp); Ztemp_data = hypre_VectorData(Ztemp_local); } #ifdef HYPRE_USING_PERSISTENT_COMM // JSP: persistent comm can be similarly used for other smoothers hypre_ParCSRPersistentCommHandle *persistent_comm_handle; #endif if (num_procs > 1) { #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_PACK_UNPACK] -= hypre_MPI_Wtime(); #endif num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); #ifdef HYPRE_USING_PERSISTENT_COMM persistent_comm_handle = hypre_ParCSRCommPkgGetPersistentCommHandle(1, comm_pkg); v_buf_data = (HYPRE_Real *)persistent_comm_handle->send_data; Vext_data = (HYPRE_Real *)persistent_comm_handle->recv_data; #else v_buf_data = hypre_CTAlloc(HYPRE_Real, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends)); Vext_data = hypre_CTAlloc(HYPRE_Real,num_cols_offd); #endif if (num_cols_offd) { A_offd_j = hypre_CSRMatrixJ(A_offd); A_offd_data = hypre_CSRMatrixData(A_offd); } HYPRE_Int begin = hypre_ParCSRCommPkgSendMapStart(comm_pkg, 0); HYPRE_Int end = hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for HYPRE_SMP_SCHEDULE #endif for (i = begin; i < end; i++) { v_buf_data[i - begin] = u_data[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,i)]; } #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_PACK_UNPACK] += hypre_MPI_Wtime(); hypre_profile_times[HYPRE_TIMER_ID_HALO_EXCHANGE] -= hypre_MPI_Wtime(); #endif #ifdef HYPRE_USING_PERSISTENT_COMM hypre_ParCSRPersistentCommHandleStart(persistent_comm_handle); #else comm_handle = hypre_ParCSRCommHandleCreate( 1, comm_pkg, v_buf_data, Vext_data); #endif /*----------------------------------------------------------------- * Copy current approximation into temporary vector. *-----------------------------------------------------------------*/ #ifdef HYPRE_USING_PERSISTENT_COMM hypre_ParCSRPersistentCommHandleWait(persistent_comm_handle); #else hypre_ParCSRCommHandleDestroy(comm_handle); #endif comm_handle = NULL; #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_HALO_EXCHANGE] += hypre_MPI_Wtime(); #endif } /*----------------------------------------------------------------- * Relax all points. *-----------------------------------------------------------------*/ #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_RELAX] -= hypre_MPI_Wtime(); #endif if (relax_weight == 1 && omega == 1) { if (relax_points == 0) { if (num_threads > 1) { tmp_data = Ztemp_data; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) tmp_data[i] = u_data[i]; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,ii,j,jj,ns,ne,res,rest,size) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < num_threads; j++) { size = n/num_threads; rest = n - size*num_threads; if (j < rest) { ns = j*size+j; ne = (j+1)*size+j+1; } else { ns = j*size+rest; ne = (j+1)*size+rest; } for (i = ns; i < ne; i++) /* interior points first */ { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( A_diag_data[A_diag_i[i]] != zero) { res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; if (ii >= ns && ii < ne) res -= A_diag_data[jj] * u_data[ii]; else res -= A_diag_data[jj] * tmp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] = res / A_diag_data[A_diag_i[i]]; } } } } else { for (i = 0; i < n; i++) /* interior points first */ { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( A_diag_data[A_diag_i[i]] != zero) { res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res -= A_diag_data[jj] * u_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] = res / A_diag_data[A_diag_i[i]]; } } } } /*----------------------------------------------------------------- * Relax only C or F points as determined by relax_points. *-----------------------------------------------------------------*/ else { if (num_threads > 1) { tmp_data = Ztemp_data; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) tmp_data[i] = u_data[i]; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,ii,j,jj,ns,ne,res,rest,size) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < num_threads; j++) { size = n/num_threads; rest = n - size*num_threads; if (j < rest) { ns = j*size+j; ne = (j+1)*size+j+1; } else { ns = j*size+rest; ne = (j+1)*size+rest; } for (i = ns; i < ne; i++) /* relax interior points */ { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && A_diag_data[A_diag_i[i]] != zero) { res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; if (ii >= ns && ii < ne) res -= A_diag_data[jj] * u_data[ii]; else res -= A_diag_data[jj] * tmp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] = res / A_diag_data[A_diag_i[i]]; } } } } else { for (i = 0; i < n; i++) /* relax interior points */ { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && A_diag_data[A_diag_i[i]] != zero) { res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res -= A_diag_data[jj] * u_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] = res / A_diag_data[A_diag_i[i]]; } } } } } else { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) { Vtemp_data[i] = u_data[i]; } prod = (1.0-relax_weight*omega); if (relax_points == 0) { if (num_threads > 1) { tmp_data = Ztemp_data; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) tmp_data[i] = u_data[i]; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,ii,j,jj,ns,ne,res,rest,size) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < num_threads; j++) { size = n/num_threads; rest = n - size*num_threads; if (j < rest) { ns = j*size+j; ne = (j+1)*size+j+1; } else { ns = j*size+rest; ne = (j+1)*size+rest; } for (i = ns; i < ne; i++) /* interior points first */ { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( A_diag_data[A_diag_i[i]] != zero) { res = f_data[i]; res0 = 0.0; res2 = 0.0; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; if (ii >= ns && ii < ne) { res0 -= A_diag_data[jj] * u_data[ii]; res2 += A_diag_data[jj] * Vtemp_data[ii]; } else res -= A_diag_data[jj] * tmp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] *= prod; u_data[i] += relax_weight*(omega*res + res0 + one_minus_omega*res2) / A_diag_data[A_diag_i[i]]; /*u_data[i] += omega*(relax_weight*res + res0 + one_minus_weight*res2) / A_diag_data[A_diag_i[i]];*/ } } } } else { for (i = 0; i < n; i++) /* interior points first */ { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( A_diag_data[A_diag_i[i]] != zero) { res0 = 0.0; res2 = 0.0; res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res0 -= A_diag_data[jj] * u_data[ii]; res2 += A_diag_data[jj] * Vtemp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] *= prod; u_data[i] += relax_weight*(omega*res + res0 + one_minus_omega*res2) / A_diag_data[A_diag_i[i]]; /*u_data[i] += omega*(relax_weight*res + res0 + one_minus_weight*res2) / A_diag_data[A_diag_i[i]];*/ } } } } /*----------------------------------------------------------------- * Relax only C or F points as determined by relax_points. *-----------------------------------------------------------------*/ else { if (num_threads > 1) { tmp_data = Ztemp_data; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) tmp_data[i] = u_data[i]; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,ii,j,jj,ns,ne,res,rest,size) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < num_threads; j++) { size = n/num_threads; rest = n - size*num_threads; if (j < rest) { ns = j*size+j; ne = (j+1)*size+j+1; } else { ns = j*size+rest; ne = (j+1)*size+rest; } for (i = ns; i < ne; i++) /* relax interior points */ { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && A_diag_data[A_diag_i[i]] != zero) { res0 = 0.0; res2 = 0.0; res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; if (ii >= ns && ii < ne) { res0 -= A_diag_data[jj] * u_data[ii]; res2 += A_diag_data[jj] * Vtemp_data[ii]; } else res -= A_diag_data[jj] * tmp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] *= prod; u_data[i] += relax_weight*(omega*res + res0 + one_minus_omega*res2) / A_diag_data[A_diag_i[i]]; /*u_data[i] += omega*(relax_weight*res + res0 + one_minus_weight*res2) / A_diag_data[A_diag_i[i]];*/ } } } } else { for (i = 0; i < n; i++) /* relax interior points */ { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && A_diag_data[A_diag_i[i]] != zero) { res = f_data[i]; res0 = 0.0; res2 = 0.0; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res0 -= A_diag_data[jj] * u_data[ii]; res2 += A_diag_data[jj] * Vtemp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] *= prod; u_data[i] += relax_weight*(omega*res + res0 + one_minus_omega*res2) / A_diag_data[A_diag_i[i]]; /*u_data[i] += omega*(relax_weight*res + res0 + one_minus_weight*res2) / A_diag_data[A_diag_i[i]];*/ } } } } } #ifndef HYPRE_USING_PERSISTENT_COMM if (num_procs > 1) { hypre_TFree(Vext_data); hypre_TFree(v_buf_data); } #endif #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_RELAX] += hypre_MPI_Wtime(); #endif } break; case 1: /* Gauss-Seidel VERY SLOW */ { if (num_procs > 1) { num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); num_recvs = hypre_ParCSRCommPkgNumRecvs(comm_pkg); v_buf_data = hypre_CTAlloc(HYPRE_Real, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends)); Vext_data = hypre_CTAlloc(HYPRE_Real,num_cols_offd); status = hypre_CTAlloc(hypre_MPI_Status,num_recvs+num_sends); requests= hypre_CTAlloc(hypre_MPI_Request, num_recvs+num_sends); if (num_cols_offd) { A_offd_j = hypre_CSRMatrixJ(A_offd); A_offd_data = hypre_CSRMatrixData(A_offd); } /*----------------------------------------------------------------- * Copy current approximation into temporary vector. *-----------------------------------------------------------------*/ /* for (i = 0; i < n; i++) { Vtemp_data[i] = u_data[i]; } */ } /*----------------------------------------------------------------- * Relax all points. *-----------------------------------------------------------------*/ for (p = 0; p < num_procs; p++) { jr = 0; if (p != my_id) { for (i = 0; i < num_sends; i++) { ip = hypre_ParCSRCommPkgSendProc(comm_pkg, i); if (ip == p) { vec_start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); vec_len = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1)-vec_start; for (j=vec_start; j < vec_start+vec_len; j++) v_buf_data[j] = u_data[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)]; hypre_MPI_Isend(&v_buf_data[vec_start], vec_len, HYPRE_MPI_REAL, ip, 0, comm, &requests[jr++]); } } hypre_MPI_Waitall(jr,requests,status); hypre_MPI_Barrier(comm); } else { if (num_procs > 1) { for (i = 0; i < num_recvs; i++) { ip = hypre_ParCSRCommPkgRecvProc(comm_pkg, i); vec_start = hypre_ParCSRCommPkgRecvVecStart(comm_pkg,i); vec_len = hypre_ParCSRCommPkgRecvVecStart(comm_pkg,i+1)-vec_start; hypre_MPI_Irecv(&Vext_data[vec_start], vec_len, HYPRE_MPI_REAL, ip, 0, comm, &requests[jr++]); } hypre_MPI_Waitall(jr,requests,status); } if (relax_points == 0) { for (i = 0; i < n; i++) { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( A_diag_data[A_diag_i[i]] != zero) { res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res -= A_diag_data[jj] * u_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] = res / A_diag_data[A_diag_i[i]]; } } } /*----------------------------------------------------------------- * Relax only C or F points as determined by relax_points. *-----------------------------------------------------------------*/ else { for (i = 0; i < n; i++) { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && A_diag_data[A_diag_i[i]] != zero) { res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res -= A_diag_data[jj] * u_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] = res / A_diag_data[A_diag_i[i]]; } } } if (num_procs > 1) hypre_MPI_Barrier(comm); } } if (num_procs > 1) { hypre_TFree(Vext_data); hypre_TFree(v_buf_data); hypre_TFree(status); hypre_TFree(requests); } } break; case 2: /* Gauss-Seidel: relax interior points in parallel, boundary sequentially */ { if (num_procs > 1) { num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); num_recvs = hypre_ParCSRCommPkgNumRecvs(comm_pkg); v_buf_data = hypre_CTAlloc(HYPRE_Real, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends)); Vext_data = hypre_CTAlloc(HYPRE_Real,num_cols_offd); status = hypre_CTAlloc(hypre_MPI_Status,num_recvs+num_sends); requests= hypre_CTAlloc(hypre_MPI_Request, num_recvs+num_sends); if (num_cols_offd) { A_offd_j = hypre_CSRMatrixJ(A_offd); A_offd_data = hypre_CSRMatrixData(A_offd); } } /*----------------------------------------------------------------- * Copy current approximation into temporary vector. *-----------------------------------------------------------------*/ /* for (i = 0; i < n; i++) { Vtemp_data[i] = u_data[i]; } */ /*----------------------------------------------------------------- * Relax interior points first *-----------------------------------------------------------------*/ if (relax_points == 0) { for (i = 0; i < n; i++) { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ((A_offd_i[i+1]-A_offd_i[i]) == zero && A_diag_data[A_diag_i[i]] != zero) { res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res -= A_diag_data[jj] * u_data[ii]; } u_data[i] = res / A_diag_data[A_diag_i[i]]; } } } else { for (i = 0; i < n; i++) { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && (A_offd_i[i+1]-A_offd_i[i]) == zero && A_diag_data[A_diag_i[i]] != zero) { res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res -= A_diag_data[jj] * u_data[ii]; } u_data[i] = res / A_diag_data[A_diag_i[i]]; } } } for (p = 0; p < num_procs; p++) { jr = 0; if (p != my_id) { for (i = 0; i < num_sends; i++) { ip = hypre_ParCSRCommPkgSendProc(comm_pkg, i); if (ip == p) { vec_start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); vec_len = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1)-vec_start; for (j=vec_start; j < vec_start+vec_len; j++) v_buf_data[j] = u_data[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)]; hypre_MPI_Isend(&v_buf_data[vec_start], vec_len, HYPRE_MPI_REAL, ip, 0, comm, &requests[jr++]); } } hypre_MPI_Waitall(jr,requests,status); hypre_MPI_Barrier(comm); } else { if (num_procs > 1) { for (i = 0; i < num_recvs; i++) { ip = hypre_ParCSRCommPkgRecvProc(comm_pkg, i); vec_start = hypre_ParCSRCommPkgRecvVecStart(comm_pkg,i); vec_len = hypre_ParCSRCommPkgRecvVecStart(comm_pkg,i+1)-vec_start; hypre_MPI_Irecv(&Vext_data[vec_start], vec_len, HYPRE_MPI_REAL, ip, 0, comm, &requests[jr++]); } hypre_MPI_Waitall(jr,requests,status); } if (relax_points == 0) { for (i = 0; i < n; i++) { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ((A_offd_i[i+1]-A_offd_i[i]) != zero && A_diag_data[A_diag_i[i]] != zero) { res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res -= A_diag_data[jj] * u_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] = res / A_diag_data[A_diag_i[i]]; } } } /*----------------------------------------------------------------- * Relax only C or F points as determined by relax_points. *-----------------------------------------------------------------*/ else { for (i = 0; i < n; i++) { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && (A_offd_i[i+1]-A_offd_i[i]) != zero && A_diag_data[A_diag_i[i]] != zero) { res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res -= A_diag_data[jj] * u_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] = res / A_diag_data[A_diag_i[i]]; } } } if (num_procs > 1) hypre_MPI_Barrier(comm); } } if (num_procs > 1) { hypre_TFree(Vext_data); hypre_TFree(v_buf_data); hypre_TFree(status); hypre_TFree(requests); } } break; case 4: /* Hybrid: Jacobi off-processor, Gauss-Seidel/SOR on-processor (backward loop) */ { if (num_procs > 1) { num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); v_buf_data = hypre_CTAlloc(HYPRE_Real, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends)); Vext_data = hypre_CTAlloc(HYPRE_Real,num_cols_offd); if (num_cols_offd) { A_offd_j = hypre_CSRMatrixJ(A_offd); A_offd_data = hypre_CSRMatrixData(A_offd); } index = 0; for (i = 0; i < num_sends; i++) { start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j=start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg,i+1); j++) v_buf_data[index++] = u_data[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)]; } comm_handle = hypre_ParCSRCommHandleCreate( 1, comm_pkg, v_buf_data, Vext_data); /*----------------------------------------------------------------- * Copy current approximation into temporary vector. *-----------------------------------------------------------------*/ hypre_ParCSRCommHandleDestroy(comm_handle); comm_handle = NULL; } /*----------------------------------------------------------------- * Relax all points. *-----------------------------------------------------------------*/ if (relax_weight == 1 && omega == 1) { if (relax_points == 0) { if (num_threads > 1) { tmp_data = hypre_CTAlloc(HYPRE_Real,n); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) tmp_data[i] = u_data[i]; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,ii,j,jj,ns,ne,res,rest,size) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < num_threads; j++) { size = n/num_threads; rest = n - size*num_threads; if (j < rest) { ns = j*size+j; ne = (j+1)*size+j+1; } else { ns = j*size+rest; ne = (j+1)*size+rest; } for (i = ne-1; i > ns-1; i--) /* interior points first */ { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( A_diag_data[A_diag_i[i]] != zero) { res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; if (ii >= ns && ii < ne) res -= A_diag_data[jj] * u_data[ii]; else res -= A_diag_data[jj] * tmp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] = res / A_diag_data[A_diag_i[i]]; } } } hypre_TFree(tmp_data); } else { for (i = n-1; i > -1; i--) /* interior points first */ { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( A_diag_data[A_diag_i[i]] != zero) { res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res -= A_diag_data[jj] * u_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] = res / A_diag_data[A_diag_i[i]]; } } } } /*----------------------------------------------------------------- * Relax only C or F points as determined by relax_points. *-----------------------------------------------------------------*/ else { if (num_threads > 1) { tmp_data = hypre_CTAlloc(HYPRE_Real,n); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) tmp_data[i] = u_data[i]; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,ii,j,jj,ns,ne,res,rest,size) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < num_threads; j++) { size = n/num_threads; rest = n - size*num_threads; if (j < rest) { ns = j*size+j; ne = (j+1)*size+j+1; } else { ns = j*size+rest; ne = (j+1)*size+rest; } for (i = ne-1; i > ns-1; i--) /* relax interior points */ { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && A_diag_data[A_diag_i[i]] != zero) { res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; if (ii >= ns && ii < ne) res -= A_diag_data[jj] * u_data[ii]; else res -= A_diag_data[jj] * tmp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] = res / A_diag_data[A_diag_i[i]]; } } } hypre_TFree(tmp_data); } else { for (i = n-1; i > -1; i--) /* relax interior points */ { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && A_diag_data[A_diag_i[i]] != zero) { res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res -= A_diag_data[jj] * u_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] = res / A_diag_data[A_diag_i[i]]; } } } } } else { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) { Vtemp_data[i] = u_data[i]; } prod = (1.0-relax_weight*omega); if (relax_points == 0) { if (num_threads > 1) { tmp_data = hypre_CTAlloc(HYPRE_Real,n); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) tmp_data[i] = u_data[i]; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,ii,j,jj,ns,ne,res,rest,size) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < num_threads; j++) { size = n/num_threads; rest = n - size*num_threads; if (j < rest) { ns = j*size+j; ne = (j+1)*size+j+1; } else { ns = j*size+rest; ne = (j+1)*size+rest; } for (i = ne-1; i > ns-1; i--) /* interior points first */ { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( A_diag_data[A_diag_i[i]] != zero) { res = f_data[i]; res0 = 0.0; res2 = 0.0; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; if (ii >= ns && ii < ne) { res0 -= A_diag_data[jj] * u_data[ii]; res2 += A_diag_data[jj] * Vtemp_data[ii]; } else res -= A_diag_data[jj] * tmp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] *= prod; u_data[i] += relax_weight*(omega*res + res0 + one_minus_omega*res2) / A_diag_data[A_diag_i[i]]; /*u_data[i] += omega*(relax_weight*res + res0 + one_minus_weight*res2) / A_diag_data[A_diag_i[i]];*/ } } } hypre_TFree(tmp_data); } else { for (i = n-1; i > -1; i--) /* interior points first */ { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( A_diag_data[A_diag_i[i]] != zero) { res0 = 0.0; res2 = 0.0; res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res0 -= A_diag_data[jj] * u_data[ii]; res2 += A_diag_data[jj] * Vtemp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] *= prod; u_data[i] += relax_weight*(omega*res + res0 + one_minus_omega*res2) / A_diag_data[A_diag_i[i]]; /*u_data[i] += omega*(relax_weight*res + res0 + one_minus_weight*res2) / A_diag_data[A_diag_i[i]];*/ } } } } /*----------------------------------------------------------------- * Relax only C or F points as determined by relax_points. *-----------------------------------------------------------------*/ else { if (num_threads > 1) { tmp_data = hypre_CTAlloc(HYPRE_Real,n); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) tmp_data[i] = u_data[i]; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,ii,j,jj,ns,ne,res,rest,size) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < num_threads; j++) { size = n/num_threads; rest = n - size*num_threads; if (j < rest) { ns = j*size+j; ne = (j+1)*size+j+1; } else { ns = j*size+rest; ne = (j+1)*size+rest; } for (i = ne-1; i > ns-1; i--) /* relax interior points */ { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && A_diag_data[A_diag_i[i]] != zero) { res0 = 0.0; res2 = 0.0; res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; if (ii >= ns && ii < ne) { res0 -= A_diag_data[jj] * u_data[ii]; res2 += A_diag_data[jj] * Vtemp_data[ii]; } else res -= A_diag_data[jj] * tmp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] *= prod; u_data[i] += relax_weight*(omega*res + res0 + one_minus_omega*res2) / A_diag_data[A_diag_i[i]]; /*u_data[i] += omega*(relax_weight*res + res0 + one_minus_weight*res2) / A_diag_data[A_diag_i[i]];*/ } } } hypre_TFree(tmp_data); } else { for (i = n-1; i > -1; i--) /* relax interior points */ { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && A_diag_data[A_diag_i[i]] != zero) { res = f_data[i]; res0 = 0.0; res2 = 0.0; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res0 -= A_diag_data[jj] * u_data[ii]; res2 += A_diag_data[jj] * Vtemp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] *= prod; u_data[i] += relax_weight*(omega*res + res0 + one_minus_omega*res2) / A_diag_data[A_diag_i[i]]; /*u_data[i] += omega*(relax_weight*res + res0 + one_minus_weight*res2) / A_diag_data[A_diag_i[i]];*/ } } } } } if (num_procs > 1) { hypre_TFree(Vext_data); hypre_TFree(v_buf_data); } } break; case 6: /* Hybrid: Jacobi off-processor, Symm. Gauss-Seidel/ SSOR on-processor with outer relaxation parameter */ { if (num_threads > 1) { Ztemp_local = hypre_ParVectorLocalVector(Ztemp); Ztemp_data = hypre_VectorData(Ztemp_local); } /*----------------------------------------------------------------- * Copy current approximation into temporary vector. *-----------------------------------------------------------------*/ if (num_procs > 1) { num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); v_buf_data = hypre_CTAlloc(HYPRE_Real, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends)); Vext_data = hypre_CTAlloc(HYPRE_Real,num_cols_offd); if (num_cols_offd) { A_offd_j = hypre_CSRMatrixJ(A_offd); A_offd_data = hypre_CSRMatrixData(A_offd); } index = 0; for (i = 0; i < num_sends; i++) { start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j=start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg,i+1); j++) v_buf_data[index++] = u_data[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)]; } comm_handle = hypre_ParCSRCommHandleCreate( 1, comm_pkg, v_buf_data, Vext_data); /*----------------------------------------------------------------- * Copy current approximation into temporary vector. *-----------------------------------------------------------------*/ hypre_ParCSRCommHandleDestroy(comm_handle); comm_handle = NULL; } /*----------------------------------------------------------------- * Relax all points. *-----------------------------------------------------------------*/ if (relax_weight == 1 && omega == 1) { if (relax_points == 0) { if (num_threads > 1) { tmp_data = Ztemp_data; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) tmp_data[i] = u_data[i]; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,ii,j,jj,ns,ne,res,rest,size) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < num_threads; j++) { size = n/num_threads; rest = n - size*num_threads; if (j < rest) { ns = j*size+j; ne = (j+1)*size+j+1; } else { ns = j*size+rest; ne = (j+1)*size+rest; } for (i = ns; i < ne; i++) /* interior points first */ { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( A_diag_data[A_diag_i[i]] != zero) { res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; if (ii >= ns && ii < ne) { res -= A_diag_data[jj] * u_data[ii]; } else res -= A_diag_data[jj] * tmp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] = res / A_diag_data[A_diag_i[i]]; } } for (i = ne-1; i > ns-1; i--) /* interior points first */ { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( A_diag_data[A_diag_i[i]] != zero) { res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; if (ii >= ns && ii < ne) { res -= A_diag_data[jj] * u_data[ii]; } else res -= A_diag_data[jj] * tmp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] = res / A_diag_data[A_diag_i[i]]; } } } } else { for (i = 0; i < n; i++) /* interior points first */ { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( A_diag_data[A_diag_i[i]] != zero) { res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res -= A_diag_data[jj] * u_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] = res / A_diag_data[A_diag_i[i]]; } } for (i = n-1; i > -1; i--) /* interior points first */ { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( A_diag_data[A_diag_i[i]] != zero) { res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res -= A_diag_data[jj] * u_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] = res / A_diag_data[A_diag_i[i]]; } } } } /*----------------------------------------------------------------- * Relax only C or F points as determined by relax_points. *-----------------------------------------------------------------*/ else { if (num_threads > 1) { tmp_data = Ztemp_data; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) tmp_data[i] = u_data[i]; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,ii,j,jj,ns,ne,res,rest,size) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < num_threads; j++) { size = n/num_threads; rest = n - size*num_threads; if (j < rest) { ns = j*size+j; ne = (j+1)*size+j+1; } else { ns = j*size+rest; ne = (j+1)*size+rest; } for (i = ns; i < ne; i++) /* relax interior points */ { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && A_diag_data[A_diag_i[i]] != zero) { res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; if (ii >= ns && ii < ne) { res -= A_diag_data[jj] * u_data[ii]; } else res -= A_diag_data[jj] * tmp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] = res / A_diag_data[A_diag_i[i]]; } } for (i = ne-1; i > ns-1; i--) /* relax interior points */ { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && A_diag_data[A_diag_i[i]] != zero) { res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; if (ii >= ns && ii < ne) { res -= A_diag_data[jj] * u_data[ii]; } else res -= A_diag_data[jj] * tmp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] = res / A_diag_data[A_diag_i[i]]; } } } } else { for (i = 0; i < n; i++) /* relax interior points */ { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && A_diag_data[A_diag_i[i]] != zero) { res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res -= A_diag_data[jj] * u_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] = res / A_diag_data[A_diag_i[i]]; } } for (i = n-1; i > -1; i--) /* relax interior points */ { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && A_diag_data[A_diag_i[i]] != zero) { res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res -= A_diag_data[jj] * u_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] = res / A_diag_data[A_diag_i[i]]; } } } } } else { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) { Vtemp_data[i] = u_data[i]; } prod = (1.0-relax_weight*omega); if (relax_points == 0) { if (num_threads > 1) { tmp_data = Ztemp_data; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) tmp_data[i] = u_data[i]; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,ii,j,jj,ns,ne,res,rest,size) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < num_threads; j++) { size = n/num_threads; rest = n - size*num_threads; if (j < rest) { ns = j*size+j; ne = (j+1)*size+j+1; } else { ns = j*size+rest; ne = (j+1)*size+rest; } for (i = ns; i < ne; i++) /* interior points first */ { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( A_diag_data[A_diag_i[i]] != zero) { res0 = 0.0; res2 = 0.0; res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; if (ii >= ns && ii < ne) { res0 -= A_diag_data[jj] * u_data[ii]; res2 += A_diag_data[jj] * Vtemp_data[ii]; } else res -= A_diag_data[jj] * tmp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] *= prod; u_data[i] += relax_weight*(omega*res + res0 + one_minus_omega*res2) / A_diag_data[A_diag_i[i]]; /*u_data[i] += omega*(relax_weight*res + res0 + one_minus_weight*res2) / A_diag_data[A_diag_i[i]];*/ } } for (i = ne-1; i > ns-1; i--) /* interior points first */ { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( A_diag_data[A_diag_i[i]] != zero) { res0 = 0.0; res2 = 0.0; res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; if (ii >= ns && ii < ne) { res0 -= A_diag_data[jj] * u_data[ii]; res2 += A_diag_data[jj] * Vtemp_data[ii]; } else res -= A_diag_data[jj] * tmp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] *= prod; u_data[i] += relax_weight*(omega*res + res0 + one_minus_omega*res2) / A_diag_data[A_diag_i[i]]; /*u_data[i] += omega*(relax_weight*res + res0 + one_minus_weight*res2) / A_diag_data[A_diag_i[i]];*/ } } } } else { for (i = 0; i < n; i++) /* interior points first */ { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( A_diag_data[A_diag_i[i]] != zero) { res0 = 0.0; res = f_data[i]; res2 = 0.0; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res0 -= A_diag_data[jj] * u_data[ii]; res2 += A_diag_data[jj] * Vtemp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] *= prod; u_data[i] += relax_weight*(omega*res + res0 + one_minus_omega*res2) / A_diag_data[A_diag_i[i]]; /*u_data[i] += omega*(relax_weight*res + res0 + one_minus_weight*res2) / A_diag_data[A_diag_i[i]];*/ } } for (i = n-1; i > -1; i--) /* interior points first */ { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( A_diag_data[A_diag_i[i]] != zero) { res0 = 0.0; res = f_data[i]; res2 = 0.0; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res0 -= A_diag_data[jj] * u_data[ii]; res2 += A_diag_data[jj] * Vtemp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] *= prod; u_data[i] += relax_weight*(omega*res + res0 + one_minus_omega*res2) / A_diag_data[A_diag_i[i]]; /*u_data[i] += omega*(relax_weight*res + res0 + one_minus_weight*res2) / A_diag_data[A_diag_i[i]];*/ } } } } /*----------------------------------------------------------------- * Relax only C or F points as determined by relax_points. *-----------------------------------------------------------------*/ else { if (num_threads > 1) { tmp_data = Ztemp_data; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) tmp_data[i] = u_data[i]; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,ii,j,jj,ns,ne,res,rest,size) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < num_threads; j++) { size = n/num_threads; rest = n - size*num_threads; if (j < rest) { ns = j*size+j; ne = (j+1)*size+j+1; } else { ns = j*size+rest; ne = (j+1)*size+rest; } for (i = ns; i < ne; i++) /* relax interior points */ { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && A_diag_data[A_diag_i[i]] != zero) { res0 = 0.0; res2 = 0.0; res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; if (ii >= ns && ii < ne) { res2 += A_diag_data[jj] * Vtemp_data[ii]; res0 -= A_diag_data[jj] * u_data[ii]; } else res -= A_diag_data[jj] * tmp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] *= prod; u_data[i] += relax_weight*(omega*res + res0 + one_minus_omega*res2) / A_diag_data[A_diag_i[i]]; /*u_data[i] += omega*(relax_weight*res + res0 + one_minus_weight*res2) / A_diag_data[A_diag_i[i]];*/ } } for (i = ne-1; i > ns-1; i--) /* relax interior points */ { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && A_diag_data[A_diag_i[i]] != zero) { res0 = 0.0; res2 = 0.0; res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; if (ii >= ns && ii < ne) { res2 += A_diag_data[jj] * Vtemp_data[ii]; res0 -= A_diag_data[jj] * u_data[ii]; } else res -= A_diag_data[jj] * tmp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] *= prod; u_data[i] += relax_weight*(omega*res + res0 + one_minus_omega*res2) / A_diag_data[A_diag_i[i]]; /*u_data[i] += omega*(relax_weight*res + res0 + one_minus_weight*res2) / A_diag_data[A_diag_i[i]];*/ } } } } else { for (i = 0; i < n; i++) /* relax interior points */ { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && A_diag_data[A_diag_i[i]] != zero) { res = f_data[i]; res0 = 0.0; res2 = 0.0; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res0 -= A_diag_data[jj] * u_data[ii]; res2 += A_diag_data[jj] * Vtemp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] *= prod; u_data[i] += relax_weight*(omega*res + res0 + one_minus_omega*res2) / A_diag_data[A_diag_i[i]]; /*u_data[i] += omega*(relax_weight*res + res0 + one_minus_weight*res2) / A_diag_data[A_diag_i[i]];*/ } } for (i = n-1; i > -1; i--) /* relax interior points */ { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && A_diag_data[A_diag_i[i]] != zero) { res = f_data[i]; res0 = 0.0; res2 = 0.0; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res0 -= A_diag_data[jj] * u_data[ii]; res2 += A_diag_data[jj] * Vtemp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] *= prod; u_data[i] += relax_weight*(omega*res + res0 + one_minus_omega*res2) / A_diag_data[A_diag_i[i]]; /*u_data[i] += omega*(relax_weight*res + res0 + one_minus_weight*res2) / A_diag_data[A_diag_i[i]];*/ } } } } } if (num_procs > 1) { hypre_TFree(Vext_data); hypre_TFree(v_buf_data); } } break; case 7: /* Jacobi (uses ParMatvec) */ { /*----------------------------------------------------------------- * Copy f into temporary vector. *-----------------------------------------------------------------*/ hypre_ParVectorCopy(f,Vtemp); /*----------------------------------------------------------------- * Perform Matvec Vtemp=f-Au *-----------------------------------------------------------------*/ hypre_ParCSRMatrixMatvec(-relax_weight,A, u, relax_weight, Vtemp); for (i = 0; i < n; i++) { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ u_data[i] += Vtemp_data[i] / l1_norms[i]; } } break; case 8: /* hybrid L1 Symm. Gauss-Seidel */ { if (num_threads > 1) { Ztemp_local = hypre_ParVectorLocalVector(Ztemp); Ztemp_data = hypre_VectorData(Ztemp_local); } /*----------------------------------------------------------------- * Copy current approximation into temporary vector. *-----------------------------------------------------------------*/ if (num_procs > 1) { num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); v_buf_data = hypre_CTAlloc(HYPRE_Real, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends)); Vext_data = hypre_CTAlloc(HYPRE_Real,num_cols_offd); if (num_cols_offd) { A_offd_j = hypre_CSRMatrixJ(A_offd); A_offd_data = hypre_CSRMatrixData(A_offd); } index = 0; for (i = 0; i < num_sends; i++) { start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j=start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg,i+1); j++) v_buf_data[index++] = u_data[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)]; } comm_handle = hypre_ParCSRCommHandleCreate( 1, comm_pkg, v_buf_data, Vext_data); /*----------------------------------------------------------------- * Copy current approximation into temporary vector. *-----------------------------------------------------------------*/ hypre_ParCSRCommHandleDestroy(comm_handle); comm_handle = NULL; } /*----------------------------------------------------------------- * Relax all points. *-----------------------------------------------------------------*/ if (relax_weight == 1 && omega == 1) { if (relax_points == 0) { if (num_threads > 1) { tmp_data = Ztemp_data; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) tmp_data[i] = u_data[i]; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,ii,j,jj,ns,ne,res,rest,size) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < num_threads; j++) { size = n/num_threads; rest = n - size*num_threads; if (j < rest) { ns = j*size+j; ne = (j+1)*size+j+1; } else { ns = j*size+rest; ne = (j+1)*size+rest; } for (i = ns; i < ne; i++) /* interior points first */ { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( l1_norms[i] != zero) { res = f_data[i]; for (jj = A_diag_i[i]; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; if (ii >= ns && ii < ne) { res -= A_diag_data[jj] * u_data[ii]; } else res -= A_diag_data[jj] * tmp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] += res / l1_norms[i]; } } for (i = ne-1; i > ns-1; i--) /* interior points first */ { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( l1_norms[i] != zero) { res = f_data[i]; for (jj = A_diag_i[i]; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; if (ii >= ns && ii < ne) { res -= A_diag_data[jj] * u_data[ii]; } else res -= A_diag_data[jj] * tmp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] += res / l1_norms[i]; } } } } else { for (i = 0; i < n; i++) /* interior points first */ { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( l1_norms[i] != zero) { res = f_data[i]; for (jj = A_diag_i[i]; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res -= A_diag_data[jj] * u_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] += res / l1_norms[i]; } } for (i = n-1; i > -1; i--) /* interior points first */ { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( l1_norms[i] != zero) { res = f_data[i]; for (jj = A_diag_i[i]; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res -= A_diag_data[jj] * u_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] += res / l1_norms[i]; } } } } /*----------------------------------------------------------------- * Relax only C or F points as determined by relax_points. *-----------------------------------------------------------------*/ else { if (num_threads > 1) { tmp_data = Ztemp_data; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) tmp_data[i] = u_data[i]; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,ii,j,jj,ns,ne,res,rest,size) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < num_threads; j++) { size = n/num_threads; rest = n - size*num_threads; if (j < rest) { ns = j*size+j; ne = (j+1)*size+j+1; } else { ns = j*size+rest; ne = (j+1)*size+rest; } for (i = ns; i < ne; i++) /* relax interior points */ { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && l1_norms[i] != zero) { res = f_data[i]; for (jj = A_diag_i[i]; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; if (ii >= ns && ii < ne) { res -= A_diag_data[jj] * u_data[ii]; } else res -= A_diag_data[jj] * tmp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] += res / l1_norms[i]; } } for (i = ne-1; i > ns-1; i--) /* relax interior points */ { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && l1_norms[i] != zero) { res = f_data[i]; for (jj = A_diag_i[i]; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; if (ii >= ns && ii < ne) { res -= A_diag_data[jj] * u_data[ii]; } else res -= A_diag_data[jj] * tmp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] += res / l1_norms[i]; } } } } else { for (i = 0; i < n; i++) /* relax interior points */ { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && l1_norms[i] != zero) { res = f_data[i]; for (jj = A_diag_i[i]; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res -= A_diag_data[jj] * u_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] += res / l1_norms[i]; } } for (i = n-1; i > -1; i--) /* relax interior points */ { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && l1_norms[i] != zero) { res = f_data[i]; for (jj = A_diag_i[i]; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res -= A_diag_data[jj] * u_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] += res / l1_norms[i]; } } } } } else { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) { Vtemp_data[i] = u_data[i]; } prod = (1.0-relax_weight*omega); if (relax_points == 0) { if (num_threads > 1) { tmp_data = Ztemp_data; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) tmp_data[i] = u_data[i]; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,ii,j,jj,ns,ne,res,rest,size) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < num_threads; j++) { size = n/num_threads; rest = n - size*num_threads; if (j < rest) { ns = j*size+j; ne = (j+1)*size+j+1; } else { ns = j*size+rest; ne = (j+1)*size+rest; } for (i = ns; i < ne; i++) /* interior points first */ { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( l1_norms[i] != zero) { res0 = 0.0; res2 = 0.0; res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; if (ii >= ns && ii < ne) { res0 -= A_diag_data[jj] * u_data[ii]; res2 += A_diag_data[jj] * Vtemp_data[ii]; } else res -= A_diag_data[jj] * tmp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] *= prod; u_data[i] += relax_weight*(omega*res + res0 + one_minus_omega*res2) / l1_norms[i]; /*u_data[i] += omega*(relax_weight*res + res0 + one_minus_weight*res2) / l1_norms[i];*/ } } for (i = ne-1; i > ns-1; i--) /* interior points first */ { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( l1_norms[i] != zero) { res0 = 0.0; res2 = 0.0; res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; if (ii >= ns && ii < ne) { res0 -= A_diag_data[jj] * u_data[ii]; res2 += A_diag_data[jj] * Vtemp_data[ii]; } else res -= A_diag_data[jj] * tmp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] *= prod; u_data[i] += relax_weight*(omega*res + res0 + one_minus_omega*res2) / l1_norms[i]; /*u_data[i] += omega*(relax_weight*res + res0 + one_minus_weight*res2) / l1_norms[i];*/ } } } } else { for (i = 0; i < n; i++) /* interior points first */ { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( l1_norms[i] != zero) { res0 = 0.0; res = f_data[i]; res2 = 0.0; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res0 -= A_diag_data[jj] * u_data[ii]; res2 += A_diag_data[jj] * Vtemp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] *= prod; u_data[i] += relax_weight*(omega*res + res0 + one_minus_omega*res2) / l1_norms[i]; /*u_data[i] += omega*(relax_weight*res + res0 + one_minus_weight*res2) / l1_norms[i];*/ } } for (i = n-1; i > -1; i--) /* interior points first */ { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( l1_norms[i] != zero) { res0 = 0.0; res = f_data[i]; res2 = 0.0; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res0 -= A_diag_data[jj] * u_data[ii]; res2 += A_diag_data[jj] * Vtemp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] *= prod; u_data[i] += relax_weight*(omega*res + res0 + one_minus_omega*res2) / l1_norms[i]; /*u_data[i] += omega*(relax_weight*res + res0 + one_minus_weight*res2) / l1_norms[i];*/ } } } } /*----------------------------------------------------------------- * Relax only C or F points as determined by relax_points. *-----------------------------------------------------------------*/ else { if (num_threads > 1) { tmp_data = Ztemp_data; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) tmp_data[i] = u_data[i]; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,ii,j,jj,ns,ne,res,rest,size) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < num_threads; j++) { size = n/num_threads; rest = n - size*num_threads; if (j < rest) { ns = j*size+j; ne = (j+1)*size+j+1; } else { ns = j*size+rest; ne = (j+1)*size+rest; } for (i = ns; i < ne; i++) /* relax interior points */ { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && l1_norms[i] != zero) { res0 = 0.0; res2 = 0.0; res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; if (ii >= ns && ii < ne) { res2 += A_diag_data[jj] * Vtemp_data[ii]; res0 -= A_diag_data[jj] * u_data[ii]; } else res -= A_diag_data[jj] * tmp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] *= prod; u_data[i] += relax_weight*(omega*res + res0 + one_minus_omega*res2) / l1_norms[i]; /*u_data[i] += omega*(relax_weight*res + res0 + one_minus_weight*res2) / l1_norms[i];*/ } } for (i = ne-1; i > ns-1; i--) /* relax interior points */ { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && l1_norms[i] != zero) { res0 = 0.0; res2 = 0.0; res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; if (ii >= ns && ii < ne) { res2 += A_diag_data[jj] * Vtemp_data[ii]; res0 -= A_diag_data[jj] * u_data[ii]; } else res -= A_diag_data[jj] * tmp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] *= prod; u_data[i] += relax_weight*(omega*res + res0 + one_minus_omega*res2) / l1_norms[i]; /*u_data[i] += omega*(relax_weight*res + res0 + one_minus_weight*res2) / l1_norms[i];*/ } } } } else { for (i = 0; i < n; i++) /* relax interior points */ { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && l1_norms[i] != zero) { res = f_data[i]; res0 = 0.0; res2 = 0.0; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res0 -= A_diag_data[jj] * u_data[ii]; res2 += A_diag_data[jj] * Vtemp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] *= prod; u_data[i] += relax_weight*(omega*res + res0 + one_minus_omega*res2) / l1_norms[i]; /*u_data[i] += omega*(relax_weight*res + res0 + one_minus_weight*res2) / l1_norms[i];*/ } } for (i = n-1; i > -1; i--) /* relax interior points */ { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && l1_norms[i] != zero) { res = f_data[i]; res0 = 0.0; res2 = 0.0; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res0 -= A_diag_data[jj] * u_data[ii]; res2 += A_diag_data[jj] * Vtemp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] *= prod; u_data[i] += relax_weight*(omega*res + res0 + one_minus_omega*res2) / l1_norms[i]; /*u_data[i] += omega*(relax_weight*res + res0 + one_minus_weight*res2) / l1_norms[i];*/ } } } } } if (num_procs > 1) { hypre_TFree(Vext_data); hypre_TFree(v_buf_data); } } break; case 13: /* hybrid L1 Gauss-Seidel forward solve */ { if (num_threads > 1) { Ztemp_local = hypre_ParVectorLocalVector(Ztemp); Ztemp_data = hypre_VectorData(Ztemp_local); } /*----------------------------------------------------------------- * Copy current approximation into temporary vector. *-----------------------------------------------------------------*/ if (num_procs > 1) { num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); v_buf_data = hypre_CTAlloc(HYPRE_Real, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends)); Vext_data = hypre_CTAlloc(HYPRE_Real,num_cols_offd); if (num_cols_offd) { A_offd_j = hypre_CSRMatrixJ(A_offd); A_offd_data = hypre_CSRMatrixData(A_offd); } index = 0; for (i = 0; i < num_sends; i++) { start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j=start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg,i+1); j++) v_buf_data[index++] = u_data[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)]; } comm_handle = hypre_ParCSRCommHandleCreate( 1, comm_pkg, v_buf_data, Vext_data); /*----------------------------------------------------------------- * Copy current approximation into temporary vector. *-----------------------------------------------------------------*/ hypre_ParCSRCommHandleDestroy(comm_handle); comm_handle = NULL; } /*----------------------------------------------------------------- * Relax all points. *-----------------------------------------------------------------*/ if (relax_weight == 1 && omega == 1) { if (relax_points == 0) { if (num_threads > 1) { tmp_data = Ztemp_data; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) tmp_data[i] = u_data[i]; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,ii,j,jj,ns,ne,res,rest,size) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < num_threads; j++) { size = n/num_threads; rest = n - size*num_threads; if (j < rest) { ns = j*size+j; ne = (j+1)*size+j+1; } else { ns = j*size+rest; ne = (j+1)*size+rest; } for (i = ns; i < ne; i++) /* interior points first */ { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( l1_norms[i] != zero) { res = f_data[i]; for (jj = A_diag_i[i]; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; if (ii >= ns && ii < ne) { res -= A_diag_data[jj] * u_data[ii]; } else res -= A_diag_data[jj] * tmp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] += res / l1_norms[i]; } } } } else { for (i = 0; i < n; i++) /* interior points first */ { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( l1_norms[i] != zero) { res = f_data[i]; for (jj = A_diag_i[i]; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res -= A_diag_data[jj] * u_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] += res / l1_norms[i]; } } } } /*----------------------------------------------------------------- * Relax only C or F points as determined by relax_points. *-----------------------------------------------------------------*/ else { if (num_threads > 1) { tmp_data = Ztemp_data; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) tmp_data[i] = u_data[i]; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,ii,j,jj,ns,ne,res,rest,size) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < num_threads; j++) { size = n/num_threads; rest = n - size*num_threads; if (j < rest) { ns = j*size+j; ne = (j+1)*size+j+1; } else { ns = j*size+rest; ne = (j+1)*size+rest; } for (i = ns; i < ne; i++) /* relax interior points */ { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && l1_norms[i] != zero) { res = f_data[i]; for (jj = A_diag_i[i]; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; if (ii >= ns && ii < ne) { res -= A_diag_data[jj] * u_data[ii]; } else res -= A_diag_data[jj] * tmp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] += res / l1_norms[i]; } } } } else { for (i = 0; i < n; i++) /* relax interior points */ { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && l1_norms[i] != zero) { res = f_data[i]; for (jj = A_diag_i[i]; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res -= A_diag_data[jj] * u_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] += res / l1_norms[i]; } } } } } else { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) { Vtemp_data[i] = u_data[i]; } prod = (1.0-relax_weight*omega); if (relax_points == 0) { if (num_threads > 1) { tmp_data = Ztemp_data; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) tmp_data[i] = u_data[i]; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,ii,j,jj,ns,ne,res,rest,size) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < num_threads; j++) { size = n/num_threads; rest = n - size*num_threads; if (j < rest) { ns = j*size+j; ne = (j+1)*size+j+1; } else { ns = j*size+rest; ne = (j+1)*size+rest; } for (i = ns; i < ne; i++) /* interior points first */ { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( l1_norms[i] != zero) { res0 = 0.0; res2 = 0.0; res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; if (ii >= ns && ii < ne) { res0 -= A_diag_data[jj] * u_data[ii]; res2 += A_diag_data[jj] * Vtemp_data[ii]; } else res -= A_diag_data[jj] * tmp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] *= prod; u_data[i] += relax_weight*(omega*res + res0 + one_minus_omega*res2) / l1_norms[i]; /*u_data[i] += omega*(relax_weight*res + res0 + one_minus_weight*res2) / l1_norms[i];*/ } } } } else { for (i = 0; i < n; i++) /* interior points first */ { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( l1_norms[i] != zero) { res0 = 0.0; res = f_data[i]; res2 = 0.0; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res0 -= A_diag_data[jj] * u_data[ii]; res2 += A_diag_data[jj] * Vtemp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] *= prod; u_data[i] += relax_weight*(omega*res + res0 + one_minus_omega*res2) / l1_norms[i]; /*u_data[i] += omega*(relax_weight*res + res0 + one_minus_weight*res2) / l1_norms[i];*/ } } } } /*----------------------------------------------------------------- * Relax only C or F points as determined by relax_points. *-----------------------------------------------------------------*/ else { if (num_threads > 1) { tmp_data = Ztemp_data; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) tmp_data[i] = u_data[i]; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,ii,j,jj,ns,ne,res,rest,size) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < num_threads; j++) { size = n/num_threads; rest = n - size*num_threads; if (j < rest) { ns = j*size+j; ne = (j+1)*size+j+1; } else { ns = j*size+rest; ne = (j+1)*size+rest; } for (i = ns; i < ne; i++) /* relax interior points */ { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && l1_norms[i] != zero) { res0 = 0.0; res2 = 0.0; res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; if (ii >= ns && ii < ne) { res2 += A_diag_data[jj] * Vtemp_data[ii]; res0 -= A_diag_data[jj] * u_data[ii]; } else res -= A_diag_data[jj] * tmp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] *= prod; u_data[i] += relax_weight*(omega*res + res0 + one_minus_omega*res2) / l1_norms[i]; /*u_data[i] += omega*(relax_weight*res + res0 + one_minus_weight*res2) / l1_norms[i];*/ } } } } else { for (i = 0; i < n; i++) /* relax interior points */ { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && l1_norms[i] != zero) { res = f_data[i]; res0 = 0.0; res2 = 0.0; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res0 -= A_diag_data[jj] * u_data[ii]; res2 += A_diag_data[jj] * Vtemp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] *= prod; u_data[i] += relax_weight*(omega*res + res0 + one_minus_omega*res2) / l1_norms[i]; /*u_data[i] += omega*(relax_weight*res + res0 + one_minus_weight*res2) / l1_norms[i];*/ } } } } } if (num_procs > 1) { hypre_TFree(Vext_data); hypre_TFree(v_buf_data); } } break; case 14: /* hybrid L1 Gauss-Seidel backward solve */ { if (num_threads > 1) { Ztemp_local = hypre_ParVectorLocalVector(Ztemp); Ztemp_data = hypre_VectorData(Ztemp_local); } /*----------------------------------------------------------------- * Copy current approximation into temporary vector. *-----------------------------------------------------------------*/ if (num_procs > 1) { num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); v_buf_data = hypre_CTAlloc(HYPRE_Real, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends)); Vext_data = hypre_CTAlloc(HYPRE_Real,num_cols_offd); if (num_cols_offd) { A_offd_j = hypre_CSRMatrixJ(A_offd); A_offd_data = hypre_CSRMatrixData(A_offd); } index = 0; for (i = 0; i < num_sends; i++) { start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j=start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg,i+1); j++) v_buf_data[index++] = u_data[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)]; } comm_handle = hypre_ParCSRCommHandleCreate( 1, comm_pkg, v_buf_data, Vext_data); /*----------------------------------------------------------------- * Copy current approximation into temporary vector. *-----------------------------------------------------------------*/ hypre_ParCSRCommHandleDestroy(comm_handle); comm_handle = NULL; } /*----------------------------------------------------------------- * Relax all points. *-----------------------------------------------------------------*/ if (relax_weight == 1 && omega == 1) { if (relax_points == 0) { if (num_threads > 1) { tmp_data = Ztemp_data; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) tmp_data[i] = u_data[i]; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,ii,j,jj,ns,ne,res,rest,size) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < num_threads; j++) { size = n/num_threads; rest = n - size*num_threads; if (j < rest) { ns = j*size+j; ne = (j+1)*size+j+1; } else { ns = j*size+rest; ne = (j+1)*size+rest; } for (i = ne-1; i > ns-1; i--) /* interior points first */ { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( l1_norms[i] != zero) { res = f_data[i]; for (jj = A_diag_i[i]; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; if (ii >= ns && ii < ne) { res -= A_diag_data[jj] * u_data[ii]; } else res -= A_diag_data[jj] * tmp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] += res / l1_norms[i]; } } } } else { for (i = n-1; i > -1; i--) /* interior points first */ { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( l1_norms[i] != zero) { res = f_data[i]; for (jj = A_diag_i[i]; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res -= A_diag_data[jj] * u_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] += res / l1_norms[i]; } } } } /*----------------------------------------------------------------- * Relax only C or F points as determined by relax_points. *-----------------------------------------------------------------*/ else { if (num_threads > 1) { tmp_data = Ztemp_data; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) tmp_data[i] = u_data[i]; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,ii,j,jj,ns,ne,res,rest,size) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < num_threads; j++) { size = n/num_threads; rest = n - size*num_threads; if (j < rest) { ns = j*size+j; ne = (j+1)*size+j+1; } else { ns = j*size+rest; ne = (j+1)*size+rest; } for (i = ne-1; i > ns-1; i--) /* relax interior points */ { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && l1_norms[i] != zero) { res = f_data[i]; for (jj = A_diag_i[i]; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; if (ii >= ns && ii < ne) { res -= A_diag_data[jj] * u_data[ii]; } else res -= A_diag_data[jj] * tmp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] += res / l1_norms[i]; } } } } else { for (i = n-1; i > -1; i--) /* relax interior points */ { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && l1_norms[i] != zero) { res = f_data[i]; for (jj = A_diag_i[i]; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res -= A_diag_data[jj] * u_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] += res / l1_norms[i]; } } } } } else { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) { Vtemp_data[i] = u_data[i]; } prod = (1.0-relax_weight*omega); if (relax_points == 0) { if (num_threads > 1) { tmp_data = Ztemp_data; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) tmp_data[i] = u_data[i]; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,ii,j,jj,ns,ne,res,rest,size) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < num_threads; j++) { size = n/num_threads; rest = n - size*num_threads; if (j < rest) { ns = j*size+j; ne = (j+1)*size+j+1; } else { ns = j*size+rest; ne = (j+1)*size+rest; } for (i = ne-1; i > ns-1; i--) /* interior points first */ { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( l1_norms[i] != zero) { res0 = 0.0; res2 = 0.0; res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; if (ii >= ns && ii < ne) { res0 -= A_diag_data[jj] * u_data[ii]; res2 += A_diag_data[jj] * Vtemp_data[ii]; } else res -= A_diag_data[jj] * tmp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] *= prod; u_data[i] += relax_weight*(omega*res + res0 + one_minus_omega*res2) / l1_norms[i]; /*u_data[i] += omega*(relax_weight*res + res0 + one_minus_weight*res2) / l1_norms[i];*/ } } } } else { for (i = n-1; i > -1; i--) /* interior points first */ { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( l1_norms[i] != zero) { res0 = 0.0; res = f_data[i]; res2 = 0.0; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res0 -= A_diag_data[jj] * u_data[ii]; res2 += A_diag_data[jj] * Vtemp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] *= prod; u_data[i] += relax_weight*(omega*res + res0 + one_minus_omega*res2) / l1_norms[i]; /*u_data[i] += omega*(relax_weight*res + res0 + one_minus_weight*res2) / l1_norms[i];*/ } } } } /*----------------------------------------------------------------- * Relax only C or F points as determined by relax_points. *-----------------------------------------------------------------*/ else { if (num_threads > 1) { tmp_data = Ztemp_data; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) tmp_data[i] = u_data[i]; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,ii,j,jj,ns,ne,res,rest,size) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < num_threads; j++) { size = n/num_threads; rest = n - size*num_threads; if (j < rest) { ns = j*size+j; ne = (j+1)*size+j+1; } else { ns = j*size+rest; ne = (j+1)*size+rest; } for (i = ne-1; i > ns-1; i--) /* relax interior points */ { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && l1_norms[i] != zero) { res0 = 0.0; res2 = 0.0; res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; if (ii >= ns && ii < ne) { res2 += A_diag_data[jj] * Vtemp_data[ii]; res0 -= A_diag_data[jj] * u_data[ii]; } else res -= A_diag_data[jj] * tmp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] *= prod; u_data[i] += relax_weight*(omega*res + res0 + one_minus_omega*res2) / l1_norms[i]; /*u_data[i] += omega*(relax_weight*res + res0 + one_minus_weight*res2) / l1_norms[i];*/ } } } } else { for (i = n-1; i > -1; i--) /* relax interior points */ { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && l1_norms[i] != zero) { res = f_data[i]; res0 = 0.0; res2 = 0.0; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res0 -= A_diag_data[jj] * u_data[ii]; res2 += A_diag_data[jj] * Vtemp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] *= prod; u_data[i] += relax_weight*(omega*res + res0 + one_minus_omega*res2) / l1_norms[i]; /*u_data[i] += omega*(relax_weight*res + res0 + one_minus_weight*res2) / l1_norms[i];*/ } } } } } if (num_procs > 1) { hypre_TFree(Vext_data); hypre_TFree(v_buf_data); } } break; case 19: /* Direct solve: use gaussian elimination */ { /*----------------------------------------------------------------- * Generate CSR matrix from ParCSRMatrix A *-----------------------------------------------------------------*/ #ifdef HYPRE_NO_GLOBAL_PARTITION /* all processors are needed for these routines */ A_CSR = hypre_ParCSRMatrixToCSRMatrixAll(A); f_vector = hypre_ParVectorToVectorAll(f); if (n) { #else if (n) { A_CSR = hypre_ParCSRMatrixToCSRMatrixAll(A); f_vector = hypre_ParVectorToVectorAll(f); #endif A_CSR_i = hypre_CSRMatrixI(A_CSR); A_CSR_j = hypre_CSRMatrixJ(A_CSR); A_CSR_data = hypre_CSRMatrixData(A_CSR); f_vector_data = hypre_VectorData(f_vector); A_mat = hypre_CTAlloc(HYPRE_Real, n_global*n_global); b_vec = hypre_CTAlloc(HYPRE_Real, n_global); /*--------------------------------------------------------------- * Load CSR matrix into A_mat. *---------------------------------------------------------------*/ for (i = 0; i < n_global; i++) { for (jj = A_CSR_i[i]; jj < A_CSR_i[i+1]; jj++) { column = A_CSR_j[jj]; A_mat[i*n_global+column] = A_CSR_data[jj]; } b_vec[i] = f_vector_data[i]; } relax_error = gselim(A_mat,b_vec,n_global); for (i = 0; i < n; i++) { u_data[i] = b_vec[first_index+i]; } hypre_TFree(A_mat); hypre_TFree(b_vec); hypre_CSRMatrixDestroy(A_CSR); A_CSR = NULL; hypre_SeqVectorDestroy(f_vector); f_vector = NULL; } #ifdef HYPRE_NO_GLOBAL_PARTITION else { hypre_CSRMatrixDestroy(A_CSR); A_CSR = NULL; hypre_SeqVectorDestroy(f_vector); f_vector = NULL; } #endif } break; } return(relax_error); } /*------------------------------------------------------------------------- * * Gaussian Elimination * *------------------------------------------------------------------------ */ HYPRE_Int hypre_GaussElimSetup (hypre_ParAMGData *amg_data, HYPRE_Int level, HYPRE_Int relax_type) { #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_GS_ELIM_SETUP] -= hypre_MPI_Wtime(); #endif /* Par Data Structure variables */ hypre_ParCSRMatrix *A = hypre_ParAMGDataAArray(amg_data)[level]; hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); HYPRE_Int num_rows = hypre_CSRMatrixNumRows(A_diag); HYPRE_Int global_num_rows = hypre_ParCSRMatrixGlobalNumRows(A); MPI_Comm comm = hypre_ParCSRMatrixComm(A); MPI_Comm new_comm; /* Generate sub communicator */ hypre_GenerateSubComm(comm, num_rows, &new_comm); if (num_rows) { hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); HYPRE_Int *col_map_offd = hypre_ParCSRMatrixColMapOffd(A); HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag); HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd); HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag); HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd); HYPRE_Real *A_diag_data = hypre_CSRMatrixData(A_diag); HYPRE_Real *A_offd_data = hypre_CSRMatrixData(A_offd); HYPRE_Real *A_mat, *A_mat_local; HYPRE_Int *comm_info, *info, *displs; HYPRE_Int *mat_info, *mat_displs; HYPRE_Int new_num_procs, A_mat_local_size, i, jj, column; HYPRE_Int first_row_index = hypre_ParCSRMatrixFirstRowIndex(A); hypre_MPI_Comm_size(new_comm, &new_num_procs); comm_info = hypre_CTAlloc(HYPRE_Int, 2*new_num_procs+1); mat_info = hypre_CTAlloc(HYPRE_Int, new_num_procs); mat_displs = hypre_CTAlloc(HYPRE_Int, new_num_procs+1); info = &comm_info[0]; displs = &comm_info[new_num_procs]; hypre_MPI_Allgather(&num_rows, 1, HYPRE_MPI_INT, info, 1, HYPRE_MPI_INT, new_comm); displs[0] = 0; mat_displs[0] = 0; for (i=0; i < new_num_procs; i++) { displs[i+1] = displs[i]+info[i]; mat_displs[i+1] = global_num_rows*displs[i+1]; mat_info[i] = global_num_rows*info[i]; } hypre_ParAMGDataBVec(amg_data) = hypre_CTAlloc(HYPRE_Real, global_num_rows); A_mat_local_size = global_num_rows*num_rows; A_mat_local = hypre_CTAlloc(HYPRE_Real, A_mat_local_size); A_mat = hypre_CTAlloc(HYPRE_Real, global_num_rows*global_num_rows); /* load local matrix into A_mat_local */ for (i = 0; i < num_rows; i++) { for (jj = A_diag_i[i]; jj < A_diag_i[i+1]; jj++) { /* need col major */ column = A_diag_j[jj]+first_row_index; A_mat_local[i*global_num_rows + column] = A_diag_data[jj]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { /* need col major */ column = col_map_offd[A_offd_j[jj]]; A_mat_local[i*global_num_rows + column] = A_offd_data[jj]; } } hypre_MPI_Allgatherv( A_mat_local, A_mat_local_size, HYPRE_MPI_REAL, A_mat, mat_info, mat_displs, HYPRE_MPI_REAL, new_comm); if (relax_type == 99) { HYPRE_Real *AT_mat; AT_mat = hypre_CTAlloc(HYPRE_Real, global_num_rows*global_num_rows); for (i=0; i < global_num_rows; i++) for (jj=0; jj < global_num_rows; jj++) AT_mat[i*global_num_rows + jj] = A_mat[i+ jj*global_num_rows]; hypre_ParAMGDataAMat(amg_data) = AT_mat; hypre_TFree (A_mat); } else hypre_ParAMGDataAMat(amg_data) = A_mat; hypre_ParAMGDataCommInfo(amg_data) = comm_info; hypre_ParAMGDataNewComm(amg_data) = new_comm; hypre_TFree(mat_info); hypre_TFree(mat_displs); hypre_TFree(A_mat_local); } #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_GS_ELIM_SETUP] += hypre_MPI_Wtime(); #endif return hypre_error_flag; } HYPRE_Int hypre_GaussElimSolve (hypre_ParAMGData *amg_data, HYPRE_Int level, HYPRE_Int relax_type) { #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_GS_ELIM_SOLVE] -= hypre_MPI_Wtime(); #endif hypre_ParCSRMatrix *A = hypre_ParAMGDataAArray(amg_data)[level]; HYPRE_Int n = hypre_CSRMatrixNumRows(hypre_ParCSRMatrixDiag(A)); HYPRE_Int error_flag = 0; if (n) { MPI_Comm new_comm = hypre_ParAMGDataNewComm(amg_data); hypre_ParVector *f = hypre_ParAMGDataFArray(amg_data)[level]; hypre_ParVector *u = hypre_ParAMGDataUArray(amg_data)[level]; HYPRE_Real *A_mat = hypre_ParAMGDataAMat(amg_data); HYPRE_Real *b_vec = hypre_ParAMGDataBVec(amg_data); HYPRE_Real *f_data = hypre_VectorData(hypre_ParVectorLocalVector(f)); HYPRE_Real *u_data = hypre_VectorData(hypre_ParVectorLocalVector(u)); HYPRE_Real *A_tmp; HYPRE_Int *comm_info = hypre_ParAMGDataCommInfo(amg_data); HYPRE_Int *displs, *info; HYPRE_Int n_global = hypre_ParCSRMatrixGlobalNumRows(A); HYPRE_Int new_num_procs, i, my_info; HYPRE_Int first_index = hypre_ParCSRMatrixFirstRowIndex(A); HYPRE_Int one_i = 1; hypre_MPI_Comm_size(new_comm, &new_num_procs); info = &comm_info[0]; displs = &comm_info[new_num_procs]; hypre_MPI_Allgatherv ( f_data, n, HYPRE_MPI_REAL, b_vec, info, displs, HYPRE_MPI_REAL, new_comm ); A_tmp = hypre_CTAlloc (HYPRE_Real, n_global*n_global); for (i=0; i < n_global*n_global; i++) A_tmp[i] = A_mat[i]; if (relax_type == 9) { error_flag = gselim(A_tmp,b_vec,n_global); } for (i = 0; i < n; i++) { u_data[i] = b_vec[first_index+i]; } hypre_TFree(A_tmp); } if (error_flag) hypre_error(HYPRE_ERROR_GENERIC); #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_GS_ELIM_SOLVE] += hypre_MPI_Wtime(); #endif return hypre_error_flag; } HYPRE_Int gselim(HYPRE_Real *A, HYPRE_Real *x, HYPRE_Int n) { HYPRE_Int err_flag = 0; HYPRE_Int j,k,m; HYPRE_Real factor; HYPRE_Real divA; if (n==1) /* A is 1x1 */ { if (A[0] != 0.0) { x[0] = x[0]/A[0]; return(err_flag); } else { err_flag = 1; return(err_flag); } } else /* A is nxn. Forward elimination */ { for (k = 0; k < n-1; k++) { if (A[k*n+k] != 0.0) { divA = 1.0/A[k*n+k]; for (j = k+1; j < n; j++) { if (A[j*n+k] != 0.0) { factor = A[j*n+k]*divA; for (m = k+1; m < n; m++) { A[j*n+m] -= factor * A[k*n+m]; } /* Elimination step for rhs */ x[j] -= factor * x[k]; } } } } /* Back Substitution */ for (k = n-1; k > 0; --k) { if (A[k*n+k] != 0.0) { x[k] /= A[k*n+k]; for (j = 0; j < k; j++) { if (A[j*n+k] != 0.0) { x[j] -= x[k] * A[j*n+k]; } } } } if (A[0] != 0.0) x[0] /= A[0]; return(err_flag); } }
151,205
34.15601
98
c
AMG
AMG-master/parcsr_ls/par_relax_interface.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /****************************************************************************** * * Relaxation scheme * *****************************************************************************/ #include "_hypre_parcsr_ls.h" /*-------------------------------------------------------------------------- * hypre_BoomerAMGRelax *--------------------------------------------------------------------------*/ HYPRE_Int hypre_BoomerAMGRelaxIF( hypre_ParCSRMatrix *A, hypre_ParVector *f, HYPRE_Int *cf_marker, HYPRE_Int relax_type, HYPRE_Int relax_order, HYPRE_Int cycle_type, HYPRE_Real relax_weight, HYPRE_Real omega, HYPRE_Real *l1_norms, hypre_ParVector *u, hypre_ParVector *Vtemp, hypre_ParVector *Ztemp ) { HYPRE_Int i, Solve_err_flag = 0; HYPRE_Int relax_points[2]; if (relax_order == 1 && cycle_type < 3) { if (cycle_type < 2) { relax_points[0] = 1; relax_points[1] = -1; } else { relax_points[0] = -1; relax_points[1] = 1; } for (i=0; i < 2; i++) Solve_err_flag = hypre_BoomerAMGRelax(A, f, cf_marker, relax_type, relax_points[i], relax_weight, omega, l1_norms, u, Vtemp, Ztemp); } else { Solve_err_flag = hypre_BoomerAMGRelax(A, f, cf_marker, relax_type, 0, relax_weight, omega, l1_norms, u, Vtemp, Ztemp); } return Solve_err_flag; }
3,608
36.59375
81
c
AMG
AMG-master/parcsr_ls/par_relax_more.c
/****************************************************************************** * * a few more relaxation schemes: Chebychev, FCF-Jacobi, CG - * these do not go through the CF interface (hypre_BoomerAMGRelaxIF) * *****************************************************************************/ #include "_hypre_parcsr_ls.h" #include "float.h" HYPRE_Int hypre_LINPACKcgtql1(HYPRE_Int*,HYPRE_Real *,HYPRE_Real *,HYPRE_Int *); /****************************************************************************** * *use max norm to estimate largest eigenvalue * *****************************************************************************/ HYPRE_Int hypre_ParCSRMaxEigEstimate(hypre_ParCSRMatrix *A, /* matrix to relax with */ HYPRE_Int scale, /* scale by diagonal?*/ HYPRE_Real *max_eig) { HYPRE_Real e_max; HYPRE_Real row_sum, max_norm; HYPRE_Real *A_diag_data; HYPRE_Real *A_offd_data; HYPRE_Real temp; HYPRE_Real diag_value; HYPRE_Int pos_diag, neg_diag; HYPRE_Int A_num_rows; HYPRE_Int *A_diag_i; HYPRE_Int *A_offd_i; HYPRE_Int j; HYPRE_Int i, start; /* estimate with the inf-norm of A - should be ok for SPD matrices */ A_num_rows = hypre_CSRMatrixNumRows(hypre_ParCSRMatrixDiag(A)); A_diag_i = hypre_CSRMatrixI(hypre_ParCSRMatrixDiag(A)); A_diag_data = hypre_CSRMatrixData(hypre_ParCSRMatrixDiag(A)); A_offd_i = hypre_CSRMatrixI(hypre_ParCSRMatrixOffd(A)); A_offd_data = hypre_CSRMatrixData(hypre_ParCSRMatrixOffd(A)); max_norm = 0.0; pos_diag = neg_diag = 0; for ( i = 0; i < A_num_rows; i++ ) { start = A_diag_i[i]; diag_value = A_diag_data[start]; if (diag_value > 0) { pos_diag++; } if (diag_value < 0) { neg_diag++; diag_value = -diag_value; } row_sum = diag_value; /*for (j = 0; j < row_length; j++)*/ for (j = start+1; j < A_diag_i[i+1]; j++) { row_sum += fabs(A_diag_data[j]); } for (j = A_offd_i[i]; j < A_offd_i[i+1]; j++) { row_sum += fabs(A_offd_data[j]); } if (scale) { if (diag_value != 0.0) row_sum = row_sum/diag_value; } if ( row_sum > max_norm ) max_norm = row_sum; } /* get max across procs */ hypre_MPI_Allreduce(&max_norm, &temp, 1, HYPRE_MPI_REAL, hypre_MPI_MAX, hypre_ParCSRMatrixComm(A)); max_norm = temp; /* from Charles */ if ( pos_diag == 0 && neg_diag > 0 ) max_norm = - max_norm; /* eig estimates */ e_max = max_norm; /* return */ *max_eig = e_max; return hypre_error_flag; } /****************************************************************************** use CG to get the eigenvalue estimate scale means get eig est of (D^{-1/2} A D^{-1/2} ******************************************************************************/ HYPRE_Int hypre_ParCSRMaxEigEstimateCG(hypre_ParCSRMatrix *A, /* matrix to relax with */ HYPRE_Int scale, /* scale by diagonal?*/ HYPRE_Int max_iter, HYPRE_Real *max_eig, HYPRE_Real *min_eig) { HYPRE_Int i, j, err; hypre_ParVector *p; hypre_ParVector *s; hypre_ParVector *r; hypre_ParVector *ds; hypre_ParVector *u; HYPRE_Real *tridiag = NULL; HYPRE_Real *trioffd = NULL; HYPRE_Real lambda_max ; HYPRE_Real beta, gamma = 0.0, alpha, sdotp, gamma_old, alphainv; HYPRE_Real diag; HYPRE_Real lambda_min; HYPRE_Real *s_data, *p_data, *ds_data, *u_data; HYPRE_Int local_size = hypre_CSRMatrixNumRows(hypre_ParCSRMatrixDiag(A)); hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); HYPRE_Real *A_diag_data = hypre_CSRMatrixData(A_diag); HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag); /* check the size of A - don't iterate more than the size */ HYPRE_Int size = hypre_ParCSRMatrixGlobalNumRows(A); if (size < max_iter) max_iter = size; /* create some temp vectors: p, s, r , ds, u*/ r = hypre_ParVectorCreate(hypre_ParCSRMatrixComm(A), hypre_ParCSRMatrixGlobalNumRows(A), hypre_ParCSRMatrixRowStarts(A)); hypre_ParVectorInitialize(r); hypre_ParVectorSetPartitioningOwner(r,0); p = hypre_ParVectorCreate(hypre_ParCSRMatrixComm(A), hypre_ParCSRMatrixGlobalNumRows(A), hypre_ParCSRMatrixRowStarts(A)); hypre_ParVectorInitialize(p); hypre_ParVectorSetPartitioningOwner(p,0); s = hypre_ParVectorCreate(hypre_ParCSRMatrixComm(A), hypre_ParCSRMatrixGlobalNumRows(A), hypre_ParCSRMatrixRowStarts(A)); hypre_ParVectorInitialize(s); hypre_ParVectorSetPartitioningOwner(s,0); ds = hypre_ParVectorCreate(hypre_ParCSRMatrixComm(A), hypre_ParCSRMatrixGlobalNumRows(A), hypre_ParCSRMatrixRowStarts(A)); hypre_ParVectorInitialize(ds); hypre_ParVectorSetPartitioningOwner(ds,0); u = hypre_ParVectorCreate(hypre_ParCSRMatrixComm(A), hypre_ParCSRMatrixGlobalNumRows(A), hypre_ParCSRMatrixRowStarts(A)); hypre_ParVectorInitialize(u); hypre_ParVectorSetPartitioningOwner(u,0); /* point to local data */ s_data = hypre_VectorData(hypre_ParVectorLocalVector(s)); p_data = hypre_VectorData(hypre_ParVectorLocalVector(p)); ds_data = hypre_VectorData(hypre_ParVectorLocalVector(ds)); u_data = hypre_VectorData(hypre_ParVectorLocalVector(u)); /* make room for tri-diag matrix */ tridiag = hypre_CTAlloc(HYPRE_Real, max_iter+1); trioffd = hypre_CTAlloc(HYPRE_Real, max_iter+1); for (i=0; i < max_iter + 1; i++) { tridiag[i] = 0; trioffd[i] = 0; } /* set residual to random */ hypre_ParVectorSetRandomValues(r,1); if (scale) { for (i = 0; i < local_size; i++) { diag = A_diag_data[A_diag_i[i]]; ds_data[i] = 1/sqrt(diag); } } else { /* set ds to 1 */ hypre_ParVectorSetConstantValues(ds,1.0); } /* gamma = <r,Cr> */ gamma = hypre_ParVectorInnerProd(r,p); /* for the initial filling of the tridiag matrix */ beta = 1.0; i = 0; while (i < max_iter) { /* s = C*r */ /* TO DO: C = diag scale */ hypre_ParVectorCopy(r, s); /*gamma = <r,Cr> */ gamma_old = gamma; gamma = hypre_ParVectorInnerProd(r,s); if (i==0) { beta = 1.0; /* p_0 = C*r */ hypre_ParVectorCopy(s, p); } else { /* beta = gamma / gamma_old */ beta = gamma / gamma_old; /* p = s + beta p */ #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(j) HYPRE_SMP_SCHEDULE #endif for (j=0; j < local_size; j++) { p_data[j] = s_data[j] + beta*p_data[j]; } } if (scale) { /* s = D^{-1/2}A*D^{-1/2}*p */ for (j = 0; j < local_size; j++) { u_data[j] = ds_data[j] * p_data[j]; } hypre_ParCSRMatrixMatvec(1.0, A, u, 0.0, s); for (j = 0; j < local_size; j++) { s_data[j] = ds_data[j] * s_data[j]; } } else { /* s = A*p */ hypre_ParCSRMatrixMatvec(1.0, A, p, 0.0, s); } /* <s,p> */ sdotp = hypre_ParVectorInnerProd(s,p); /* alpha = gamma / <s,p> */ alpha = gamma/sdotp; /* get tridiagonal matrix */ alphainv = 1.0/alpha; tridiag[i+1] = alphainv; tridiag[i] *= beta; tridiag[i] += alphainv; trioffd[i+1] = alphainv; trioffd[i] *= sqrt(beta); /* x = x + alpha*p */ /* don't need */ /* r = r - alpha*s */ hypre_ParVectorAxpy( -alpha, s, r); i++; } /* eispack routine - eigenvalues return in tridiag and ordered*/ hypre_LINPACKcgtql1(&i,tridiag,trioffd,&err); lambda_max = tridiag[i-1]; lambda_min = tridiag[0]; /* hypre_printf("linpack max eig est = %g\n", lambda_max);*/ /* hypre_printf("linpack min eig est = %g\n", lambda_min);*/ hypre_TFree(tridiag); hypre_TFree(trioffd); hypre_ParVectorDestroy(r); hypre_ParVectorDestroy(s); hypre_ParVectorDestroy(p); hypre_ParVectorDestroy(ds); hypre_ParVectorDestroy(u); /* return */ *max_eig = lambda_max; *min_eig = lambda_min; return hypre_error_flag; } /****************************************************************************** Chebyshev relaxation Can specify order 1-4 (this is the order of the resid polynomial)- here we explicitly code the coefficients (instead of iteratively determining) variant 0: standard chebyshev this is rlx 11 if scale = 0, and 16 if scale == 1 variant 1: modified cheby: T(t)* f(t) where f(t) = (1-b/t) this is rlx 15 if scale = 0, and 17 if scale == 1 ratio indicates the percentage of the whole spectrum to use (so .5 means half, and .1 means 10percent) *******************************************************************************/ HYPRE_Int hypre_ParCSRRelax_Cheby(hypre_ParCSRMatrix *A, /* matrix to relax with */ hypre_ParVector *f, /* right-hand side */ HYPRE_Real max_eig, HYPRE_Real min_eig, HYPRE_Real fraction, HYPRE_Int order, /* polynomial order */ HYPRE_Int scale, /* scale by diagonal?*/ HYPRE_Int variant, hypre_ParVector *u, /* initial/updated approximation */ hypre_ParVector *v /* temporary vector */, hypre_ParVector *r /*another temp vector */ ) { hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); HYPRE_Real *A_diag_data = hypre_CSRMatrixData(A_diag); HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag); HYPRE_Real *u_data = hypre_VectorData(hypre_ParVectorLocalVector(u)); HYPRE_Real *f_data = hypre_VectorData(hypre_ParVectorLocalVector(f)); HYPRE_Real *v_data = hypre_VectorData(hypre_ParVectorLocalVector(v)); HYPRE_Real *r_data = hypre_VectorData(hypre_ParVectorLocalVector(r)); HYPRE_Real theta, delta; HYPRE_Real den; HYPRE_Real upper_bound, lower_bound; HYPRE_Int i, j; HYPRE_Int num_rows = hypre_CSRMatrixNumRows(A_diag); HYPRE_Real coefs[5]; HYPRE_Real mult; HYPRE_Real *orig_u; HYPRE_Real tmp_d; HYPRE_Int cheby_order; HYPRE_Real *ds_data, *tmp_data; HYPRE_Real diag; hypre_ParVector *ds; hypre_ParVector *tmp_vec; /* u = u + p(A)r */ if (order > 4) order = 4; if (order < 1) order = 1; /* we are using the order of p(A) */ cheby_order = order -1; /* make sure we are large enough - Adams et al. 2003 */ upper_bound = max_eig * 1.1; /* lower_bound = max_eig/fraction; */ lower_bound = (upper_bound - min_eig)* fraction + min_eig; /* theta and delta */ theta = (upper_bound + lower_bound)/2; delta = (upper_bound - lower_bound)/2; if (variant == 1 ) { switch ( cheby_order ) /* these are the corresponding cheby polynomials: u = u_o + s(A)r_0 - so order is one less that resid poly: r(t) = 1 - t*s(t) */ { case 0: coefs[0] = 1.0/theta; break; case 1: /* (del - t + 2*th)/(th^2 + del*th) */ den = (theta*theta + delta*theta); coefs[0] = (delta + 2*theta)/den; coefs[1] = -1.0/den; break; case 2: /* (4*del*th - del^2 - t*(2*del + 6*th) + 2*t^2 + 6*th^2)/(2*del*th^2 - del^2*th - del^3 + 2*th^3)*/ den = 2*delta*theta*theta - delta*delta*theta - pow(delta,3) + 2*pow(theta,3); coefs[0] = (4*delta*theta - pow(delta,2) + 6*pow(theta,2))/den; coefs[1] = -(2*delta + 6*theta)/den; coefs[2] = 2/den; break; case 3: /* -(6*del^2*th - 12*del*th^2 - t^2*(4*del + 16*th) + t*(12*del*th - 3*del^2 + 24*th^2) + 3*del^3 + 4*t^3 - 16*th^3)/(4*del*th^3 - 3*del^2*th^2 - 3*del^3*th + 4*th^4)*/ den = - (4*delta*pow(theta,3) - 3*pow(delta,2)*pow(theta,2) - 3*pow(delta,3)*theta + 4*pow(theta,4) ); coefs[0] = (6*pow(delta,2)*theta - 12*delta*pow(theta,2) + 3*pow(delta,3) - 16*pow(theta,3) )/den; coefs[1] = (12*delta*theta - 3*pow(delta,2) + 24*pow(theta,2))/den; coefs[2] = -( 4*delta + 16*theta)/den; coefs[3] = 4/den; break; } } else /* standard chebyshev */ { switch ( cheby_order ) /* these are the corresponding cheby polynomials: u = u_o + s(A)r_0 - so order is one less thatn resid poly: r(t) = 1 - t*s(t) */ { case 0: coefs[0] = 1.0/theta; break; case 1: /* ( 2*t - 4*th)/(del^2 - 2*th^2) */ den = delta*delta - 2*theta*theta; coefs[0] = -4*theta/den; coefs[1] = 2/den; break; case 2: /* (3*del^2 - 4*t^2 + 12*t*th - 12*th^2)/(3*del^2*th - 4*th^3)*/ den = 3*(delta*delta)*theta - 4*(theta*theta*theta); coefs[0] = (3*delta*delta - 12 *theta*theta)/den; coefs[1] = 12*theta/den; coefs[2] = -4/den; break; case 3: /*(t*(8*del^2 - 48*th^2) - 16*del^2*th + 32*t^2*th - 8*t^3 + 32*th^3)/(del^4 - 8*del^2*th^2 + 8*th^4)*/ den = pow(delta,4) - 8*delta*delta*theta*theta + 8*pow(theta,4); coefs[0] = (32*pow(theta,3)- 16*delta*delta*theta)/den; coefs[1] = (8*delta*delta - 48*theta*theta)/den; coefs[2] = 32*theta/den; coefs[3] = -8/den; break; } } orig_u = hypre_CTAlloc(HYPRE_Real, num_rows); if (!scale) { /* get residual: r = f - A*u */ hypre_ParVectorCopy(f, r); hypre_ParCSRMatrixMatvec(-1.0, A, u, 1.0, r); for ( i = 0; i < num_rows; i++ ) { orig_u[i] = u_data[i]; u_data[i] = r_data[i] * coefs[cheby_order]; } for (i = cheby_order - 1; i >= 0; i-- ) { hypre_ParCSRMatrixMatvec(1.0, A, u, 0.0, v); mult = coefs[i]; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(j) HYPRE_SMP_SCHEDULE #endif for ( j = 0; j < num_rows; j++ ) { u_data[j] = mult * r_data[j] + v_data[j]; } } #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for ( i = 0; i < num_rows; i++ ) { u_data[i] = orig_u[i] + u_data[i]; } } else /* scaling! */ { /*grab 1/sqrt(diagonal) */ ds = hypre_ParVectorCreate(hypre_ParCSRMatrixComm(A), hypre_ParCSRMatrixGlobalNumRows(A), hypre_ParCSRMatrixRowStarts(A)); hypre_ParVectorInitialize(ds); hypre_ParVectorSetPartitioningOwner(ds,0); ds_data = hypre_VectorData(hypre_ParVectorLocalVector(ds)); tmp_vec = hypre_ParVectorCreate(hypre_ParCSRMatrixComm(A), hypre_ParCSRMatrixGlobalNumRows(A), hypre_ParCSRMatrixRowStarts(A)); hypre_ParVectorInitialize(tmp_vec); hypre_ParVectorSetPartitioningOwner(tmp_vec,0); tmp_data = hypre_VectorData(hypre_ParVectorLocalVector(tmp_vec)); /* get ds_data and get scaled residual: r = D^(-1/2)f - * D^(-1/2)A*u */ #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(j,diag) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < num_rows; j++) { diag = A_diag_data[A_diag_i[j]]; ds_data[j] = 1/sqrt(diag); r_data[j] = ds_data[j] * f_data[j]; } hypre_ParCSRMatrixMatvec(-1.0, A, u, 0.0, tmp_vec); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(j) HYPRE_SMP_SCHEDULE #endif for ( j = 0; j < num_rows; j++ ) { r_data[j] += ds_data[j] * tmp_data[j]; } /* save original u, then start the iteration by multiplying r by the cheby coef.*/ #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(j) HYPRE_SMP_SCHEDULE #endif for ( j = 0; j < num_rows; j++ ) { orig_u[j] = u_data[j]; /* orig, unscaled u */ u_data[j] = r_data[j] * coefs[cheby_order]; } /* now do the other coefficients */ for (i = cheby_order - 1; i >= 0; i-- ) { /* v = D^(-1/2)AD^(-1/2)u */ #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(j) HYPRE_SMP_SCHEDULE #endif for ( j = 0; j < num_rows; j++ ) { tmp_data[j] = ds_data[j] * u_data[j]; } hypre_ParCSRMatrixMatvec(1.0, A, tmp_vec, 0.0, v); /* u_new = coef*r + v*/ mult = coefs[i]; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(j,tmp_d) HYPRE_SMP_SCHEDULE #endif for ( j = 0; j < num_rows; j++ ) { tmp_d = ds_data[j]* v_data[j]; u_data[j] = mult * r_data[j] + tmp_d; } } /* end of cheby_order loop */ /* now we have to scale u_data before adding it to u_orig*/ #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(j) HYPRE_SMP_SCHEDULE #endif for ( j = 0; j < num_rows; j++ ) { u_data[j] = orig_u[j] + ds_data[j]*u_data[j]; } hypre_ParVectorDestroy(ds); hypre_ParVectorDestroy(tmp_vec); }/* end of scaling code */ hypre_TFree(orig_u); return hypre_error_flag; } /*-------------------------------------------------------------------------- * hypre_BoomerAMGRelax_FCFJacobi *--------------------------------------------------------------------------*/ HYPRE_Int hypre_BoomerAMGRelax_FCFJacobi( hypre_ParCSRMatrix *A, hypre_ParVector *f, HYPRE_Int *cf_marker, HYPRE_Real relax_weight, hypre_ParVector *u, hypre_ParVector *Vtemp) { HYPRE_Int i; HYPRE_Int relax_points[3]; HYPRE_Int relax_type = 0; hypre_ParVector *Ztemp = NULL; relax_points[0] = -1; /*F */ relax_points[1] = 1; /*C */ relax_points[2] = -1; /*F */ /* if we are on the coarsest level ,the cf_marker will be null and we just do one sweep regular jacobi */ if (cf_marker == NULL) { hypre_BoomerAMGRelax(A, f, cf_marker, relax_type, 0, relax_weight, 0.0, NULL, u, Vtemp, Ztemp); } else { for (i=0; i < 3; i++) hypre_BoomerAMGRelax(A, f, cf_marker, relax_type, relax_points[i], relax_weight, 0.0, NULL, u, Vtemp, Ztemp); } return hypre_error_flag; } /*-------------------------------------------------------------------------- * CG Smoother - * *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParCSRRelax_CG( HYPRE_Solver solver, hypre_ParCSRMatrix *A, hypre_ParVector *f, hypre_ParVector *u, HYPRE_Int num_its) { HYPRE_PCGSetMaxIter(solver, num_its); /* max iterations */ HYPRE_ParCSRPCGSolve(solver, (HYPRE_ParCSRMatrix)A, (HYPRE_ParVector)f, (HYPRE_ParVector)u); #if 0 { HYPRE_Int myid; HYPRE_Int num_iterations; HYPRE_Real final_res_norm; hypre_MPI_Comm_rank(hypre_MPI_COMM_WORLD, &myid); HYPRE_PCGGetNumIterations(solver, &num_iterations); HYPRE_PCGGetFinalRelativeResidualNorm(solver, &final_res_norm); if (myid ==0) { hypre_printf(" -----CG PCG Iterations = %d\n", num_iterations); hypre_printf(" -----CG PCG Final Relative Residual Norm = %e\n", final_res_norm); } } #endif return hypre_error_flag; } /* tql1.f -- this is the eispack translation - from Barry Smith in Petsc Note that this routine always uses real numbers (not complex) even if the underlying matrix is Hermitian. This is because the Lanczos process applied to Hermitian matrices always produces a real, symmetric tridiagonal matrix. */ HYPRE_Real hypre_LINPACKcgpthy(HYPRE_Real*,HYPRE_Real*); HYPRE_Int hypre_LINPACKcgtql1(HYPRE_Int *n,HYPRE_Real *d,HYPRE_Real *e,HYPRE_Int *ierr) { /* System generated locals */ HYPRE_Int i__1,i__2; HYPRE_Real d__1,d__2,c_b10 = 1.0; /* Local variables */ HYPRE_Real c,f,g,h; HYPRE_Int i,j,l,m; HYPRE_Real p,r,s,c2,c3 = 0.0; HYPRE_Int l1,l2; HYPRE_Real s2 = 0.0; HYPRE_Int ii; HYPRE_Real dl1,el1; HYPRE_Int mml; HYPRE_Real tst1,tst2; /* THIS SUBROUTINE IS A TRANSLATION OF THE ALGOL PROCEDURE TQL1, */ /* NUM. MATH. 11, 293-306(1968) BY BOWDLER, MARTIN, REINSCH, AND */ /* WILKINSON. */ /* HANDBOOK FOR AUTO. COMP., VOL.II-LINEAR ALGEBRA, 227-240(1971). */ /* THIS SUBROUTINE FINDS THE EIGENVALUES OF A SYMMETRIC */ /* TRIDIAGONAL MATRIX BY THE QL METHOD. */ /* ON INPUT */ /* N IS THE ORDER OF THE MATRIX. */ /* D CONTAINS THE DIAGONAL ELEMENTS OF THE INPUT MATRIX. */ /* E CONTAINS THE SUBDIAGONAL ELEMENTS OF THE INPUT MATRIX */ /* IN ITS LAST N-1 POSITIONS. E(1) IS ARBITRARY. */ /* ON OUTPUT */ /* D CONTAINS THE EIGENVALUES IN ASCENDING ORDER. IF AN */ /* ERROR EXIT IS MADE, THE EIGENVALUES ARE CORRECT AND */ /* ORDERED FOR INDICES 1,2,...IERR-1, BUT MAY NOT BE */ /* THE SMALLEST EIGENVALUES. */ /* E HAS BEEN DESTROYED. */ /* IERR IS SET TO */ /* ZERO FOR NORMAL RETURN, */ /* J IF THE J-TH EIGENVALUE HAS NOT BEEN */ /* DETERMINED AFTER 30 ITERATIONS. */ /* CALLS CGPTHY FOR DSQRT(A*A + B*B) . */ /* QUESTIONS AND COMMENTS SHOULD BE DIRECTED TO BURTON S. GARBOW, */ /* MATHEMATICS AND COMPUTER SCIENCE DIV, ARGONNE NATIONAL LABORATORY */ /* THIS VERSION DATED AUGUST 1983. */ /* ------------------------------------------------------------------ */ HYPRE_Real ds; --e; --d; *ierr = 0; if (*n == 1) { goto L1001; } i__1 = *n; for (i = 2; i <= i__1; ++i) { e[i - 1] = e[i]; } f = 0.; tst1 = 0.; e[*n] = 0.; i__1 = *n; for (l = 1; l <= i__1; ++l) { j = 0; h = (d__1 = d[l],fabs(d__1)) + (d__2 = e[l],fabs(d__2)); if (tst1 < h) { tst1 = h; } /* .......... LOOK FOR SMALL SUB-DIAGONAL ELEMENT .......... */ i__2 = *n; for (m = l; m <= i__2; ++m) { tst2 = tst1 + (d__1 = e[m],fabs(d__1)); if (tst2 == tst1) { goto L120; } /* .......... E(N) IS ALWAYS ZERO,SO THERE IS NO EXIT */ /* THROUGH THE BOTTOM OF THE LOOP .......... */ } L120: if (m == l) { goto L210; } L130: if (j == 30) { goto L1000; } ++j; /* .......... FORM SHIFT .......... */ l1 = l + 1; l2 = l1 + 1; g = d[l]; p = (d[l1] - g) / (e[l] * 2.); r = hypre_LINPACKcgpthy(&p,&c_b10); ds = 1.0; if (p < 0.0) ds = -1.0; d[l] = e[l] / (p + ds*r); d[l1] = e[l] * (p + ds*r); dl1 = d[l1]; h = g - d[l]; if (l2 > *n) { goto L145; } i__2 = *n; for (i = l2; i <= i__2; ++i) { d[i] -= h; } L145: f += h; /* .......... QL TRANSFORMATION .......... */ p = d[m]; c = 1.; c2 = c; el1 = e[l1]; s = 0.; mml = m - l; /* .......... FOR I=M-1 STEP -1 UNTIL L DO -- .......... */ i__2 = mml; for (ii = 1; ii <= i__2; ++ii) { c3 = c2; c2 = c; s2 = s; i = m - ii; g = c * e[i]; h = c * p; r = hypre_LINPACKcgpthy(&p,&e[i]); e[i + 1] = s * r; s = e[i] / r; c = p / r; p = c * d[i] - s * g; d[i + 1] = h + s * (c * g + s * d[i]); } p = -s * s2 * c3 * el1 * e[l] / dl1; e[l] = s * p; d[l] = c * p; tst2 = tst1 + (d__1 = e[l],fabs(d__1)); if (tst2 > tst1) { goto L130; } L210: p = d[l] + f; /* .......... ORDER EIGENVALUES .......... */ if (l == 1) { goto L250; } /* .......... FOR I=L STEP -1 UNTIL 2 DO -- .......... */ i__2 = l; for (ii = 2; ii <= i__2; ++ii) { i = l + 2 - ii; if (p >= d[i - 1]) { goto L270; } d[i] = d[i - 1]; } L250: i = 1; L270: d[i] = p; } goto L1001; /* .......... SET ERROR -- NO CONVERGENCE TO AN */ /* EIGENVALUE AFTER 30 ITERATIONS .......... */ L1000: *ierr = l; L1001: return 0; } /* cgtql1_ */ HYPRE_Real hypre_LINPACKcgpthy(HYPRE_Real *a,HYPRE_Real *b) { /* System generated locals */ HYPRE_Real ret_val,d__1,d__2,d__3; /* Local variables */ HYPRE_Real p,r,s,t,u; /* FINDS DSQRT(A**2+B**2) WITHOUT OVERFLOW OR DESTRUCTIVE UNDERFLOW */ /* Computing MAX */ d__1 = fabs(*a),d__2 = fabs(*b); p = hypre_max(d__1,d__2); if (!p) { goto L20; } /* Computing MIN */ d__2 = fabs(*a),d__3 = fabs(*b); /* Computing 2nd power */ d__1 = hypre_min(d__2,d__3) / p; r = d__1 * d__1; L10: t = r + 4.; if (t == 4.) { goto L20; } s = r / t; u = s * 2. + 1.; p = u * p; /* Computing 2nd power */ d__1 = s / u; r = d__1 * d__1 * r; goto L10; L20: ret_val = p; return ret_val; } /* cgpthy_ */ /*-------------------------------------------------------------------------- * hypre_ParCSRRelax_L1_Jacobi (same as the one in AMS, but this allows CF) u += w D^{-1}(f - A u), where D_ii = ||A(i,:)||_1 *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParCSRRelax_L1_Jacobi( hypre_ParCSRMatrix *A, hypre_ParVector *f, HYPRE_Int *cf_marker, HYPRE_Int relax_points, HYPRE_Real relax_weight, HYPRE_Real *l1_norms, hypre_ParVector *u, hypre_ParVector *Vtemp ) { MPI_Comm comm = hypre_ParCSRMatrixComm(A); hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); HYPRE_Real *A_diag_data = hypre_CSRMatrixData(A_diag); HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag); HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag); hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd); HYPRE_Real *A_offd_data = hypre_CSRMatrixData(A_offd); HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd); hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A); hypre_ParCSRCommHandle *comm_handle; HYPRE_Int n = hypre_CSRMatrixNumRows(A_diag); HYPRE_Int num_cols_offd = hypre_CSRMatrixNumCols(A_offd); hypre_Vector *u_local = hypre_ParVectorLocalVector(u); HYPRE_Real *u_data = hypre_VectorData(u_local); hypre_Vector *f_local = hypre_ParVectorLocalVector(f); HYPRE_Real *f_data = hypre_VectorData(f_local); hypre_Vector *Vtemp_local = hypre_ParVectorLocalVector(Vtemp); HYPRE_Real *Vtemp_data = hypre_VectorData(Vtemp_local); HYPRE_Real *Vext_data = NULL; HYPRE_Real *v_buf_data; HYPRE_Int i, j; HYPRE_Int ii, jj; HYPRE_Int num_sends; HYPRE_Int index, start; HYPRE_Int num_procs, my_id ; HYPRE_Real zero = 0.0; HYPRE_Real res; hypre_MPI_Comm_size(comm,&num_procs); hypre_MPI_Comm_rank(comm,&my_id); if (num_procs > 1) { num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); v_buf_data = hypre_CTAlloc(HYPRE_Real, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends)); Vext_data = hypre_CTAlloc(HYPRE_Real,num_cols_offd); if (num_cols_offd) { A_offd_j = hypre_CSRMatrixJ(A_offd); A_offd_data = hypre_CSRMatrixData(A_offd); } index = 0; for (i = 0; i < num_sends; i++) { start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j=start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++) v_buf_data[index++] = u_data[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)]; } comm_handle = hypre_ParCSRCommHandleCreate( 1, comm_pkg, v_buf_data, Vext_data); } /*----------------------------------------------------------------- * Copy current approximation into temporary vector. *-----------------------------------------------------------------*/ #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) { Vtemp_data[i] = u_data[i]; } if (num_procs > 1) { hypre_ParCSRCommHandleDestroy(comm_handle); comm_handle = NULL; } /*----------------------------------------------------------------- * Relax all points. *-----------------------------------------------------------------*/ if (relax_points == 0) { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,ii,jj,res) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (A_diag_data[A_diag_i[i]] != zero) { res = f_data[i]; for (jj = A_diag_i[i]; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res -= A_diag_data[jj] * Vtemp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] += (relax_weight*res)/l1_norms[i]; } } } /*----------------------------------------------------------------- * Relax only C or F points as determined by relax_points. *-----------------------------------------------------------------*/ else { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,ii,jj,res) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n; i++) { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if (cf_marker[i] == relax_points && A_diag_data[A_diag_i[i]] != zero) { res = f_data[i]; for (jj = A_diag_i[i]; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res -= A_diag_data[jj] * Vtemp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * Vext_data[ii]; } u_data[i] += (relax_weight * res)/l1_norms[i]; } } } if (num_procs > 1) { hypre_TFree(Vext_data); hypre_TFree(v_buf_data); } return 0; }
33,880
27.884058
185
c
AMG
AMG-master/parcsr_ls/par_scaled_matnorm.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /****************************************************************************** * * computes |D^-1/2 A D^-1/2 |_sup where D diagonal matrix * *****************************************************************************/ #include "_hypre_parcsr_ls.h" /*-------------------------------------------------------------------------- * hypre_ParCSRMatrixScaledNorm *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParCSRMatrixScaledNorm( hypre_ParCSRMatrix *A, HYPRE_Real *scnorm) { hypre_ParCSRCommHandle *comm_handle; hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A); MPI_Comm comm = hypre_ParCSRMatrixComm(A); hypre_CSRMatrix *diag = hypre_ParCSRMatrixDiag(A); HYPRE_Int *diag_i = hypre_CSRMatrixI(diag); HYPRE_Int *diag_j = hypre_CSRMatrixJ(diag); HYPRE_Real *diag_data = hypre_CSRMatrixData(diag); hypre_CSRMatrix *offd = hypre_ParCSRMatrixOffd(A); HYPRE_Int *offd_i = hypre_CSRMatrixI(offd); HYPRE_Int *offd_j = hypre_CSRMatrixJ(offd); HYPRE_Real *offd_data = hypre_CSRMatrixData(offd); HYPRE_Int global_num_rows = hypre_ParCSRMatrixGlobalNumRows(A); HYPRE_Int *row_starts = hypre_ParCSRMatrixRowStarts(A); HYPRE_Int num_rows = hypre_CSRMatrixNumRows(diag); hypre_ParVector *dinvsqrt; HYPRE_Real *dis_data; hypre_Vector *dis_ext; HYPRE_Real *dis_ext_data; hypre_Vector *sum; HYPRE_Real *sum_data; HYPRE_Int num_cols_offd = hypre_CSRMatrixNumCols(offd); HYPRE_Int num_sends, i, j, index, start; HYPRE_Real *d_buf_data; HYPRE_Real mat_norm, max_row_sum; dinvsqrt = hypre_ParVectorCreate(comm, global_num_rows, row_starts); hypre_ParVectorInitialize(dinvsqrt); dis_data = hypre_VectorData(hypre_ParVectorLocalVector(dinvsqrt)); hypre_ParVectorSetPartitioningOwner(dinvsqrt,0); dis_ext = hypre_SeqVectorCreate(num_cols_offd); hypre_SeqVectorInitialize(dis_ext); dis_ext_data = hypre_VectorData(dis_ext); sum = hypre_SeqVectorCreate(num_rows); hypre_SeqVectorInitialize(sum); sum_data = hypre_VectorData(sum); /* generate dinvsqrt */ for (i=0; i < num_rows; i++) { dis_data[i] = 1.0/sqrt(fabs(diag_data[diag_i[i]])); } /*--------------------------------------------------------------------- * If there exists no CommPkg for A, a CommPkg is generated using * equally load balanced partitionings *--------------------------------------------------------------------*/ if (!comm_pkg) { hypre_MatvecCommPkgCreate(A); comm_pkg = hypre_ParCSRMatrixCommPkg(A); } num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); d_buf_data = hypre_CTAlloc(HYPRE_Real, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends)); index = 0; for (i = 0; i < num_sends; i++) { start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j = start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++) d_buf_data[index++] = dis_data[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)]; } comm_handle = hypre_ParCSRCommHandleCreate( 1, comm_pkg, d_buf_data, dis_ext_data); for (i=0; i < num_rows; i++) { for (j=diag_i[i]; j < diag_i[i+1]; j++) { sum_data[i] += fabs(diag_data[j])*dis_data[i]*dis_data[diag_j[j]]; } } hypre_ParCSRCommHandleDestroy(comm_handle); for (i=0; i < num_rows; i++) { for (j=offd_i[i]; j < offd_i[i+1]; j++) { sum_data[i] += fabs(offd_data[j])*dis_data[i]*dis_ext_data[offd_j[j]]; } } max_row_sum = 0; for (i=0; i < num_rows; i++) { if (max_row_sum < sum_data[i]) max_row_sum = sum_data[i]; } hypre_MPI_Allreduce(&max_row_sum, &mat_norm, 1, HYPRE_MPI_REAL, hypre_MPI_MAX, comm); hypre_ParVectorDestroy(dinvsqrt); hypre_SeqVectorDestroy(sum); hypre_SeqVectorDestroy(dis_ext); hypre_TFree(d_buf_data); *scnorm = mat_norm; return 0; }
4,918
33.640845
88
c
AMG
AMG-master/parcsr_ls/par_stats.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ #include "_hypre_parcsr_ls.h" #include "par_amg.h" /***************************************************************************** * * Routine for getting matrix statistics from setup * * * AHB - using block norm 6 (sum of all elements) instead of 1 (frobenius) * *****************************************************************************/ HYPRE_Int hypre_BoomerAMGSetupStats( void *amg_vdata, hypre_ParCSRMatrix *A ) { MPI_Comm comm = hypre_ParCSRMatrixComm(A); hypre_ParAMGData *amg_data = (hypre_ParAMGData*) amg_vdata; /* Data Structure variables */ hypre_ParCSRMatrix **A_array; hypre_ParCSRMatrix **P_array; hypre_CSRMatrix *A_diag; HYPRE_Real *A_diag_data; HYPRE_Int *A_diag_i; hypre_CSRMatrix *A_offd; HYPRE_Real *A_offd_data; HYPRE_Int *A_offd_i; hypre_CSRMatrix *P_diag; HYPRE_Real *P_diag_data; HYPRE_Int *P_diag_i; hypre_CSRMatrix *P_offd; HYPRE_Real *P_offd_data; HYPRE_Int *P_offd_i; HYPRE_Int numrows; HYPRE_Int *row_starts; HYPRE_Int num_levels; HYPRE_Int coarsen_type; HYPRE_Int interp_type; HYPRE_Int agg_interp_type; HYPRE_Int measure_type; HYPRE_Int agg_num_levels; HYPRE_Real global_nonzeros; HYPRE_Real *send_buff; HYPRE_Real *gather_buff; /* Local variables */ HYPRE_Int level; HYPRE_Int j; HYPRE_Int fine_size; HYPRE_Int min_entries; HYPRE_Int max_entries; HYPRE_Int num_procs,my_id; HYPRE_Int num_threads; HYPRE_Real min_rowsum; HYPRE_Real max_rowsum; HYPRE_Real sparse; HYPRE_Int i; HYPRE_Int coarse_size; HYPRE_Int entries; HYPRE_Real avg_entries; HYPRE_Real rowsum; HYPRE_Real min_weight; HYPRE_Real max_weight; HYPRE_Int global_min_e; HYPRE_Int global_max_e; HYPRE_Real global_min_rsum; HYPRE_Real global_max_rsum; HYPRE_Real global_min_wt; HYPRE_Real global_max_wt; HYPRE_Real *num_mem; HYPRE_Real *num_coeffs; HYPRE_Real *num_variables; HYPRE_Real total_variables; HYPRE_Real operat_cmplxty; HYPRE_Real grid_cmplxty = 0; HYPRE_Real memory_cmplxty = 0; /* amg solve params */ HYPRE_Int max_iter; HYPRE_Int cycle_type; HYPRE_Int *num_grid_sweeps; HYPRE_Int *grid_relax_type; HYPRE_Int relax_order; HYPRE_Int **grid_relax_points; HYPRE_Real *relax_weight; HYPRE_Real *omega; HYPRE_Real tol; HYPRE_Real tmp_norm; HYPRE_Int one = 1; HYPRE_Int minus_one = -1; HYPRE_Int zero = 0; HYPRE_Int smooth_type; HYPRE_Int smooth_num_levels; HYPRE_Int additive; HYPRE_Int mult_additive; HYPRE_Int simple; HYPRE_Int add_end; HYPRE_Int add_rlx; HYPRE_Real add_rlx_wt; hypre_MPI_Comm_size(comm, &num_procs); hypre_MPI_Comm_rank(comm,&my_id); num_threads = hypre_NumThreads(); A_array = hypre_ParAMGDataAArray(amg_data); P_array = hypre_ParAMGDataPArray(amg_data); num_levels = hypre_ParAMGDataNumLevels(amg_data); coarsen_type = hypre_ParAMGDataCoarsenType(amg_data); interp_type = hypre_ParAMGDataInterpType(amg_data); agg_interp_type = hypre_ParAMGDataAggInterpType(amg_data); measure_type = hypre_ParAMGDataMeasureType(amg_data); agg_num_levels = hypre_ParAMGDataAggNumLevels(amg_data); additive = hypre_ParAMGDataAdditive(amg_data); mult_additive = hypre_ParAMGDataMultAdditive(amg_data); simple = hypre_ParAMGDataSimple(amg_data); add_end = hypre_ParAMGDataAddLastLvl(amg_data); add_rlx = hypre_ParAMGDataAddRelaxType(amg_data); add_rlx_wt = hypre_ParAMGDataAddRelaxWt(amg_data); /*---------------------------------------------------------- * Get the amg_data data *----------------------------------------------------------*/ num_levels = hypre_ParAMGDataNumLevels(amg_data); max_iter = hypre_ParAMGDataMaxIter(amg_data); cycle_type = hypre_ParAMGDataCycleType(amg_data); num_grid_sweeps = hypre_ParAMGDataNumGridSweeps(amg_data); grid_relax_type = hypre_ParAMGDataGridRelaxType(amg_data); grid_relax_points = hypre_ParAMGDataGridRelaxPoints(amg_data); relax_weight = hypre_ParAMGDataRelaxWeight(amg_data); relax_order = hypre_ParAMGDataRelaxOrder(amg_data); omega = hypre_ParAMGDataOmega(amg_data); tol = hypre_ParAMGDataTol(amg_data); send_buff = hypre_CTAlloc(HYPRE_Real, 6); #ifdef HYPRE_NO_GLOBAL_PARTITION gather_buff = hypre_CTAlloc(HYPRE_Real,6); #else gather_buff = hypre_CTAlloc(HYPRE_Real,6*num_procs); #endif if (my_id==0) { hypre_printf("\n\n Num MPI tasks = %d Num OpenMP threads = %d\n\n",num_procs,num_threads); hypre_printf("\nBoomerAMG SETUP PARAMETERS:\n\n"); hypre_printf(" Max levels = %d\n",hypre_ParAMGDataMaxLevels(amg_data)); hypre_printf(" Num levels = %d\n\n",num_levels); hypre_printf(" Strength Threshold = %f\n", hypre_ParAMGDataStrongThreshold(amg_data)); hypre_printf(" Interpolation Truncation Factor = %f\n", hypre_ParAMGDataTruncFactor(amg_data)); hypre_printf(" Maximum Row Sum Threshold for Dependency Weakening = %f\n\n", hypre_ParAMGDataMaxRowSum(amg_data)); if (coarsen_type == 0) { hypre_printf(" Coarsening Type = Cleary-Luby-Jones-Plassman\n"); } else if (hypre_abs(coarsen_type) == 1) { hypre_printf(" Coarsening Type = Ruge\n"); } else if (hypre_abs(coarsen_type) == 2) { hypre_printf(" Coarsening Type = Ruge2B\n"); } else if (hypre_abs(coarsen_type) == 3) { hypre_printf(" Coarsening Type = Ruge3\n"); } else if (hypre_abs(coarsen_type) == 4) { hypre_printf(" Coarsening Type = Ruge 3c \n"); } else if (hypre_abs(coarsen_type) == 5) { hypre_printf(" Coarsening Type = Ruge relax special points \n"); } else if (hypre_abs(coarsen_type) == 6) { hypre_printf(" Coarsening Type = Falgout-CLJP \n"); } else if (hypre_abs(coarsen_type) == 8) { hypre_printf(" Coarsening Type = PMIS \n"); } else if (hypre_abs(coarsen_type) == 10) { hypre_printf(" Coarsening Type = HMIS \n"); } else if (hypre_abs(coarsen_type) == 11) { hypre_printf(" Coarsening Type = Ruge 1st pass only \n"); } else if (hypre_abs(coarsen_type) == 9) { hypre_printf(" Coarsening Type = PMIS fixed random \n"); } else if (hypre_abs(coarsen_type) == 7) { hypre_printf(" Coarsening Type = CLJP, fixed random \n"); } /*if (coarsen_type > 0) { hypre_printf(" Hybrid Coarsening (switch to CLJP when coarsening slows)\n"); }*/ if (agg_num_levels > 0) { hypre_printf("\n No. of levels of aggressive coarsening: %d\n\n", agg_num_levels); if (agg_interp_type == 4) hypre_printf(" Interpolation on agg. levels= multipass interpolation\n"); else if (agg_interp_type == 1) hypre_printf(" Interpolation on agg. levels = 2-stage extended+i interpolation \n"); else if (agg_interp_type == 2) hypre_printf(" Interpolation on agg. levels = 2-stage std interpolation \n"); else if (agg_interp_type == 3) hypre_printf(" Interpolation on agg. levels = 2-stage extended interpolation \n"); } if (coarsen_type) hypre_printf(" measures are determined %s\n\n", (measure_type ? "globally" : "locally")); #ifdef HYPRE_NO_GLOBAL_PARTITION hypre_printf( "\n No global partition option chosen.\n\n"); #endif if (interp_type == 0) { hypre_printf(" Interpolation = modified classical interpolation\n"); } else if (interp_type == 2) { hypre_printf(" Interpolation = modified classical interpolation for hyperbolic PDEs\n"); } else if (interp_type == 3) { hypre_printf(" Interpolation = direct interpolation with separation of weights\n"); } else if (interp_type == 4) { hypre_printf(" Interpolation = multipass interpolation\n"); } else if (interp_type == 5) { hypre_printf(" Interpolation = multipass interpolation with separation of weights\n"); } else if (interp_type == 6) { hypre_printf(" Interpolation = extended+i interpolation\n"); } else if (interp_type == 7) { hypre_printf(" Interpolation = extended+i interpolation (if no common C point)\n"); } else if (interp_type == 12) { hypre_printf(" Interpolation = F-F interpolation\n"); } else if (interp_type == 13) { hypre_printf(" Interpolation = F-F1 interpolation\n"); } else if (interp_type == 14) { hypre_printf(" Interpolation = extended interpolation\n"); } else if (interp_type == 8) { hypre_printf(" Interpolation = standard interpolation\n"); } else if (interp_type == 9) { hypre_printf(" Interpolation = standard interpolation with separation of weights\n"); } else if (interp_type == 10) { hypre_printf(" Interpolation = block classical interpolation for nodal systems AMG\n"); } else if (interp_type == 11) { hypre_printf(" Interpolation = block classical interpolation with diagonal blocks\n"); hypre_printf(" for nodal systems AMG\n"); } else if (interp_type == 24) { hypre_printf(" Interpolation = block direct interpolation \n"); hypre_printf(" for nodal systems AMG\n"); } hypre_printf( "\nOperator Matrix Information:\n\n"); hypre_printf(" nonzero entries p"); hypre_printf("er row row sums\n"); hypre_printf("lev rows entries sparse min max "); hypre_printf("avg min max\n"); hypre_printf("======================================="); hypre_printf("============================\n"); } /*----------------------------------------------------- * Enter Statistics Loop *-----------------------------------------------------*/ num_coeffs = hypre_CTAlloc(HYPRE_Real,num_levels); num_mem = hypre_CTAlloc(HYPRE_Real,num_levels); num_variables = hypre_CTAlloc(HYPRE_Real,num_levels); for (level = 0; level < num_levels; level++) { A_diag = hypre_ParCSRMatrixDiag(A_array[level]); A_diag_data = hypre_CSRMatrixData(A_diag); A_diag_i = hypre_CSRMatrixI(A_diag); A_offd = hypre_ParCSRMatrixOffd(A_array[level]); A_offd_data = hypre_CSRMatrixData(A_offd); A_offd_i = hypre_CSRMatrixI(A_offd); row_starts = hypre_ParCSRMatrixRowStarts(A_array[level]); fine_size = hypre_ParCSRMatrixGlobalNumRows(A_array[level]); global_nonzeros = hypre_ParCSRMatrixDNumNonzeros(A_array[level]); num_coeffs[level] = global_nonzeros; if (level == 0) num_mem[level] += global_nonzeros; if (level == 0 && (additive == 0 || mult_additive == 0) ) num_mem[level] += global_nonzeros; if (level > 0) { if (simple > level || simple == -1) num_mem[level] += global_nonzeros; } num_variables[level] = (HYPRE_Real) fine_size; sparse = global_nonzeros /((HYPRE_Real) fine_size * (HYPRE_Real) fine_size); min_entries = 0; max_entries = 0; min_rowsum = 0.0; max_rowsum = 0.0; if (hypre_CSRMatrixNumRows(A_diag)) { min_entries = (A_diag_i[1]-A_diag_i[0])+(A_offd_i[1]-A_offd_i[0]); for (j = A_diag_i[0]; j < A_diag_i[1]; j++) min_rowsum += A_diag_data[j]; for (j = A_offd_i[0]; j < A_offd_i[1]; j++) min_rowsum += A_offd_data[j]; max_rowsum = min_rowsum; for (j = 0; j < hypre_CSRMatrixNumRows(A_diag); j++) { entries = (A_diag_i[j+1]-A_diag_i[j])+(A_offd_i[j+1]-A_offd_i[j]); min_entries = hypre_min(entries, min_entries); max_entries = hypre_max(entries, max_entries); rowsum = 0.0; for (i = A_diag_i[j]; i < A_diag_i[j+1]; i++) rowsum += A_diag_data[i]; for (i = A_offd_i[j]; i < A_offd_i[j+1]; i++) rowsum += A_offd_data[i]; min_rowsum = hypre_min(rowsum, min_rowsum); max_rowsum = hypre_max(rowsum, max_rowsum); } } avg_entries = global_nonzeros / ((HYPRE_Real) fine_size); #ifdef HYPRE_NO_GLOBAL_PARTITION numrows = row_starts[1]-row_starts[0]; if (!numrows) /* if we don't have any rows, then don't have this count toward min row sum or min num entries */ { min_entries = 1000000; min_rowsum = 1.0e7; } send_buff[0] = - (HYPRE_Real) min_entries; send_buff[1] = (HYPRE_Real) max_entries; send_buff[2] = - min_rowsum; send_buff[3] = max_rowsum; hypre_MPI_Reduce(send_buff, gather_buff, 4, HYPRE_MPI_REAL, hypre_MPI_MAX, 0, comm); if (my_id ==0) { global_min_e = - gather_buff[0]; global_max_e = gather_buff[1]; global_min_rsum = - gather_buff[2]; global_max_rsum = gather_buff[3]; hypre_printf( "%2d %7d %8.0f %0.3f %4d %4d", level, fine_size, global_nonzeros, sparse, global_min_e, global_max_e); hypre_printf(" %4.1f %10.3e %10.3e\n", avg_entries, global_min_rsum, global_max_rsum); } #else send_buff[0] = (HYPRE_Real) min_entries; send_buff[1] = (HYPRE_Real) max_entries; send_buff[2] = min_rowsum; send_buff[3] = max_rowsum; hypre_MPI_Gather(send_buff,4,HYPRE_MPI_REAL,gather_buff,4,HYPRE_MPI_REAL,0,comm); if (my_id == 0) { global_min_e = 1000000; global_max_e = 0; global_min_rsum = 1.0e7; global_max_rsum = 0.0; for (j = 0; j < num_procs; j++) { numrows = row_starts[j+1]-row_starts[j]; if (numrows) { global_min_e = hypre_min(global_min_e, (HYPRE_Int) gather_buff[j*4]); global_min_rsum = hypre_min(global_min_rsum, gather_buff[j*4 +2]); } global_max_e = hypre_max(global_max_e, (HYPRE_Int) gather_buff[j*4 +1]); global_max_rsum = hypre_max(global_max_rsum, gather_buff[j*4 +3]); } hypre_printf( "%2d %7d %8.0f %0.3f %4d %4d", level, fine_size, global_nonzeros, sparse, global_min_e, global_max_e); hypre_printf(" %4.1f %10.3e %10.3e\n", avg_entries, global_min_rsum, global_max_rsum); } #endif } if (my_id == 0) { hypre_printf( "\n\nInterpolation Matrix Information:\n"); hypre_printf(" entries/row min max"); hypre_printf(" row sums\n"); hypre_printf("lev rows cols min max "); hypre_printf(" weight weight min max \n"); hypre_printf("======================================="); hypre_printf("==========================\n"); } /*----------------------------------------------------- * Enter Statistics Loop *-----------------------------------------------------*/ for (level = 0; level < num_levels-1; level++) { P_diag = hypre_ParCSRMatrixDiag(P_array[level]); P_diag_data = hypre_CSRMatrixData(P_diag); P_diag_i = hypre_CSRMatrixI(P_diag); P_offd = hypre_ParCSRMatrixOffd(P_array[level]); P_offd_data = hypre_CSRMatrixData(P_offd); P_offd_i = hypre_CSRMatrixI(P_offd); row_starts = hypre_ParCSRMatrixRowStarts(P_array[level]); fine_size = hypre_ParCSRMatrixGlobalNumRows(P_array[level]); coarse_size = hypre_ParCSRMatrixGlobalNumCols(P_array[level]); /*hypre_ParCSRMatrixSetDNumNonzeros(P_array[level]);*/ global_nonzeros = hypre_ParCSRMatrixDNumNonzeros(P_array[level]); num_mem[level] += (HYPRE_Real) global_nonzeros; min_weight = 1.0; max_weight = 0.0; max_rowsum = 0.0; min_rowsum = 0.0; min_entries = 0; max_entries = 0; if (hypre_CSRMatrixNumRows(P_diag)) { if (P_diag_data) min_weight = P_diag_data[0]; for (j = P_diag_i[0]; j < P_diag_i[1]; j++) { min_weight = hypre_min(min_weight, P_diag_data[j]); if (P_diag_data[j] != 1.0) max_weight = hypre_max(max_weight, P_diag_data[j]); min_rowsum += P_diag_data[j]; } for (j = P_offd_i[0]; j < P_offd_i[1]; j++) { min_weight = hypre_min(min_weight, P_offd_data[j]); if (P_offd_data[j] != 1.0) max_weight = hypre_max(max_weight, P_offd_data[j]); min_rowsum += P_offd_data[j]; } max_rowsum = min_rowsum; min_entries = (P_diag_i[1]-P_diag_i[0])+(P_offd_i[1]-P_offd_i[0]); max_entries = 0; for (j = 0; j < hypre_CSRMatrixNumRows(P_diag); j++) { entries = (P_diag_i[j+1]-P_diag_i[j])+(P_offd_i[j+1]-P_offd_i[j]); min_entries = hypre_min(entries, min_entries); max_entries = hypre_max(entries, max_entries); rowsum = 0.0; for (i = P_diag_i[j]; i < P_diag_i[j+1]; i++) { min_weight = hypre_min(min_weight, P_diag_data[i]); if (P_diag_data[i] != 1.0) max_weight = hypre_max(max_weight, P_diag_data[i]); rowsum += P_diag_data[i]; } for (i = P_offd_i[j]; i < P_offd_i[j+1]; i++) { min_weight = hypre_min(min_weight, P_offd_data[i]); if (P_offd_data[i] != 1.0) max_weight = hypre_max(max_weight, P_offd_data[i]); rowsum += P_offd_data[i]; } min_rowsum = hypre_min(rowsum, min_rowsum); max_rowsum = hypre_max(rowsum, max_rowsum); } } avg_entries = ((HYPRE_Real) global_nonzeros) / ((HYPRE_Real) fine_size); #ifdef HYPRE_NO_GLOBAL_PARTITION numrows = row_starts[1]-row_starts[0]; if (!numrows) /* if we don't have any rows, then don't have this count toward min row sum or min num entries */ { min_entries = 1000000; min_rowsum = 1.0e7; min_weight = 1.0e7; } send_buff[0] = - (HYPRE_Real) min_entries; send_buff[1] = (HYPRE_Real) max_entries; send_buff[2] = - min_rowsum; send_buff[3] = max_rowsum; send_buff[4] = - min_weight; send_buff[5] = max_weight; hypre_MPI_Reduce(send_buff, gather_buff, 6, HYPRE_MPI_REAL, hypre_MPI_MAX, 0, comm); if (my_id == 0) { global_min_e = - gather_buff[0]; global_max_e = gather_buff[1]; global_min_rsum = -gather_buff[2]; global_max_rsum = gather_buff[3]; global_min_wt = -gather_buff[4]; global_max_wt = gather_buff[5]; hypre_printf( "%2d %5d x %-5d %3d %3d", level, fine_size, coarse_size, global_min_e, global_max_e); hypre_printf(" %10.3e %9.3e %9.3e %9.3e\n", global_min_wt, global_max_wt, global_min_rsum, global_max_rsum); } #else send_buff[0] = (HYPRE_Real) min_entries; send_buff[1] = (HYPRE_Real) max_entries; send_buff[2] = min_rowsum; send_buff[3] = max_rowsum; send_buff[4] = min_weight; send_buff[5] = max_weight; hypre_MPI_Gather(send_buff,6,HYPRE_MPI_REAL,gather_buff,6,HYPRE_MPI_REAL,0,comm); if (my_id == 0) { global_min_e = 1000000; global_max_e = 0; global_min_rsum = 1.0e7; global_max_rsum = 0.0; global_min_wt = 1.0e7; global_max_wt = 0.0; for (j = 0; j < num_procs; j++) { numrows = row_starts[j+1] - row_starts[j]; if (numrows) { global_min_e = hypre_min(global_min_e, (HYPRE_Int) gather_buff[j*6]); global_min_rsum = hypre_min(global_min_rsum, gather_buff[j*6+2]); global_min_wt = hypre_min(global_min_wt, gather_buff[j*6+4]); } global_max_e = hypre_max(global_max_e, (HYPRE_Int) gather_buff[j*6+1]); global_max_rsum = hypre_max(global_max_rsum, gather_buff[j*6+3]); global_max_wt = hypre_max(global_max_wt, gather_buff[j*6+5]); } hypre_printf( "%2d %5d x %-5d %3d %3d", level, fine_size, coarse_size, global_min_e, global_max_e); hypre_printf(" %10.3e %9.3e %9.3e %9.3e\n", global_min_wt, global_max_wt, global_min_rsum, global_max_rsum); } #endif } total_variables = 0; operat_cmplxty = 0; for (j=0;j<hypre_ParAMGDataNumLevels(amg_data);j++) { memory_cmplxty += num_mem[j] / num_coeffs[0]; operat_cmplxty += num_coeffs[j] / num_coeffs[0]; total_variables += num_variables[j]; } if (num_variables[0] != 0) grid_cmplxty = total_variables / num_variables[0]; if (my_id == 0 ) { hypre_printf("\n\n Complexity: grid = %f\n",grid_cmplxty); hypre_printf(" operator = %f\n",operat_cmplxty); hypre_printf(" memory = %f\n",memory_cmplxty); } if (my_id == 0) hypre_printf("\n\n"); if (my_id == 0) { hypre_printf("\n\nBoomerAMG SOLVER PARAMETERS:\n\n"); hypre_printf( " Maximum number of cycles: %d \n",max_iter); hypre_printf( " Stopping Tolerance: %e \n",tol); hypre_printf( " Cycle type (1 = V, 2 = W, etc.): %d\n\n", cycle_type); if (additive == 0 || mult_additive == 0 || simple == 0) { HYPRE_Int add_lvl = add_end; if (add_end == -1) add_lvl = num_levels-1; if (additive > -1) hypre_printf( " Additive V-cycle 1st level %d last level %d: \n", additive, add_lvl); if (mult_additive > -1) hypre_printf( " Mult-Additive V-cycle 1st level %d last level %d: \n", mult_additive, add_lvl); if (simple > -1) hypre_printf( " Simplified Mult-Additive V-cycle 1st level %d: last level %d \n", simple, add_lvl); hypre_printf( " Relaxation Parameters:\n"); if (add_lvl == num_levels-1) { hypre_printf( " Visiting Grid: down up coarse\n"); hypre_printf( " Number of sweeps: %4d %2d %4d \n", num_grid_sweeps[1], num_grid_sweeps[1],(2*num_grid_sweeps[1])); hypre_printf( " Type 0=Jac, 3=hGS, 6=hSGS, 9=GE: %2d %2d %2d \n", add_rlx, add_rlx, add_rlx); } else { hypre_printf( " Visiting Grid: down up\n"); hypre_printf( " Number of sweeps: %4d %2d\n", num_grid_sweeps[1], num_grid_sweeps[1]); hypre_printf( " Type 0=Jac, 3=hGS, 6=hSGS, 9=GE: %2d %2d\n", add_rlx, add_rlx); } if (add_lvl < num_levels -1) { hypre_printf( " \n"); hypre_printf( "Multiplicative portion: \n"); hypre_printf( " Visiting Grid: down up coarse\n"); hypre_printf( " Number of sweeps: %4d %2d %4d\n", num_grid_sweeps[1], num_grid_sweeps[2], num_grid_sweeps[3]); hypre_printf( " Type 0=Jac, 3=hGS, 6=hSGS, 9=GE: %4d %2d %4d\n", grid_relax_type[1], grid_relax_type[2], grid_relax_type[3]); } if (add_rlx == 0) hypre_printf( " Relaxation Weight: %e \n", add_rlx_wt); hypre_printf( " Point types, partial sweeps (1=C, -1=F):\n"); hypre_printf( " Pre-CG relaxation (down):"); for (j = 0; j < num_grid_sweeps[1]; j++) hypre_printf(" %2d", zero); hypre_printf( "\n"); hypre_printf( " Post-CG relaxation (up):"); for (j = 0; j < num_grid_sweeps[2]; j++) hypre_printf(" %2d", zero); hypre_printf( "\n"); hypre_printf( " Coarsest grid:"); for (j = 0; j < num_grid_sweeps[3]; j++) hypre_printf(" %2d", zero); hypre_printf( "\n\n"); } else if (additive > 0 || mult_additive > 0 || simple > 0) { HYPRE_Int add_lvl = add_end; if (add_end == -1) add_lvl = num_levels-1; hypre_printf( " Relaxation Parameters:\n"); if (add_lvl < num_levels -1) { hypre_printf( " Visiting Grid: down up coarse\n"); hypre_printf( " Number of sweeps: %4d %2d %4d\n", num_grid_sweeps[1], num_grid_sweeps[2], num_grid_sweeps[3]); hypre_printf( " Type 0=Jac, 3=hGS, 6=hSGS, 9=GE: %4d %2d %4d\n", grid_relax_type[1], grid_relax_type[2], grid_relax_type[3]); } else { hypre_printf( " Visiting Grid: down up \n"); hypre_printf( " Number of sweeps: %4d %2d \n", num_grid_sweeps[1], num_grid_sweeps[2]); hypre_printf( " Type 0=Jac, 3=hGS, 6=hSGS, 9=GE: %4d %2d \n", grid_relax_type[1], grid_relax_type[2]); } hypre_printf( " Point types, partial sweeps (1=C, -1=F):\n"); if (grid_relax_points && grid_relax_type[1] != 8) { hypre_printf( " Pre-CG relaxation (down):"); for (j = 0; j < num_grid_sweeps[1]; j++) hypre_printf(" %2d", grid_relax_points[1][j]); hypre_printf( "\n"); hypre_printf( " Post-CG relaxation (up):"); for (j = 0; j < num_grid_sweeps[2]; j++) hypre_printf(" %2d", grid_relax_points[2][j]); hypre_printf( "\n"); } else if (relax_order == 1 && grid_relax_type[1] != 8) { hypre_printf( " Pre-CG relaxation (down):"); for (j = 0; j < num_grid_sweeps[1]; j++) hypre_printf(" %2d %2d", one, minus_one); hypre_printf( "\n"); hypre_printf( " Post-CG relaxation (up):"); for (j = 0; j < num_grid_sweeps[2]; j++) hypre_printf(" %2d %2d", minus_one, one); hypre_printf( "\n"); } else { hypre_printf( " Pre-CG relaxation (down):"); for (j = 0; j < num_grid_sweeps[1]; j++) hypre_printf(" %2d", zero); hypre_printf( "\n"); hypre_printf( " Post-CG relaxation (up):"); for (j = 0; j < num_grid_sweeps[2]; j++) hypre_printf(" %2d", zero); hypre_printf( "\n"); } hypre_printf( "\n\n"); if (additive > -1) hypre_printf( " Additive V-cycle 1st level %d last level %d: \n", additive, add_lvl); if (mult_additive > -1) hypre_printf( " Mult-Additive V-cycle 1st level %d last level %d: \n", mult_additive, add_lvl); if (simple > -1) hypre_printf( " Simplified Mult-Additive V-cycle 1st level %d: last level %d \n", simple, add_lvl); hypre_printf( " Relaxation Parameters:\n"); if (add_lvl == num_levels-1) { hypre_printf( " Visiting Grid: down up coarse\n"); hypre_printf( " Number of sweeps: %4d %2d %4d \n", num_grid_sweeps[1], num_grid_sweeps[1],(2*num_grid_sweeps[1])); hypre_printf( " Type 0=Jac, 3=hGS, 6=hSGS, 9=GE: %2d %2d %2d \n", add_rlx, add_rlx, add_rlx); } else { hypre_printf( " Visiting Grid: down up\n"); hypre_printf( " Number of sweeps: %4d %2d\n", num_grid_sweeps[1], num_grid_sweeps[1]); hypre_printf( " Type 0=Jac, 3=hGS, 6=hSGS, 9=GE: %2d %2d\n", add_rlx, add_rlx); } if (add_rlx == 0) hypre_printf( " Relaxation Weight: %e \n", add_rlx_wt); hypre_printf( " Point types, partial sweeps (1=C, -1=F):\n"); hypre_printf( " Pre-CG relaxation (down):"); for (j = 0; j < num_grid_sweeps[1]; j++) hypre_printf(" %2d", zero); hypre_printf( "\n"); hypre_printf( " Post-CG relaxation (up):"); for (j = 0; j < num_grid_sweeps[2]; j++) hypre_printf(" %2d", zero); hypre_printf( "\n"); hypre_printf( " Coarsest grid:"); for (j = 0; j < num_grid_sweeps[3]; j++) hypre_printf(" %2d", zero); hypre_printf( "\n\n"); } else { hypre_printf( " Relaxation Parameters:\n"); hypre_printf( " Visiting Grid: down up coarse\n"); hypre_printf( " Number of sweeps: %4d %2d %4d \n", num_grid_sweeps[1], num_grid_sweeps[2],num_grid_sweeps[3]); hypre_printf( " Type 0=Jac, 3=hGS, 6=hSGS, 9=GE: %4d %2d %4d \n", grid_relax_type[1], grid_relax_type[2],grid_relax_type[3]); hypre_printf( " Point types, partial sweeps (1=C, -1=F):\n"); if (grid_relax_points && grid_relax_type[1] != 8) { hypre_printf( " Pre-CG relaxation (down):"); for (j = 0; j < num_grid_sweeps[1]; j++) hypre_printf(" %2d", grid_relax_points[1][j]); hypre_printf( "\n"); hypre_printf( " Post-CG relaxation (up):"); for (j = 0; j < num_grid_sweeps[2]; j++) hypre_printf(" %2d", grid_relax_points[2][j]); hypre_printf( "\n"); hypre_printf( " Coarsest grid:"); for (j = 0; j < num_grid_sweeps[3]; j++) hypre_printf(" %2d", grid_relax_points[3][j]); hypre_printf( "\n\n"); } else if (relax_order == 1 && grid_relax_type[1] != 8) { hypre_printf( " Pre-CG relaxation (down):"); for (j = 0; j < num_grid_sweeps[1]; j++) hypre_printf(" %2d %2d", one, minus_one); hypre_printf( "\n"); hypre_printf( " Post-CG relaxation (up):"); for (j = 0; j < num_grid_sweeps[2]; j++) hypre_printf(" %2d %2d", minus_one, one); hypre_printf( "\n"); hypre_printf( " Coarsest grid:"); for (j = 0; j < num_grid_sweeps[3]; j++) hypre_printf(" %2d", zero); hypre_printf( "\n\n"); } else { hypre_printf( " Pre-CG relaxation (down):"); for (j = 0; j < num_grid_sweeps[1]; j++) hypre_printf(" %2d", zero); hypre_printf( "\n"); hypre_printf( " Post-CG relaxation (up):"); for (j = 0; j < num_grid_sweeps[2]; j++) hypre_printf(" %2d", zero); hypre_printf( "\n"); hypre_printf( " Coarsest grid:"); for (j = 0; j < num_grid_sweeps[3]; j++) hypre_printf(" %2d", zero); hypre_printf( "\n\n"); } } for (j=0; j < num_levels; j++) if (relax_weight[j] != 1) hypre_printf( " Relaxation Weight %f level %d\n",relax_weight[j],j); for (j=0; j < num_levels; j++) if (omega[j] != 1) hypre_printf( " Outer relaxation weight %f level %d\n",omega[j],j); } hypre_TFree(num_coeffs); hypre_TFree(num_mem); hypre_TFree(num_variables); hypre_TFree(send_buff); hypre_TFree(gather_buff); return(0); } /*--------------------------------------------------------------- * hypre_BoomerAMGWriteSolverParams *---------------------------------------------------------------*/ HYPRE_Int hypre_BoomerAMGWriteSolverParams(void* data) { hypre_ParAMGData *amg_data = (hypre_ParAMGData*) data; /* amg solve params */ HYPRE_Int num_levels; HYPRE_Int max_iter; HYPRE_Int cycle_type; HYPRE_Int *num_grid_sweeps; HYPRE_Int *grid_relax_type; HYPRE_Int **grid_relax_points; HYPRE_Int relax_order; HYPRE_Real *relax_weight; HYPRE_Real *omega; HYPRE_Real tol; /* amg output params */ HYPRE_Int amg_print_level; HYPRE_Int j; HYPRE_Int one = 1; HYPRE_Int minus_one = -1; HYPRE_Int zero = 0; /*---------------------------------------------------------- * Get the amg_data data *----------------------------------------------------------*/ num_levels = hypre_ParAMGDataNumLevels(amg_data); max_iter = hypre_ParAMGDataMaxIter(amg_data); cycle_type = hypre_ParAMGDataCycleType(amg_data); num_grid_sweeps = hypre_ParAMGDataNumGridSweeps(amg_data); grid_relax_type = hypre_ParAMGDataGridRelaxType(amg_data); grid_relax_points = hypre_ParAMGDataGridRelaxPoints(amg_data); relax_order = hypre_ParAMGDataRelaxOrder(amg_data); relax_weight = hypre_ParAMGDataRelaxWeight(amg_data); omega = hypre_ParAMGDataOmega(amg_data); tol = hypre_ParAMGDataTol(amg_data); amg_print_level = hypre_ParAMGDataPrintLevel(amg_data); /*---------------------------------------------------------- * AMG info *----------------------------------------------------------*/ if (amg_print_level == 1 || amg_print_level == 3) { hypre_printf("\n\nBoomerAMG SOLVER PARAMETERS:\n\n"); hypre_printf( " Maximum number of cycles: %d \n",max_iter); hypre_printf( " Stopping Tolerance: %e \n",tol); hypre_printf( " Cycle type (1 = V, 2 = W, etc.): %d\n\n", cycle_type); hypre_printf( " Relaxation Parameters:\n"); hypre_printf( " Visiting Grid: down up coarse\n"); hypre_printf( " Number of sweeps: %4d %2d %4d \n", num_grid_sweeps[1], num_grid_sweeps[2],num_grid_sweeps[3]); hypre_printf( " Type 0=Jac, 3=hGS, 6=hSGS, 9=GE: %4d %2d %4d \n", grid_relax_type[1], grid_relax_type[2],grid_relax_type[3]); hypre_printf( " Point types, partial sweeps (1=C, -1=F):\n"); if (grid_relax_points) { hypre_printf( " Pre-CG relaxation (down):"); for (j = 0; j < num_grid_sweeps[1]; j++) hypre_printf(" %2d", grid_relax_points[1][j]); hypre_printf( "\n"); hypre_printf( " Post-CG relaxation (up):"); for (j = 0; j < num_grid_sweeps[2]; j++) hypre_printf(" %2d", grid_relax_points[2][j]); hypre_printf( "\n"); hypre_printf( " Coarsest grid:"); for (j = 0; j < num_grid_sweeps[3]; j++) hypre_printf(" %2d", grid_relax_points[3][j]); hypre_printf( "\n\n"); } else if (relax_order == 1) { hypre_printf( " Pre-CG relaxation (down):"); for (j = 0; j < num_grid_sweeps[1]; j++) hypre_printf(" %2d %2d", one, minus_one); hypre_printf( "\n"); hypre_printf( " Post-CG relaxation (up):"); for (j = 0; j < num_grid_sweeps[2]; j++) hypre_printf(" %2d %2d", minus_one, one); hypre_printf( "\n"); hypre_printf( " Coarsest grid:"); for (j = 0; j < num_grid_sweeps[3]; j++) hypre_printf(" %2d", zero); hypre_printf( "\n\n"); } else { hypre_printf( " Pre-CG relaxation (down):"); for (j = 0; j < num_grid_sweeps[1]; j++) hypre_printf(" %2d", zero); hypre_printf( "\n"); hypre_printf( " Post-CG relaxation (up):"); for (j = 0; j < num_grid_sweeps[2]; j++) hypre_printf(" %2d", zero); hypre_printf( "\n"); hypre_printf( " Coarsest grid:"); for (j = 0; j < num_grid_sweeps[3]; j++) hypre_printf(" %2d", zero); hypre_printf( "\n\n"); } for (j=0; j < num_levels; j++) if (relax_weight[j] != 1) hypre_printf( " Relaxation Weight %f level %d\n",relax_weight[j],j); for (j=0; j < num_levels; j++) if (omega[j] != 1) hypre_printf( " Outer relaxation weight %f level %d\n",omega[j],j); hypre_printf( " Output flag (print_level): %d \n", amg_print_level); } return 0; }
39,007
36.185891
114
c
AMG
AMG-master/parcsr_ls/par_strength.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /****************************************************************************** * *****************************************************************************/ /* following should be in a header file */ #include "_hypre_parcsr_ls.h" #include "hypre_hopscotch_hash.h" /*==========================================================================*/ /*==========================================================================*/ /** Generates strength matrix Notes: \begin{itemize} \item The underlying matrix storage scheme is a hypre_ParCSR matrix. \item The routine returns the following: \begin{itemize} \item S - a ParCSR matrix representing the "strength matrix". This is used in the coarsening and interpolation routines. \end{itemize} \item The graph of the "strength matrix" for A is a subgraph of the graph of A, but requires nonsymmetric storage even if A is symmetric. This is because of the directional nature of the "strengh of dependence" notion (see below). Since we are using nonsymmetric storage for A right now, this is not a problem. If we ever add the ability to store A symmetrically, then we could store the strength graph as floats instead of doubles to save space. \item This routine currently "compresses" the strength matrix. We should consider the possibility of defining this matrix to have the same "nonzero structure" as A. To do this, we could use the same A\_i and A\_j arrays, and would need only define the S\_data array. There are several pros and cons to discuss. \end{itemize} Terminology: \begin{itemize} \item Ruge's terminology: A point is "strongly connected to" $j$, or "strongly depends on" $j$, if $-a_ij >= \theta max_{l != j} \{-a_il\}$. \item Here, we retain some of this terminology, but with a more generalized notion of "strength". We also retain the "natural" graph notation for representing the directed graph of a matrix. That is, the nonzero entry $a_ij$ is represented as: i --> j. In the strength matrix, S, the entry $s_ij$ is also graphically denoted as above, and means both of the following: \begin{itemize} \item $i$ "depends on" $j$ with "strength" $s_ij$ \item $j$ "influences" $i$ with "strength" $s_ij$ \end{itemize} \end{itemize} {\bf Input files:} _hypre_parcsr_ls.h @return Error code. @param A [IN] coefficient matrix @param strength_threshold [IN] threshold parameter used to define strength @param max_row_sum [IN] parameter used to modify definition of strength for diagonal dominant matrices @param S_ptr [OUT] strength matrix @see */ /*--------------------------------------------------------------------------*/ HYPRE_Int hypre_BoomerAMGCreateS(hypre_ParCSRMatrix *A, HYPRE_Real strength_threshold, HYPRE_Real max_row_sum, HYPRE_Int num_functions, HYPRE_Int *dof_func, hypre_ParCSRMatrix **S_ptr) { #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_CREATES] -= hypre_MPI_Wtime(); #endif MPI_Comm comm = hypre_ParCSRMatrixComm(A); hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A); hypre_ParCSRCommHandle *comm_handle; hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag); HYPRE_Real *A_diag_data = hypre_CSRMatrixData(A_diag); hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd); HYPRE_Real *A_offd_data = NULL; HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag); HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd); HYPRE_Int *row_starts = hypre_ParCSRMatrixRowStarts(A); HYPRE_Int num_variables = hypre_CSRMatrixNumRows(A_diag); HYPRE_Int global_num_vars = hypre_ParCSRMatrixGlobalNumRows(A); HYPRE_Int num_nonzeros_diag; HYPRE_Int num_nonzeros_offd = 0; HYPRE_Int num_cols_offd = 0; hypre_ParCSRMatrix *S; hypre_CSRMatrix *S_diag; HYPRE_Int *S_diag_i; HYPRE_Int *S_diag_j; /* HYPRE_Real *S_diag_data; */ hypre_CSRMatrix *S_offd; HYPRE_Int *S_offd_i = NULL; HYPRE_Int *S_offd_j = NULL; /* HYPRE_Real *S_offd_data; */ HYPRE_Real diag, row_scale, row_sum; HYPRE_Int i, jA, jS; HYPRE_Int ierr = 0; HYPRE_Int *dof_func_offd; HYPRE_Int num_sends; HYPRE_Int *int_buf_data; HYPRE_Int index, start, j; HYPRE_Int *prefix_sum_workspace; /*-------------------------------------------------------------- * Compute a ParCSR strength matrix, S. * * For now, the "strength" of dependence/influence is defined in * the following way: i depends on j if * aij > hypre_max (k != i) aik, aii < 0 * or * aij < hypre_min (k != i) aik, aii >= 0 * Then S_ij = 1, else S_ij = 0. * * NOTE: the entries are negative initially, corresponding * to "unaccounted-for" dependence. *----------------------------------------------------------------*/ num_nonzeros_diag = A_diag_i[num_variables]; num_cols_offd = hypre_CSRMatrixNumCols(A_offd); A_offd_i = hypre_CSRMatrixI(A_offd); num_nonzeros_offd = A_offd_i[num_variables]; S = hypre_ParCSRMatrixCreate(comm, global_num_vars, global_num_vars, row_starts, row_starts, num_cols_offd, num_nonzeros_diag, num_nonzeros_offd); /* row_starts is owned by A, col_starts = row_starts */ hypre_ParCSRMatrixSetRowStartsOwner(S,0); S_diag = hypre_ParCSRMatrixDiag(S); hypre_CSRMatrixI(S_diag) = hypre_CTAlloc(HYPRE_Int, num_variables+1); hypre_CSRMatrixJ(S_diag) = hypre_CTAlloc(HYPRE_Int, num_nonzeros_diag); S_offd = hypre_ParCSRMatrixOffd(S); hypre_CSRMatrixI(S_offd) = hypre_CTAlloc(HYPRE_Int, num_variables+1); S_diag_i = hypre_CSRMatrixI(S_diag); HYPRE_Int *S_temp_diag_j = hypre_CSRMatrixJ(S_diag); S_offd_i = hypre_CSRMatrixI(S_offd); S_diag_j = hypre_TAlloc(HYPRE_Int, num_nonzeros_diag); HYPRE_Int *S_temp_offd_j = NULL; dof_func_offd = NULL; if (num_cols_offd) { A_offd_data = hypre_CSRMatrixData(A_offd); hypre_CSRMatrixJ(S_offd) = hypre_CTAlloc(HYPRE_Int, num_nonzeros_offd); S_temp_offd_j = hypre_CSRMatrixJ(S_offd); HYPRE_Int *col_map_offd_S = hypre_TAlloc(HYPRE_Int, num_cols_offd); hypre_ParCSRMatrixColMapOffd(S) = col_map_offd_S; if (num_functions > 1) dof_func_offd = hypre_CTAlloc(HYPRE_Int, num_cols_offd); S_offd_j = hypre_TAlloc(HYPRE_Int, num_nonzeros_offd); HYPRE_Int *col_map_offd_A = hypre_ParCSRMatrixColMapOffd(A); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_cols_offd; i++) col_map_offd_S[i] = col_map_offd_A[i]; } /*------------------------------------------------------------------- * Get the dof_func data for the off-processor columns *-------------------------------------------------------------------*/ if (!comm_pkg) { hypre_MatvecCommPkgCreate(A); comm_pkg = hypre_ParCSRMatrixCommPkg(A); } num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); if (num_functions > 1) { int_buf_data = hypre_CTAlloc(HYPRE_Int,hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends)); index = 0; for (i = 0; i < num_sends; i++) { start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j=start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++) int_buf_data[index++] = dof_func[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)]; } comm_handle = hypre_ParCSRCommHandleCreate( 11, comm_pkg, int_buf_data, dof_func_offd); hypre_ParCSRCommHandleDestroy(comm_handle); hypre_TFree(int_buf_data); } /*HYPRE_Int prefix_sum_workspace[2*(hypre_NumThreads() + 1)];*/ prefix_sum_workspace = hypre_TAlloc(HYPRE_Int, 2*(hypre_NumThreads() + 1)); /* give S same nonzero structure as A */ #ifdef HYPRE_USING_OPENMP #pragma omp parallel private(i,diag,row_scale,row_sum,jA,jS) #endif { HYPRE_Int start, stop; hypre_GetSimpleThreadPartition(&start, &stop, num_variables); HYPRE_Int jS_diag = 0, jS_offd = 0; for (i = start; i < stop; i++) { S_diag_i[i] = jS_diag; if (num_cols_offd) { S_offd_i[i] = jS_offd; } diag = A_diag_data[A_diag_i[i]]; /* compute scaling factor and row sum */ row_scale = 0.0; row_sum = diag; if (num_functions > 1) { if (diag < 0) { for (jA = A_diag_i[i]+1; jA < A_diag_i[i+1]; jA++) { if (dof_func[i] == dof_func[A_diag_j[jA]]) { row_scale = hypre_max(row_scale, A_diag_data[jA]); row_sum += A_diag_data[jA]; } } for (jA = A_offd_i[i]; jA < A_offd_i[i+1]; jA++) { if (dof_func[i] == dof_func_offd[A_offd_j[jA]]) { row_scale = hypre_max(row_scale, A_offd_data[jA]); row_sum += A_offd_data[jA]; } } } else { for (jA = A_diag_i[i]+1; jA < A_diag_i[i+1]; jA++) { if (dof_func[i] == dof_func[A_diag_j[jA]]) { row_scale = hypre_min(row_scale, A_diag_data[jA]); row_sum += A_diag_data[jA]; } } for (jA = A_offd_i[i]; jA < A_offd_i[i+1]; jA++) { if (dof_func[i] == dof_func_offd[A_offd_j[jA]]) { row_scale = hypre_min(row_scale, A_offd_data[jA]); row_sum += A_offd_data[jA]; } } } /* diag >= 0 */ } /* num_functions > 1 */ else { if (diag < 0) { for (jA = A_diag_i[i]+1; jA < A_diag_i[i+1]; jA++) { row_scale = hypre_max(row_scale, A_diag_data[jA]); row_sum += A_diag_data[jA]; } for (jA = A_offd_i[i]; jA < A_offd_i[i+1]; jA++) { row_scale = hypre_max(row_scale, A_offd_data[jA]); row_sum += A_offd_data[jA]; } } else { for (jA = A_diag_i[i]+1; jA < A_diag_i[i+1]; jA++) { row_scale = hypre_min(row_scale, A_diag_data[jA]); row_sum += A_diag_data[jA]; } for (jA = A_offd_i[i]; jA < A_offd_i[i+1]; jA++) { row_scale = hypre_min(row_scale, A_offd_data[jA]); row_sum += A_offd_data[jA]; } } /* diag >= 0*/ } /* num_functions <= 1 */ jS_diag += A_diag_i[i + 1] - A_diag_i[i] - 1; jS_offd += A_offd_i[i + 1] - A_offd_i[i]; /* compute row entries of S */ S_temp_diag_j[A_diag_i[i]] = -1; if ((fabs(row_sum) > fabs(diag)*max_row_sum) && (max_row_sum < 1.0)) { /* make all dependencies weak */ for (jA = A_diag_i[i]+1; jA < A_diag_i[i+1]; jA++) { S_temp_diag_j[jA] = -1; } jS_diag -= A_diag_i[i + 1] - (A_diag_i[i] + 1); for (jA = A_offd_i[i]; jA < A_offd_i[i+1]; jA++) { S_temp_offd_j[jA] = -1; } jS_offd -= A_offd_i[i + 1] - A_offd_i[i]; } else { if (num_functions > 1) { if (diag < 0) { for (jA = A_diag_i[i]+1; jA < A_diag_i[i+1]; jA++) { if (A_diag_data[jA] <= strength_threshold * row_scale || dof_func[i] != dof_func[A_diag_j[jA]]) { S_temp_diag_j[jA] = -1; --jS_diag; } else { S_temp_diag_j[jA] = A_diag_j[jA]; } } for (jA = A_offd_i[i]; jA < A_offd_i[i+1]; jA++) { if (A_offd_data[jA] <= strength_threshold * row_scale || dof_func[i] != dof_func_offd[A_offd_j[jA]]) { S_temp_offd_j[jA] = -1; --jS_offd; } else { S_temp_offd_j[jA] = A_offd_j[jA]; } } } else { for (jA = A_diag_i[i]+1; jA < A_diag_i[i+1]; jA++) { if (A_diag_data[jA] >= strength_threshold * row_scale || dof_func[i] != dof_func[A_diag_j[jA]]) { S_temp_diag_j[jA] = -1; --jS_diag; } else { S_temp_diag_j[jA] = A_diag_j[jA]; } } for (jA = A_offd_i[i]; jA < A_offd_i[i+1]; jA++) { if (A_offd_data[jA] >= strength_threshold * row_scale || dof_func[i] != dof_func_offd[A_offd_j[jA]]) { S_temp_offd_j[jA] = -1; --jS_offd; } else { S_temp_offd_j[jA] = A_offd_j[jA]; } } } /* diag >= 0 */ } /* num_functions > 1 */ else { if (diag < 0) { for (jA = A_diag_i[i]+1; jA < A_diag_i[i+1]; jA++) { if (A_diag_data[jA] <= strength_threshold * row_scale) { S_temp_diag_j[jA] = -1; --jS_diag; } else { S_temp_diag_j[jA] = A_diag_j[jA]; } } for (jA = A_offd_i[i]; jA < A_offd_i[i+1]; jA++) { if (A_offd_data[jA] <= strength_threshold * row_scale) { S_temp_offd_j[jA] = -1; --jS_offd; } else { S_temp_offd_j[jA] = A_offd_j[jA]; } } } else { for (jA = A_diag_i[i]+1; jA < A_diag_i[i+1]; jA++) { if (A_diag_data[jA] >= strength_threshold * row_scale) { S_temp_diag_j[jA] = -1; --jS_diag; } else { S_temp_diag_j[jA] = A_diag_j[jA]; } } for (jA = A_offd_i[i]; jA < A_offd_i[i+1]; jA++) { if (A_offd_data[jA] >= strength_threshold * row_scale) { S_temp_offd_j[jA] = -1; --jS_offd; } else { S_temp_offd_j[jA] = A_offd_j[jA]; } } } /* diag >= 0 */ } /* num_functions <= 1 */ } /* !((row_sum > max_row_sum) && (max_row_sum < 1.0)) */ } /* for each variable */ hypre_prefix_sum_pair(&jS_diag, S_diag_i + num_variables, &jS_offd, S_offd_i + num_variables, prefix_sum_workspace); /*-------------------------------------------------------------- * "Compress" the strength matrix. * * NOTE: S has *NO DIAGONAL ELEMENT* on any row. Caveat Emptor! * * NOTE: This "compression" section of code may be removed, and * coarsening will still be done correctly. However, the routine * that builds interpolation would have to be modified first. *----------------------------------------------------------------*/ for (i = start; i < stop; i++) { S_diag_i[i] += jS_diag; S_offd_i[i] += jS_offd; jS = S_diag_i[i]; for (jA = A_diag_i[i]; jA < A_diag_i[i+1]; jA++) { if (S_temp_diag_j[jA] > -1) { S_diag_j[jS] = S_temp_diag_j[jA]; jS++; } } jS = S_offd_i[i]; for (jA = A_offd_i[i]; jA < A_offd_i[i+1]; jA++) { if (S_temp_offd_j[jA] > -1) { S_offd_j[jS] = S_temp_offd_j[jA]; jS++; } } } /* for each variable */ } /* omp parallel */ hypre_CSRMatrixNumNonzeros(S_diag) = S_diag_i[num_variables]; hypre_CSRMatrixNumNonzeros(S_offd) = S_offd_i[num_variables]; hypre_CSRMatrixJ(S_diag) = S_diag_j; hypre_CSRMatrixJ(S_offd) = S_offd_j; hypre_ParCSRMatrixCommPkg(S) = NULL; *S_ptr = S; hypre_TFree(prefix_sum_workspace); hypre_TFree(dof_func_offd); hypre_TFree(S_temp_diag_j); hypre_TFree(S_temp_offd_j); #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_CREATES] += hypre_MPI_Wtime(); #endif return (ierr); } /*==========================================================================*/ /*==========================================================================*/ /** Generates strength matrix Notes: \begin{itemize} \item The underlying matrix storage scheme is a hypre_ParCSR matrix. \item The routine returns the following: \begin{itemize} \item S - a ParCSR matrix representing the "strength matrix". This is used in the coarsening and interpolation routines. \end{itemize} \item The graph of the "strength matrix" for A is a subgraph of the graph of A, but requires nonsymmetric storage even if A is symmetric. This is because of the directional nature of the "strengh of dependence" notion (see below). Since we are using nonsymmetric storage for A right now, this is not a problem. If we ever add the ability to store A symmetrically, then we could store the strength graph as floats instead of doubles to save space. \item This routine currently "compresses" the strength matrix. We should consider the possibility of defining this matrix to have the same "nonzero structure" as A. To do this, we could use the same A\_i and A\_j arrays, and would need only define the S\_data array. There are several pros and cons to discuss. \end{itemize} Terminology: \begin{itemize} \item Ruge's terminology: A point is "strongly connected to" $j$, or "strongly depends on" $j$, if $|a_ij| >= \theta max_{l != j} |a_il|}$. \item Here, we retain some of this terminology, but with a more generalized notion of "strength". We also retain the "natural" graph notation for representing the directed graph of a matrix. That is, the nonzero entry $a_ij$ is represented as: i --> j. In the strength matrix, S, the entry $s_ij$ is also graphically denoted as above, and means both of the following: \begin{itemize} \item $i$ "depends on" $j$ with "strength" $s_ij$ \item $j$ "influences" $i$ with "strength" $s_ij$ \end{itemize} \end{itemize} {\bf Input files:} _hypre_parcsr_ls.h @return Error code. @param A [IN] coefficient matrix @param strength_threshold [IN] threshold parameter used to define strength @param max_row_sum [IN] parameter used to modify definition of strength for diagonal dominant matrices @param S_ptr [OUT] strength matrix @see */ /*--------------------------------------------------------------------------*/ HYPRE_Int hypre_BoomerAMGCreateSabs(hypre_ParCSRMatrix *A, HYPRE_Real strength_threshold, HYPRE_Real max_row_sum, HYPRE_Int num_functions, HYPRE_Int *dof_func, hypre_ParCSRMatrix **S_ptr) { MPI_Comm comm = hypre_ParCSRMatrixComm(A); hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A); hypre_ParCSRCommHandle *comm_handle; hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag); HYPRE_Real *A_diag_data = hypre_CSRMatrixData(A_diag); hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd); HYPRE_Real *A_offd_data = NULL; HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag); HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd); HYPRE_Int *row_starts = hypre_ParCSRMatrixRowStarts(A); HYPRE_Int num_variables = hypre_CSRMatrixNumRows(A_diag); HYPRE_Int global_num_vars = hypre_ParCSRMatrixGlobalNumRows(A); HYPRE_Int num_nonzeros_diag; HYPRE_Int num_nonzeros_offd = 0; HYPRE_Int num_cols_offd = 0; hypre_ParCSRMatrix *S; hypre_CSRMatrix *S_diag; HYPRE_Int *S_diag_i; HYPRE_Int *S_diag_j; /* HYPRE_Real *S_diag_data; */ hypre_CSRMatrix *S_offd; HYPRE_Int *S_offd_i = NULL; HYPRE_Int *S_offd_j = NULL; /* HYPRE_Real *S_offd_data; */ HYPRE_Real diag, row_scale, row_sum; HYPRE_Int i, jA, jS; HYPRE_Int ierr = 0; HYPRE_Int *dof_func_offd; HYPRE_Int num_sends; HYPRE_Int *int_buf_data; HYPRE_Int index, start, j; /*-------------------------------------------------------------- * Compute a ParCSR strength matrix, S. * * For now, the "strength" of dependence/influence is defined in * the following way: i depends on j if * aij > hypre_max (k != i) aik, aii < 0 * or * aij < hypre_min (k != i) aik, aii >= 0 * Then S_ij = 1, else S_ij = 0. * * NOTE: the entries are negative initially, corresponding * to "unaccounted-for" dependence. *----------------------------------------------------------------*/ num_nonzeros_diag = A_diag_i[num_variables]; num_cols_offd = hypre_CSRMatrixNumCols(A_offd); A_offd_i = hypre_CSRMatrixI(A_offd); num_nonzeros_offd = A_offd_i[num_variables]; S = hypre_ParCSRMatrixCreate(comm, global_num_vars, global_num_vars, row_starts, row_starts, num_cols_offd, num_nonzeros_diag, num_nonzeros_offd); /* row_starts is owned by A, col_starts = row_starts */ hypre_ParCSRMatrixSetRowStartsOwner(S,0); S_diag = hypre_ParCSRMatrixDiag(S); hypre_CSRMatrixI(S_diag) = hypre_CTAlloc(HYPRE_Int, num_variables+1); hypre_CSRMatrixJ(S_diag) = hypre_CTAlloc(HYPRE_Int, num_nonzeros_diag); S_offd = hypre_ParCSRMatrixOffd(S); hypre_CSRMatrixI(S_offd) = hypre_CTAlloc(HYPRE_Int, num_variables+1); S_diag_i = hypre_CSRMatrixI(S_diag); S_diag_j = hypre_CSRMatrixJ(S_diag); S_offd_i = hypre_CSRMatrixI(S_offd); dof_func_offd = NULL; if (num_cols_offd) { A_offd_data = hypre_CSRMatrixData(A_offd); hypre_CSRMatrixJ(S_offd) = hypre_CTAlloc(HYPRE_Int, num_nonzeros_offd); S_offd_j = hypre_CSRMatrixJ(S_offd); hypre_ParCSRMatrixColMapOffd(S) = hypre_CTAlloc(HYPRE_Int, num_cols_offd); if (num_functions > 1) dof_func_offd = hypre_CTAlloc(HYPRE_Int, num_cols_offd); } /*------------------------------------------------------------------- * Get the dof_func data for the off-processor columns *-------------------------------------------------------------------*/ if (!comm_pkg) { hypre_MatvecCommPkgCreate(A); comm_pkg = hypre_ParCSRMatrixCommPkg(A); } num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); if (num_functions > 1) { int_buf_data = hypre_CTAlloc(HYPRE_Int,hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends)); index = 0; for (i = 0; i < num_sends; i++) { start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j=start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++) int_buf_data[index++] = dof_func[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)]; } comm_handle = hypre_ParCSRCommHandleCreate( 11, comm_pkg, int_buf_data, dof_func_offd); hypre_ParCSRCommHandleDestroy(comm_handle); hypre_TFree(int_buf_data); } /* give S same nonzero structure as A */ hypre_ParCSRMatrixCopy(A,S,0); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,diag,row_scale,row_sum,jA) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_variables; i++) { diag = A_diag_data[A_diag_i[i]]; /* compute scaling factor and row sum */ row_scale = 0.0; row_sum = diag; if (num_functions > 1) { for (jA = A_diag_i[i]+1; jA < A_diag_i[i+1]; jA++) { if (dof_func[i] == dof_func[A_diag_j[jA]]) { row_scale = hypre_max(row_scale, fabs(A_diag_data[jA])); row_sum += fabs(A_diag_data[jA]); } } for (jA = A_offd_i[i]; jA < A_offd_i[i+1]; jA++) { if (dof_func[i] == dof_func_offd[A_offd_j[jA]]) { row_scale = hypre_max(row_scale, fabs(A_offd_data[jA])); row_sum += fabs(A_offd_data[jA]); } } } else { for (jA = A_diag_i[i]+1; jA < A_diag_i[i+1]; jA++) { row_scale = hypre_max(row_scale, fabs(A_diag_data[jA])); row_sum += fabs(A_diag_data[jA]); } for (jA = A_offd_i[i]; jA < A_offd_i[i+1]; jA++) { row_scale = hypre_max(row_scale, fabs(A_offd_data[jA])); row_sum += fabs(A_offd_data[jA]); } } /* compute row entries of S */ S_diag_j[A_diag_i[i]] = -1; if ((fabs(row_sum) > fabs(diag)*max_row_sum) && (max_row_sum < 1.0)) { /* make all dependencies weak */ for (jA = A_diag_i[i]+1; jA < A_diag_i[i+1]; jA++) { S_diag_j[jA] = -1; } for (jA = A_offd_i[i]; jA < A_offd_i[i+1]; jA++) { S_offd_j[jA] = -1; } } else { if (num_functions > 1) { for (jA = A_diag_i[i]+1; jA < A_diag_i[i+1]; jA++) { if (fabs(A_diag_data[jA]) <= strength_threshold * row_scale || dof_func[i] != dof_func[A_diag_j[jA]]) { S_diag_j[jA] = -1; } } for (jA = A_offd_i[i]; jA < A_offd_i[i+1]; jA++) { if (fabs(A_offd_data[jA]) <= strength_threshold * row_scale || dof_func[i] != dof_func_offd[A_offd_j[jA]]) { S_offd_j[jA] = -1; } } } else { for (jA = A_diag_i[i]+1; jA < A_diag_i[i+1]; jA++) { if (fabs(A_diag_data[jA]) <= strength_threshold * row_scale) { S_diag_j[jA] = -1; } } for (jA = A_offd_i[i]; jA < A_offd_i[i+1]; jA++) { if (fabs(A_offd_data[jA]) <= strength_threshold * row_scale) { S_offd_j[jA] = -1; } } } } } /*-------------------------------------------------------------- * "Compress" the strength matrix. * * NOTE: S has *NO DIAGONAL ELEMENT* on any row. Caveat Emptor! * * NOTE: This "compression" section of code may be removed, and * coarsening will still be done correctly. However, the routine * that builds interpolation would have to be modified first. *----------------------------------------------------------------*/ /* RDF: not sure if able to thread this loop */ jS = 0; for (i = 0; i < num_variables; i++) { S_diag_i[i] = jS; for (jA = A_diag_i[i]; jA < A_diag_i[i+1]; jA++) { if (S_diag_j[jA] > -1) { S_diag_j[jS] = S_diag_j[jA]; jS++; } } } S_diag_i[num_variables] = jS; hypre_CSRMatrixNumNonzeros(S_diag) = jS; /* RDF: not sure if able to thread this loop */ jS = 0; for (i = 0; i < num_variables; i++) { S_offd_i[i] = jS; for (jA = A_offd_i[i]; jA < A_offd_i[i+1]; jA++) { if (S_offd_j[jA] > -1) { S_offd_j[jS] = S_offd_j[jA]; jS++; } } } S_offd_i[num_variables] = jS; hypre_CSRMatrixNumNonzeros(S_offd) = jS; hypre_ParCSRMatrixCommPkg(S) = NULL; *S_ptr = S; hypre_TFree(dof_func_offd); return (ierr); } /*--------------------------------------------------------------------------*/ HYPRE_Int hypre_BoomerAMGCreateSCommPkg(hypre_ParCSRMatrix *A, hypre_ParCSRMatrix *S, HYPRE_Int **col_offd_S_to_A_ptr) { MPI_Comm comm = hypre_ParCSRMatrixComm(A); hypre_MPI_Status *status; hypre_MPI_Request *requests; hypre_ParCSRCommPkg *comm_pkg_A = hypre_ParCSRMatrixCommPkg(A); hypre_ParCSRCommPkg *comm_pkg_S; hypre_ParCSRCommHandle *comm_handle; hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); HYPRE_Int *col_map_offd_A = hypre_ParCSRMatrixColMapOffd(A); hypre_CSRMatrix *S_diag = hypre_ParCSRMatrixDiag(S); hypre_CSRMatrix *S_offd = hypre_ParCSRMatrixOffd(S); HYPRE_Int *S_offd_i = hypre_CSRMatrixI(S_offd); HYPRE_Int *S_offd_j = hypre_CSRMatrixJ(S_offd); HYPRE_Int *col_map_offd_S = hypre_ParCSRMatrixColMapOffd(S); HYPRE_Int *recv_procs_A = hypre_ParCSRCommPkgRecvProcs(comm_pkg_A); HYPRE_Int *recv_vec_starts_A = hypre_ParCSRCommPkgRecvVecStarts(comm_pkg_A); HYPRE_Int *send_procs_A = hypre_ParCSRCommPkgSendProcs(comm_pkg_A); HYPRE_Int *send_map_starts_A = hypre_ParCSRCommPkgSendMapStarts(comm_pkg_A); HYPRE_Int *recv_procs_S; HYPRE_Int *recv_vec_starts_S; HYPRE_Int *send_procs_S; HYPRE_Int *send_map_starts_S; HYPRE_Int *send_map_elmts_S; HYPRE_Int *col_offd_S_to_A; HYPRE_Int *S_marker; HYPRE_Int *send_change; HYPRE_Int *recv_change; HYPRE_Int num_variables = hypre_CSRMatrixNumRows(S_diag); HYPRE_Int num_cols_offd_A = hypre_CSRMatrixNumCols(A_offd); HYPRE_Int num_cols_offd_S; HYPRE_Int i, j, jcol; HYPRE_Int proc, cnt, proc_cnt, total_nz; HYPRE_Int first_row; HYPRE_Int ierr = 0; HYPRE_Int num_sends_A = hypre_ParCSRCommPkgNumSends(comm_pkg_A); HYPRE_Int num_recvs_A = hypre_ParCSRCommPkgNumRecvs(comm_pkg_A); HYPRE_Int num_sends_S; HYPRE_Int num_recvs_S; HYPRE_Int num_nonzeros; num_nonzeros = S_offd_i[num_variables]; S_marker = NULL; if (num_cols_offd_A) S_marker = hypre_CTAlloc(HYPRE_Int,num_cols_offd_A); for (i=0; i < num_cols_offd_A; i++) S_marker[i] = -1; for (i=0; i < num_nonzeros; i++) { jcol = S_offd_j[i]; S_marker[jcol] = 0; } proc = 0; proc_cnt = 0; cnt = 0; num_recvs_S = 0; for (i=0; i < num_recvs_A; i++) { for (j=recv_vec_starts_A[i]; j < recv_vec_starts_A[i+1]; j++) { if (!S_marker[j]) { S_marker[j] = cnt; cnt++; proc = 1; } } if (proc) {num_recvs_S++; proc = 0;} } num_cols_offd_S = cnt; recv_change = NULL; recv_procs_S = NULL; send_change = NULL; if (col_map_offd_S) hypre_TFree(col_map_offd_S); col_map_offd_S = NULL; col_offd_S_to_A = NULL; if (num_recvs_A) recv_change = hypre_CTAlloc(HYPRE_Int, num_recvs_A); if (num_sends_A) send_change = hypre_CTAlloc(HYPRE_Int, num_sends_A); if (num_recvs_S) recv_procs_S = hypre_CTAlloc(HYPRE_Int, num_recvs_S); recv_vec_starts_S = hypre_CTAlloc(HYPRE_Int, num_recvs_S+1); if (num_cols_offd_S) { col_map_offd_S = hypre_CTAlloc(HYPRE_Int,num_cols_offd_S); col_offd_S_to_A = hypre_CTAlloc(HYPRE_Int,num_cols_offd_S); } if (num_cols_offd_S < num_cols_offd_A) { for (i=0; i < num_nonzeros; i++) { jcol = S_offd_j[i]; S_offd_j[i] = S_marker[jcol]; } proc = 0; proc_cnt = 0; cnt = 0; recv_vec_starts_S[0] = 0; for (i=0; i < num_recvs_A; i++) { for (j=recv_vec_starts_A[i]; j < recv_vec_starts_A[i+1]; j++) { if (S_marker[j] != -1) { col_map_offd_S[cnt] = col_map_offd_A[j]; col_offd_S_to_A[cnt++] = j; proc = 1; } } recv_change[i] = j-cnt-recv_vec_starts_A[i] +recv_vec_starts_S[proc_cnt]; if (proc) { recv_procs_S[proc_cnt++] = recv_procs_A[i]; recv_vec_starts_S[proc_cnt] = cnt; proc = 0; } } } else { for (i=0; i < num_recvs_A; i++) { for (j=recv_vec_starts_A[i]; j < recv_vec_starts_A[i+1]; j++) { col_map_offd_S[j] = col_map_offd_A[j]; col_offd_S_to_A[j] = j; } recv_procs_S[i] = recv_procs_A[i]; recv_vec_starts_S[i] = recv_vec_starts_A[i]; } recv_vec_starts_S[num_recvs_A] = recv_vec_starts_A[num_recvs_A]; } requests = hypre_CTAlloc(hypre_MPI_Request,num_sends_A+num_recvs_A); j=0; for (i=0; i < num_sends_A; i++) hypre_MPI_Irecv(&send_change[i],1,HYPRE_MPI_INT,send_procs_A[i], 0,comm,&requests[j++]); for (i=0; i < num_recvs_A; i++) hypre_MPI_Isend(&recv_change[i],1,HYPRE_MPI_INT,recv_procs_A[i], 0,comm,&requests[j++]); status = hypre_CTAlloc(hypre_MPI_Status,j); hypre_MPI_Waitall(j,requests,status); hypre_TFree(status); hypre_TFree(requests); num_sends_S = 0; total_nz = send_map_starts_A[num_sends_A]; for (i=0; i < num_sends_A; i++) { if (send_change[i]) { if ((send_map_starts_A[i+1]-send_map_starts_A[i]) > send_change[i]) num_sends_S++; } else num_sends_S++; total_nz -= send_change[i]; } send_procs_S = NULL; if (num_sends_S) send_procs_S = hypre_CTAlloc(HYPRE_Int,num_sends_S); send_map_starts_S = hypre_CTAlloc(HYPRE_Int,num_sends_S+1); send_map_elmts_S = NULL; if (total_nz) send_map_elmts_S = hypre_CTAlloc(HYPRE_Int,total_nz); proc = 0; proc_cnt = 0; for (i=0; i < num_sends_A; i++) { cnt = send_map_starts_A[i+1]-send_map_starts_A[i]-send_change[i]; if (cnt) { send_procs_S[proc_cnt++] = send_procs_A[i]; send_map_starts_S[proc_cnt] = send_map_starts_S[proc_cnt-1]+cnt; } } comm_pkg_S = hypre_CTAlloc(hypre_ParCSRCommPkg,1); hypre_ParCSRCommPkgComm(comm_pkg_S) = comm; hypre_ParCSRCommPkgNumRecvs(comm_pkg_S) = num_recvs_S; hypre_ParCSRCommPkgRecvProcs(comm_pkg_S) = recv_procs_S; hypre_ParCSRCommPkgRecvVecStarts(comm_pkg_S) = recv_vec_starts_S; hypre_ParCSRCommPkgNumSends(comm_pkg_S) = num_sends_S; hypre_ParCSRCommPkgSendProcs(comm_pkg_S) = send_procs_S; hypre_ParCSRCommPkgSendMapStarts(comm_pkg_S) = send_map_starts_S; comm_handle = hypre_ParCSRCommHandleCreate(12, comm_pkg_S, col_map_offd_S, send_map_elmts_S); hypre_ParCSRCommHandleDestroy(comm_handle); first_row = hypre_ParCSRMatrixFirstRowIndex(A); if (first_row) for (i=0; i < send_map_starts_S[num_sends_S]; i++) send_map_elmts_S[i] -= first_row; hypre_ParCSRCommPkgSendMapElmts(comm_pkg_S) = send_map_elmts_S; hypre_ParCSRMatrixCommPkg(S) = comm_pkg_S; hypre_ParCSRMatrixColMapOffd(S) = col_map_offd_S; hypre_CSRMatrixNumCols(S_offd) = num_cols_offd_S; hypre_TFree(S_marker); hypre_TFree(send_change); hypre_TFree(recv_change); *col_offd_S_to_A_ptr = col_offd_S_to_A; return ierr; } /*-------------------------------------------------------------------------- * hypre_BoomerAMGCreate2ndS : creates strength matrix on coarse points * for second coarsening pass in aggressive coarsening (S*S+2S) *--------------------------------------------------------------------------*/ HYPRE_Int hypre_BoomerAMGCreate2ndS( hypre_ParCSRMatrix *S, HYPRE_Int *CF_marker, HYPRE_Int num_paths, HYPRE_Int *coarse_row_starts, hypre_ParCSRMatrix **C_ptr) { #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_CREATE_2NDS] -= hypre_MPI_Wtime(); #endif MPI_Comm comm = hypre_ParCSRMatrixComm(S); hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(S); hypre_ParCSRCommPkg *tmp_comm_pkg; hypre_ParCSRCommHandle *comm_handle; hypre_CSRMatrix *S_diag = hypre_ParCSRMatrixDiag(S); HYPRE_Int *S_diag_i = hypre_CSRMatrixI(S_diag); HYPRE_Int *S_diag_j = hypre_CSRMatrixJ(S_diag); hypre_CSRMatrix *S_offd = hypre_ParCSRMatrixOffd(S); HYPRE_Int *S_offd_i = hypre_CSRMatrixI(S_offd); HYPRE_Int *S_offd_j = hypre_CSRMatrixJ(S_offd); HYPRE_Int num_cols_diag_S = hypre_CSRMatrixNumCols(S_diag); HYPRE_Int num_cols_offd_S = hypre_CSRMatrixNumCols(S_offd); hypre_ParCSRMatrix *S2; HYPRE_Int *col_map_offd_C = NULL; hypre_CSRMatrix *C_diag; /*HYPRE_Int *C_diag_data = NULL;*/ HYPRE_Int *C_diag_i; HYPRE_Int *C_diag_j = NULL; hypre_CSRMatrix *C_offd; /*HYPRE_Int *C_offd_data=NULL;*/ HYPRE_Int *C_offd_i; HYPRE_Int *C_offd_j=NULL; HYPRE_Int num_cols_offd_C = 0; HYPRE_Int *S_ext_diag_i = NULL; HYPRE_Int *S_ext_diag_j = NULL; HYPRE_Int S_ext_diag_size = 0; HYPRE_Int *S_ext_offd_i = NULL; HYPRE_Int *S_ext_offd_j = NULL; HYPRE_Int S_ext_offd_size = 0; HYPRE_Int *CF_marker_offd = NULL; HYPRE_Int *S_marker = NULL; HYPRE_Int *S_marker_offd = NULL; HYPRE_Int *temp = NULL; HYPRE_Int *fine_to_coarse = NULL; HYPRE_Int *fine_to_coarse_offd = NULL; HYPRE_Int *map_S_to_C = NULL; HYPRE_Int num_sends = 0; HYPRE_Int num_recvs = 0; HYPRE_Int *send_map_starts; HYPRE_Int *tmp_send_map_starts = NULL; HYPRE_Int *send_map_elmts; HYPRE_Int *recv_vec_starts; HYPRE_Int *tmp_recv_vec_starts = NULL; HYPRE_Int *int_buf_data = NULL; HYPRE_Int i, j, k; HYPRE_Int i1, i2, i3; HYPRE_Int jj1, jj2, jrow, j_cnt; /*HYPRE_Int cnt, cnt_offd, cnt_diag;*/ HYPRE_Int num_procs, my_id; HYPRE_Int index; /*HYPRE_Int value;*/ HYPRE_Int num_coarse; HYPRE_Int num_nonzeros; HYPRE_Int global_num_coarse; HYPRE_Int my_first_cpt, my_last_cpt; HYPRE_Int *S_int_i = NULL; HYPRE_Int *S_int_j = NULL; HYPRE_Int *S_ext_i = NULL; HYPRE_Int *S_ext_j = NULL; /*HYPRE_Int prefix_sum_workspace[2*(hypre_NumThreads() + 1)];*/ HYPRE_Int *prefix_sum_workspace; HYPRE_Int *num_coarse_prefix_sum; prefix_sum_workspace = hypre_TAlloc(HYPRE_Int, 2*(hypre_NumThreads() + 1)); num_coarse_prefix_sum = hypre_TAlloc(HYPRE_Int, hypre_NumThreads() + 1); /*----------------------------------------------------------------------- * Extract S_ext, i.e. portion of B that is stored on neighbor procs * and needed locally for matrix matrix product *-----------------------------------------------------------------------*/ hypre_MPI_Comm_size(comm, &num_procs); hypre_MPI_Comm_rank(comm, &my_id); #ifdef HYPRE_NO_GLOBAL_PARTITION my_first_cpt = coarse_row_starts[0]; my_last_cpt = coarse_row_starts[1]-1; if (my_id == (num_procs -1)) global_num_coarse = coarse_row_starts[1]; hypre_MPI_Bcast(&global_num_coarse, 1, HYPRE_MPI_INT, num_procs-1, comm); #else my_first_cpt = coarse_row_starts[my_id]; my_last_cpt = coarse_row_starts[my_id+1]-1; global_num_coarse = coarse_row_starts[num_procs]; #endif if (num_cols_offd_S) { CF_marker_offd = hypre_TAlloc(HYPRE_Int, num_cols_offd_S); fine_to_coarse_offd = hypre_TAlloc(HYPRE_Int, num_cols_offd_S); } HYPRE_Int *coarse_to_fine = NULL; if (num_cols_diag_S) { fine_to_coarse = hypre_TAlloc(HYPRE_Int, num_cols_diag_S); coarse_to_fine = hypre_TAlloc(HYPRE_Int, num_cols_diag_S); } /*HYPRE_Int num_coarse_prefix_sum[hypre_NumThreads() + 1];*/ #ifdef HYPRE_USING_OPENMP #pragma omp parallel private(i) #endif { HYPRE_Int num_coarse_private = 0; HYPRE_Int i_begin, i_end; hypre_GetSimpleThreadPartition(&i_begin, &i_end, num_cols_diag_S); for (i = i_begin; i < i_end; i++) { if (CF_marker[i] > 0) num_coarse_private++; } hypre_prefix_sum(&num_coarse_private, &num_coarse, num_coarse_prefix_sum); for (i = i_begin; i < i_end; i++) { if (CF_marker[i] > 0) { fine_to_coarse[i] = num_coarse_private; coarse_to_fine[num_coarse_private] = i; num_coarse_private++; } else { fine_to_coarse[i] = -1; } } } /* omp parallel */ if (num_procs > 1) { if (!comm_pkg) { hypre_MatvecCommPkgCreate(S); comm_pkg = hypre_ParCSRMatrixCommPkg(S); } num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); send_map_starts = hypre_ParCSRCommPkgSendMapStarts(comm_pkg); send_map_elmts = hypre_ParCSRCommPkgSendMapElmts(comm_pkg); num_recvs = hypre_ParCSRCommPkgNumRecvs(comm_pkg); recv_vec_starts = hypre_ParCSRCommPkgRecvVecStarts(comm_pkg); HYPRE_Int begin = send_map_starts[0]; HYPRE_Int end = send_map_starts[num_sends]; int_buf_data = hypre_TAlloc(HYPRE_Int, end); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for HYPRE_SMP_SCHEDULE #endif for (index = begin; index < end; index++) { int_buf_data[index - begin] = fine_to_coarse[send_map_elmts[index]] + my_first_cpt; } comm_handle = hypre_ParCSRCommHandleCreate( 11, comm_pkg, int_buf_data, fine_to_coarse_offd); hypre_ParCSRCommHandleDestroy(comm_handle); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for HYPRE_SMP_SCHEDULE #endif for (index = begin; index < end; index++) { int_buf_data[index - begin] = CF_marker[send_map_elmts[index]]; } comm_handle = hypre_ParCSRCommHandleCreate(11, comm_pkg, int_buf_data, CF_marker_offd); hypre_ParCSRCommHandleDestroy(comm_handle); hypre_TFree(int_buf_data); S_int_i = hypre_TAlloc(HYPRE_Int, end+1); S_ext_i = hypre_CTAlloc(HYPRE_Int, recv_vec_starts[num_recvs]+1); /*-------------------------------------------------------------------------- * generate S_int_i through adding number of coarse row-elements of offd and diag * for corresponding rows. S_int_i[j+1] contains the number of coarse elements of * a row j (which is determined through send_map_elmts) *--------------------------------------------------------------------------*/ S_int_i[0] = 0; num_nonzeros = 0; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(j,k) reduction(+:num_nonzeros) HYPRE_SMP_SCHEDULE #endif for (j = begin; j < end; j++) { HYPRE_Int jrow = send_map_elmts[j]; HYPRE_Int index = 0; for (k = S_diag_i[jrow]; k < S_diag_i[jrow+1]; k++) { if (CF_marker[S_diag_j[k]] > 0) index++; } for (k = S_offd_i[jrow]; k < S_offd_i[jrow+1]; k++) { if (CF_marker_offd[S_offd_j[k]] > 0) index++; } S_int_i[j - begin + 1] = index; num_nonzeros += S_int_i[j - begin + 1]; } /*-------------------------------------------------------------------------- * initialize communication *--------------------------------------------------------------------------*/ if (num_procs > 1) comm_handle = hypre_ParCSRCommHandleCreate(11,comm_pkg,&S_int_i[1],&S_ext_i[1]); if (num_nonzeros) S_int_j = hypre_TAlloc(HYPRE_Int, num_nonzeros); tmp_send_map_starts = hypre_CTAlloc(HYPRE_Int, num_sends+1); tmp_recv_vec_starts = hypre_CTAlloc(HYPRE_Int, num_recvs+1); tmp_send_map_starts[0] = 0; j_cnt = 0; for (i=0; i < num_sends; i++) { for (j = send_map_starts[i]; j < send_map_starts[i+1]; j++) { jrow = send_map_elmts[j]; for (k=S_diag_i[jrow]; k < S_diag_i[jrow+1]; k++) { if (CF_marker[S_diag_j[k]] > 0) S_int_j[j_cnt++] = fine_to_coarse[S_diag_j[k]]+my_first_cpt; } for (k=S_offd_i[jrow]; k < S_offd_i[jrow+1]; k++) { if (CF_marker_offd[S_offd_j[k]] > 0) S_int_j[j_cnt++] = fine_to_coarse_offd[S_offd_j[k]]; } } tmp_send_map_starts[i+1] = j_cnt; } tmp_comm_pkg = hypre_CTAlloc(hypre_ParCSRCommPkg,1); hypre_ParCSRCommPkgComm(tmp_comm_pkg) = comm; hypre_ParCSRCommPkgNumSends(tmp_comm_pkg) = num_sends; hypre_ParCSRCommPkgNumRecvs(tmp_comm_pkg) = num_recvs; hypre_ParCSRCommPkgSendProcs(tmp_comm_pkg) = hypre_ParCSRCommPkgSendProcs(comm_pkg); hypre_ParCSRCommPkgRecvProcs(tmp_comm_pkg) = hypre_ParCSRCommPkgRecvProcs(comm_pkg); hypre_ParCSRCommPkgSendMapStarts(tmp_comm_pkg) = tmp_send_map_starts; hypre_ParCSRCommHandleDestroy(comm_handle); comm_handle = NULL; /*-------------------------------------------------------------------------- * after communication exchange S_ext_i[j+1] contains the number of coarse elements * of a row j ! * evaluate S_ext_i and compute num_nonzeros for S_ext *--------------------------------------------------------------------------*/ for (i=0; i < recv_vec_starts[num_recvs]; i++) S_ext_i[i+1] += S_ext_i[i]; num_nonzeros = S_ext_i[recv_vec_starts[num_recvs]]; if (num_nonzeros) S_ext_j = hypre_TAlloc(HYPRE_Int, num_nonzeros); tmp_recv_vec_starts[0] = 0; for (i=0; i < num_recvs; i++) tmp_recv_vec_starts[i+1] = S_ext_i[recv_vec_starts[i+1]]; hypre_ParCSRCommPkgRecvVecStarts(tmp_comm_pkg) = tmp_recv_vec_starts; comm_handle = hypre_ParCSRCommHandleCreate(11,tmp_comm_pkg,S_int_j,S_ext_j); hypre_ParCSRCommHandleDestroy(comm_handle); comm_handle = NULL; hypre_TFree(tmp_send_map_starts); hypre_TFree(tmp_recv_vec_starts); hypre_TFree(tmp_comm_pkg); hypre_TFree(S_int_i); hypre_TFree(S_int_j); #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_RENUMBER_COLIDX] -= hypre_MPI_Wtime(); #endif #ifdef HYPRE_CONCURRENT_HOPSCOTCH S_ext_diag_i = hypre_TAlloc(HYPRE_Int, num_cols_offd_S+1); S_ext_diag_i[0] = 0; S_ext_offd_i = hypre_TAlloc(HYPRE_Int, num_cols_offd_S+1); S_ext_offd_i[0] = 0; /*HYPRE_Int temp_size = 0;*/ hypre_UnorderedIntSet found_set; hypre_UnorderedIntSetCreate(&found_set, S_ext_i[num_cols_offd_S] + num_cols_offd_S, 16*hypre_NumThreads()); #pragma omp parallel private(i,j) { HYPRE_Int S_ext_offd_size_private = 0; HYPRE_Int S_ext_diag_size_private = 0; HYPRE_Int i_begin, i_end; hypre_GetSimpleThreadPartition(&i_begin, &i_end, num_cols_offd_S); for (i = i_begin; i < i_end; i++) { if (CF_marker_offd[i] > 0) { hypre_UnorderedIntSetPut(&found_set, fine_to_coarse_offd[i]); } for (j=S_ext_i[i]; j < S_ext_i[i+1]; j++) { HYPRE_Int i1 = S_ext_j[j]; if (i1 < my_first_cpt || i1 > my_last_cpt) { S_ext_offd_size_private++; hypre_UnorderedIntSetPut(&found_set, i1); } else S_ext_diag_size_private++; } } hypre_prefix_sum_pair( &S_ext_diag_size_private, &S_ext_diag_size, &S_ext_offd_size_private, &S_ext_offd_size, prefix_sum_workspace); #pragma omp master { if (S_ext_diag_size) S_ext_diag_j = hypre_TAlloc(HYPRE_Int, S_ext_diag_size); if (S_ext_offd_size) S_ext_offd_j = hypre_TAlloc(HYPRE_Int, S_ext_offd_size); } #pragma omp barrier for (i = i_begin; i < i_end; i++) { for (j=S_ext_i[i]; j < S_ext_i[i+1]; j++) { HYPRE_Int i1 = S_ext_j[j]; if (i1 < my_first_cpt || i1 > my_last_cpt) S_ext_offd_j[S_ext_offd_size_private++] = i1; else S_ext_diag_j[S_ext_diag_size_private++] = i1 - my_first_cpt; } S_ext_diag_i[i + 1] = S_ext_diag_size_private; S_ext_offd_i[i + 1] = S_ext_offd_size_private; } } // omp parallel temp = hypre_UnorderedIntSetCopyToArray(&found_set, &num_cols_offd_C); hypre_UnorderedIntSetDestroy( &found_set); hypre_TFree(S_ext_i); hypre_TFree(S_ext_j); hypre_UnorderedIntMap col_map_offd_C_inverse; hypre_sort_and_create_inverse_map(temp, num_cols_offd_C, &col_map_offd_C, &col_map_offd_C_inverse); #pragma omp parallel for HYPRE_SMP_SCHEDULE for (i=0 ; i < S_ext_offd_size; i++) S_ext_offd_j[i] = hypre_UnorderedIntMapGet(&col_map_offd_C_inverse, S_ext_offd_j[i]); if (num_cols_offd_C) hypre_UnorderedIntMapDestroy(&col_map_offd_C_inverse); #else /* !HYPRE_CONCURRENT_HOPSCOTCH */ HYPRE_Int cnt_offd, cnt_diag, cnt, value; S_ext_diag_size = 0; S_ext_offd_size = 0; for (i=0; i < num_cols_offd_S; i++) { for (j=S_ext_i[i]; j < S_ext_i[i+1]; j++) { if (S_ext_j[j] < my_first_cpt || S_ext_j[j] > my_last_cpt) S_ext_offd_size++; else S_ext_diag_size++; } } S_ext_diag_i = hypre_CTAlloc(HYPRE_Int, num_cols_offd_S+1); S_ext_offd_i = hypre_CTAlloc(HYPRE_Int, num_cols_offd_S+1); if (S_ext_diag_size) { S_ext_diag_j = hypre_CTAlloc(HYPRE_Int, S_ext_diag_size); } if (S_ext_offd_size) { S_ext_offd_j = hypre_CTAlloc(HYPRE_Int, S_ext_offd_size); } cnt_offd = 0; cnt_diag = 0; cnt = 0; HYPRE_Int num_coarse_offd = 0; for (i=0; i < num_cols_offd_S; i++) { if (CF_marker_offd[i] > 0) num_coarse_offd++; for (j=S_ext_i[i]; j < S_ext_i[i+1]; j++) { i1 = S_ext_j[j]; if (i1 < my_first_cpt || i1 > my_last_cpt) S_ext_offd_j[cnt_offd++] = i1; else S_ext_diag_j[cnt_diag++] = i1 - my_first_cpt; } S_ext_diag_i[++cnt] = cnt_diag; S_ext_offd_i[cnt] = cnt_offd; } hypre_TFree(S_ext_i); hypre_TFree(S_ext_j); cnt = 0; if (S_ext_offd_size || num_coarse_offd) { temp = hypre_CTAlloc(HYPRE_Int, S_ext_offd_size+num_coarse_offd); for (i=0; i < S_ext_offd_size; i++) temp[i] = S_ext_offd_j[i]; cnt = S_ext_offd_size; for (i=0; i < num_cols_offd_S; i++) if (CF_marker_offd[i] > 0) temp[cnt++] = fine_to_coarse_offd[i]; } if (cnt) { hypre_qsort0(temp, 0, cnt-1); num_cols_offd_C = 1; value = temp[0]; for (i=1; i < cnt; i++) { if (temp[i] > value) { value = temp[i]; temp[num_cols_offd_C++] = value; } } } if (num_cols_offd_C) col_map_offd_C = hypre_CTAlloc(HYPRE_Int,num_cols_offd_C); for (i=0; i < num_cols_offd_C; i++) col_map_offd_C[i] = temp[i]; if (S_ext_offd_size || num_coarse_offd) hypre_TFree(temp); for (i=0 ; i < S_ext_offd_size; i++) S_ext_offd_j[i] = hypre_BinarySearch(col_map_offd_C, S_ext_offd_j[i], num_cols_offd_C); #endif /* !HYPRE_CONCURRENT_HOPSCOTCH */ if (num_cols_offd_S) { map_S_to_C = hypre_TAlloc(HYPRE_Int,num_cols_offd_S); #ifdef HYPRE_USING_OPENMP #pragma omp parallel private(i) #endif { HYPRE_Int i_begin, i_end; hypre_GetSimpleThreadPartition(&i_begin, &i_end, num_cols_offd_S); HYPRE_Int cnt = 0; for (i = i_begin; i < i_end; i++) { if (CF_marker_offd[i] > 0) { cnt = hypre_LowerBound(col_map_offd_C + cnt, col_map_offd_C + num_cols_offd_C, fine_to_coarse_offd[i]) - col_map_offd_C; map_S_to_C[i] = cnt++; } else map_S_to_C[i] = -1; } } /* omp parallel */ } #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_RENUMBER_COLIDX] += hypre_MPI_Wtime(); #endif } /* num_procs > 1 */ /*----------------------------------------------------------------------- * Allocate and initialize some stuff. *-----------------------------------------------------------------------*/ HYPRE_Int *S_marker_array = NULL, *S_marker_offd_array = NULL; if (num_coarse) S_marker_array = hypre_TAlloc(HYPRE_Int, num_coarse*hypre_NumThreads()); if (num_cols_offd_C) S_marker_offd_array = hypre_TAlloc(HYPRE_Int, num_cols_offd_C*hypre_NumThreads()); HYPRE_Int *C_temp_offd_j_array = NULL; HYPRE_Int *C_temp_diag_j_array = NULL; HYPRE_Int *C_temp_offd_data_array = NULL; HYPRE_Int *C_temp_diag_data_array = NULL; if (num_paths > 1) { C_temp_diag_j_array = hypre_TAlloc(HYPRE_Int, num_coarse*hypre_NumThreads()); C_temp_offd_j_array = hypre_TAlloc(HYPRE_Int, num_cols_offd_C*hypre_NumThreads()); C_temp_diag_data_array = hypre_TAlloc(HYPRE_Int, num_coarse*hypre_NumThreads()); C_temp_offd_data_array = hypre_TAlloc(HYPRE_Int, num_cols_offd_C*hypre_NumThreads()); } C_diag_i = hypre_CTAlloc(HYPRE_Int, num_coarse+1); C_offd_i = hypre_CTAlloc(HYPRE_Int, num_coarse+1); /*----------------------------------------------------------------------- * Loop over rows of S *-----------------------------------------------------------------------*/ #ifdef HYPRE_USING_OPENMP #pragma omp parallel private(i1,i2,i3,jj1,jj2,index) #endif { HYPRE_Int my_thread_num = hypre_GetThreadNum(); HYPRE_Int i1_begin, i1_end; hypre_GetSimpleThreadPartition(&i1_begin, &i1_end, num_cols_diag_S); HYPRE_Int *C_temp_diag_j = NULL, *C_temp_offd_j = NULL; HYPRE_Int *C_temp_diag_data = NULL, *C_temp_offd_data = NULL; if (num_paths > 1) { C_temp_diag_j = C_temp_diag_j_array + num_coarse*my_thread_num; C_temp_offd_j = C_temp_offd_j_array + num_cols_offd_C*my_thread_num; C_temp_diag_data = C_temp_diag_data_array + num_coarse*my_thread_num; C_temp_offd_data = C_temp_offd_data_array + num_cols_offd_C*my_thread_num; } HYPRE_Int *S_marker = NULL, *S_marker_offd = NULL; if (num_coarse) S_marker = S_marker_array + num_coarse*my_thread_num; if (num_cols_offd_C) S_marker_offd = S_marker_offd_array + num_cols_offd_C*my_thread_num; for (i1 = 0; i1 < num_coarse; i1++) { S_marker[i1] = -1; } for (i1 = 0; i1 < num_cols_offd_C; i1++) { S_marker_offd[i1] = -1; } // These two counters are for before filtering by num_paths HYPRE_Int jj_count_diag = 0; HYPRE_Int jj_count_offd = 0; // These two counters are for after filtering by num_paths HYPRE_Int num_nonzeros_diag = 0; HYPRE_Int num_nonzeros_offd = 0; HYPRE_Int ic_begin = num_coarse_prefix_sum[my_thread_num]; HYPRE_Int ic_end = num_coarse_prefix_sum[my_thread_num + 1]; HYPRE_Int ic; if (num_paths == 1) { for (ic = ic_begin; ic < ic_end; ic++) { /*-------------------------------------------------------------------- * Set marker for diagonal entry, C_{i1,i1} (for square matrices). *--------------------------------------------------------------------*/ HYPRE_Int i1 = coarse_to_fine[ic]; HYPRE_Int jj_row_begin_diag = num_nonzeros_diag; HYPRE_Int jj_row_begin_offd = num_nonzeros_offd; C_diag_i[ic] = num_nonzeros_diag; if (num_cols_offd_C) { C_offd_i[ic] = num_nonzeros_offd; } for (jj1 = S_diag_i[i1]; jj1 < S_diag_i[i1+1]; jj1++) { i2 = S_diag_j[jj1]; if (CF_marker[i2] > 0) { index = fine_to_coarse[i2]; if (S_marker[index] < jj_row_begin_diag) { S_marker[index] = num_nonzeros_diag; num_nonzeros_diag++; } } for (jj2 = S_diag_i[i2]; jj2 < S_diag_i[i2+1]; jj2++) { i3 = S_diag_j[jj2]; if (CF_marker[i3] > 0) { index = fine_to_coarse[i3]; if (index != ic && S_marker[index] < jj_row_begin_diag) { S_marker[index] = num_nonzeros_diag; num_nonzeros_diag++; } } } for (jj2 = S_offd_i[i2]; jj2 < S_offd_i[i2+1]; jj2++) { i3 = S_offd_j[jj2]; if (CF_marker_offd[i3] > 0) { index = map_S_to_C[i3]; if (S_marker_offd[index] < jj_row_begin_offd) { S_marker_offd[index] = num_nonzeros_offd; num_nonzeros_offd++; } } } } for (jj1 = S_offd_i[i1]; jj1 < S_offd_i[i1+1]; jj1++) { i2 = S_offd_j[jj1]; if (CF_marker_offd[i2] > 0) { index = map_S_to_C[i2]; if (S_marker_offd[index] < jj_row_begin_offd) { S_marker_offd[index] = num_nonzeros_offd; num_nonzeros_offd++; } } for (jj2 = S_ext_diag_i[i2]; jj2 < S_ext_diag_i[i2+1]; jj2++) { i3 = S_ext_diag_j[jj2]; if (i3 != ic && S_marker[i3] < jj_row_begin_diag) { S_marker[i3] = num_nonzeros_diag; num_nonzeros_diag++; } } for (jj2 = S_ext_offd_i[i2]; jj2 < S_ext_offd_i[i2+1]; jj2++) { i3 = S_ext_offd_j[jj2]; if (S_marker_offd[i3] < jj_row_begin_offd) { S_marker_offd[i3] = num_nonzeros_offd; num_nonzeros_offd++; } } } } /* for each row */ } /* num_paths == 1 */ else { for (ic = ic_begin; ic < ic_end; ic++) { /*-------------------------------------------------------------------- * Set marker for diagonal entry, C_{i1,i1} (for square matrices). *--------------------------------------------------------------------*/ HYPRE_Int i1 = coarse_to_fine[ic]; HYPRE_Int jj_row_begin_diag = jj_count_diag; HYPRE_Int jj_row_begin_offd = jj_count_offd; C_diag_i[ic] = num_nonzeros_diag; if (num_cols_offd_C) { C_offd_i[ic] = num_nonzeros_offd; } for (jj1 = S_diag_i[i1]; jj1 < S_diag_i[i1+1]; jj1++) { i2 = S_diag_j[jj1]; if (CF_marker[i2] > 0) { index = fine_to_coarse[i2]; if (S_marker[index] < jj_row_begin_diag) { S_marker[index] = jj_count_diag; C_temp_diag_data[jj_count_diag - jj_row_begin_diag] = 2; jj_count_diag++; } else { C_temp_diag_data[S_marker[index] - jj_row_begin_diag] += 2; } } for (jj2 = S_diag_i[i2]; jj2 < S_diag_i[i2+1]; jj2++) { i3 = S_diag_j[jj2]; if (CF_marker[i3] > 0 && fine_to_coarse[i3] != ic) { index = fine_to_coarse[i3]; if (S_marker[index] < jj_row_begin_diag) { S_marker[index] = jj_count_diag; C_temp_diag_data[jj_count_diag - jj_row_begin_diag] = 1; jj_count_diag++; } else { C_temp_diag_data[S_marker[index] - jj_row_begin_diag]++; } } } for (jj2 = S_offd_i[i2]; jj2 < S_offd_i[i2+1]; jj2++) { i3 = S_offd_j[jj2]; if (CF_marker_offd[i3] > 0) { index = map_S_to_C[i3]; if (S_marker_offd[index] < jj_row_begin_offd) { S_marker_offd[index] = jj_count_offd; C_temp_offd_data[jj_count_offd - jj_row_begin_offd] = 1; jj_count_offd++; } else { C_temp_offd_data[S_marker_offd[index] - jj_row_begin_offd]++; } } } } for (jj1 = S_offd_i[i1]; jj1 < S_offd_i[i1+1]; jj1++) { i2 = S_offd_j[jj1]; if (CF_marker_offd[i2] > 0) { index = map_S_to_C[i2]; if (S_marker_offd[index] < jj_row_begin_offd) { S_marker_offd[index] = jj_count_offd; C_temp_offd_data[jj_count_offd - jj_row_begin_offd] = 2; jj_count_offd++; } else { C_temp_offd_data[S_marker_offd[index] - jj_row_begin_offd] += 2; } } for (jj2 = S_ext_diag_i[i2]; jj2 < S_ext_diag_i[i2+1]; jj2++) { i3 = S_ext_diag_j[jj2]; if (i3 != ic) { if (S_marker[i3] < jj_row_begin_diag) { S_marker[i3] = jj_count_diag; C_temp_diag_data[jj_count_diag - jj_row_begin_diag] = 1; jj_count_diag++; } else { C_temp_diag_data[S_marker[i3] - jj_row_begin_diag]++; } } } for (jj2 = S_ext_offd_i[i2]; jj2 < S_ext_offd_i[i2+1]; jj2++) { i3 = S_ext_offd_j[jj2]; if (S_marker_offd[i3] < jj_row_begin_offd) { S_marker_offd[i3] = jj_count_offd; C_temp_offd_data[jj_count_offd - jj_row_begin_offd] = 1; jj_count_offd++; } else { C_temp_offd_data[S_marker_offd[i3] - jj_row_begin_offd]++; } } } for (jj1 = jj_row_begin_diag; jj1 < jj_count_diag; jj1++) { if (C_temp_diag_data[jj1 - jj_row_begin_diag] >= num_paths) { ++num_nonzeros_diag; } C_temp_diag_data[jj1 - jj_row_begin_diag] = 0; } for (jj1 = jj_row_begin_offd; jj1 < jj_count_offd; jj1++) { if (C_temp_offd_data[jj1 - jj_row_begin_offd] >= num_paths) { ++num_nonzeros_offd; } C_temp_offd_data[jj1 - jj_row_begin_offd] = 0; } } /* for each row */ } /* num_paths > 1 */ hypre_prefix_sum_pair( &num_nonzeros_diag, &C_diag_i[num_coarse], &num_nonzeros_offd, &C_offd_i[num_coarse], prefix_sum_workspace); for (i1 = 0; i1 < num_coarse; i1++) { S_marker[i1] = -1; } for (i1 = 0; i1 < num_cols_offd_C; i1++) { S_marker_offd[i1] = -1; } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #pragma omp master #endif { if (C_diag_i[num_coarse]) { C_diag_j = hypre_TAlloc(HYPRE_Int, C_diag_i[num_coarse]); } if (C_offd_i[num_coarse]) { C_offd_j = hypre_TAlloc(HYPRE_Int, C_offd_i[num_coarse]); } } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif for (ic = ic_begin; ic < ic_end - 1; ic++) { if (C_diag_i[ic+1] == C_diag_i[ic] && C_offd_i[ic+1] == C_offd_i[ic]) CF_marker[coarse_to_fine[ic]] = 2; C_diag_i[ic] += num_nonzeros_diag; C_offd_i[ic] += num_nonzeros_offd; } if (ic_begin < ic_end) { C_diag_i[ic] += num_nonzeros_diag; C_offd_i[ic] += num_nonzeros_offd; HYPRE_Int next_C_diag_i = prefix_sum_workspace[2*(my_thread_num + 1)]; HYPRE_Int next_C_offd_i = prefix_sum_workspace[2*(my_thread_num + 1) + 1]; if (next_C_diag_i == C_diag_i[ic] && next_C_offd_i == C_offd_i[ic]) CF_marker[coarse_to_fine[ic]] = 2; } if (num_paths == 1) { for (ic = ic_begin; ic < ic_end; ic++) { /*-------------------------------------------------------------------- * Set marker for diagonal entry, C_{i1,i1} (for square matrices). *--------------------------------------------------------------------*/ HYPRE_Int i1 = coarse_to_fine[ic]; HYPRE_Int jj_row_begin_diag = num_nonzeros_diag; HYPRE_Int jj_row_begin_offd = num_nonzeros_offd; for (jj1 = S_diag_i[i1]; jj1 < S_diag_i[i1+1]; jj1++) { i2 = S_diag_j[jj1]; if (CF_marker[i2] > 0) { index = fine_to_coarse[i2]; if (S_marker[index] < jj_row_begin_diag) { S_marker[index] = num_nonzeros_diag; C_diag_j[num_nonzeros_diag] = index; num_nonzeros_diag++; } } for (jj2 = S_diag_i[i2]; jj2 < S_diag_i[i2+1]; jj2++) { i3 = S_diag_j[jj2]; if (CF_marker[i3] > 0) { index = fine_to_coarse[i3]; if (index != ic && S_marker[index] < jj_row_begin_diag) { S_marker[index] = num_nonzeros_diag; C_diag_j[num_nonzeros_diag] = index; num_nonzeros_diag++; } } } for (jj2 = S_offd_i[i2]; jj2 < S_offd_i[i2+1]; jj2++) { i3 = S_offd_j[jj2]; if (CF_marker_offd[i3] > 0) { index = map_S_to_C[i3]; if (S_marker_offd[index] < jj_row_begin_offd) { S_marker_offd[index] = num_nonzeros_offd; C_offd_j[num_nonzeros_offd] = index; num_nonzeros_offd++; } } } } for (jj1 = S_offd_i[i1]; jj1 < S_offd_i[i1+1]; jj1++) { i2 = S_offd_j[jj1]; if (CF_marker_offd[i2] > 0) { index = map_S_to_C[i2]; if (S_marker_offd[index] < jj_row_begin_offd) { S_marker_offd[index] = num_nonzeros_offd; C_offd_j[num_nonzeros_offd] = index; num_nonzeros_offd++; } } for (jj2 = S_ext_diag_i[i2]; jj2 < S_ext_diag_i[i2+1]; jj2++) { i3 = S_ext_diag_j[jj2]; if (i3 != ic && S_marker[i3] < jj_row_begin_diag) { S_marker[i3] = num_nonzeros_diag; C_diag_j[num_nonzeros_diag] = i3; num_nonzeros_diag++; } } for (jj2 = S_ext_offd_i[i2]; jj2 < S_ext_offd_i[i2+1]; jj2++) { i3 = S_ext_offd_j[jj2]; if (S_marker_offd[i3] < jj_row_begin_offd) { S_marker_offd[i3] = num_nonzeros_offd; C_offd_j[num_nonzeros_offd] = i3; num_nonzeros_offd++; } } } } /* for each row */ } /* num_paths == 1 */ else { jj_count_diag = num_nonzeros_diag; jj_count_offd = num_nonzeros_offd; for (ic = ic_begin; ic < ic_end; ic++) { /*-------------------------------------------------------------------- * Set marker for diagonal entry, C_{i1,i1} (for square matrices). *--------------------------------------------------------------------*/ HYPRE_Int i1 = coarse_to_fine[ic]; HYPRE_Int jj_row_begin_diag = jj_count_diag; HYPRE_Int jj_row_begin_offd = jj_count_offd; for (jj1 = S_diag_i[i1]; jj1 < S_diag_i[i1+1]; jj1++) { i2 = S_diag_j[jj1]; if (CF_marker[i2] > 0) { index = fine_to_coarse[i2]; if (S_marker[index] < jj_row_begin_diag) { S_marker[index] = jj_count_diag; C_temp_diag_j[jj_count_diag - jj_row_begin_diag] = index; C_temp_diag_data[jj_count_diag - jj_row_begin_diag] = 2; jj_count_diag++; } else { C_temp_diag_data[S_marker[index] - jj_row_begin_diag] += 2; } } for (jj2 = S_diag_i[i2]; jj2 < S_diag_i[i2+1]; jj2++) { i3 = S_diag_j[jj2]; if (CF_marker[i3] > 0 && fine_to_coarse[i3] != ic) { index = fine_to_coarse[i3]; if (S_marker[index] < jj_row_begin_diag) { S_marker[index] = jj_count_diag; C_temp_diag_j[jj_count_diag - jj_row_begin_diag] = index; C_temp_diag_data[jj_count_diag - jj_row_begin_diag] = 1; jj_count_diag++; } else { C_temp_diag_data[S_marker[index] - jj_row_begin_diag]++; } } } for (jj2 = S_offd_i[i2]; jj2 < S_offd_i[i2+1]; jj2++) { i3 = S_offd_j[jj2]; if (CF_marker_offd[i3] > 0) { index = map_S_to_C[i3]; if (S_marker_offd[index] < jj_row_begin_offd) { S_marker_offd[index] = jj_count_offd; C_temp_offd_j[jj_count_offd - jj_row_begin_offd] = index; C_temp_offd_data[jj_count_offd - jj_row_begin_offd] = 1; jj_count_offd++; } else { C_temp_offd_data[S_marker_offd[index] - jj_row_begin_offd]++; } } } } for (jj1 = S_offd_i[i1]; jj1 < S_offd_i[i1+1]; jj1++) { i2 = S_offd_j[jj1]; if (CF_marker_offd[i2] > 0) { index = map_S_to_C[i2]; if (S_marker_offd[index] < jj_row_begin_offd) { S_marker_offd[index] = jj_count_offd; C_temp_offd_j[jj_count_offd - jj_row_begin_offd] = index; C_temp_offd_data[jj_count_offd - jj_row_begin_offd] = 2; jj_count_offd++; } else { C_temp_offd_data[S_marker_offd[index] - jj_row_begin_offd] += 2; } } for (jj2 = S_ext_diag_i[i2]; jj2 < S_ext_diag_i[i2+1]; jj2++) { i3 = S_ext_diag_j[jj2]; if (i3 != ic) { if (S_marker[i3] < jj_row_begin_diag) { S_marker[i3] = jj_count_diag; C_temp_diag_j[jj_count_diag - jj_row_begin_diag] = i3; C_temp_diag_data[jj_count_diag - jj_row_begin_diag] = 1; jj_count_diag++; } else { C_temp_diag_data[S_marker[i3] - jj_row_begin_diag]++; } } } for (jj2 = S_ext_offd_i[i2]; jj2 < S_ext_offd_i[i2+1]; jj2++) { i3 = S_ext_offd_j[jj2]; if (S_marker_offd[i3] < jj_row_begin_offd) { S_marker_offd[i3] = jj_count_offd; C_temp_offd_j[jj_count_offd - jj_row_begin_offd] = i3; C_temp_offd_data[jj_count_offd - jj_row_begin_offd] = 1; jj_count_offd++; } else { C_temp_offd_data[S_marker_offd[i3] - jj_row_begin_offd]++; } } } for (jj1 = jj_row_begin_diag; jj1 < jj_count_diag; jj1++) { if (C_temp_diag_data[jj1 - jj_row_begin_diag] >= num_paths) { C_diag_j[num_nonzeros_diag++] = C_temp_diag_j[jj1 - jj_row_begin_diag]; } C_temp_diag_data[jj1 - jj_row_begin_diag] = 0; } for (jj1 = jj_row_begin_offd; jj1 < jj_count_offd; jj1++) { if (C_temp_offd_data[jj1 - jj_row_begin_offd] >= num_paths) { C_offd_j[num_nonzeros_offd++] = C_temp_offd_j[jj1 - jj_row_begin_offd]; } C_temp_offd_data[jj1 - jj_row_begin_offd] = 0; } } /* for each row */ } /* num_paths > 1 */ } /* omp parallel */ S2 = hypre_ParCSRMatrixCreate(comm, global_num_coarse, global_num_coarse, coarse_row_starts, coarse_row_starts, num_cols_offd_C, C_diag_i[num_coarse], C_offd_i[num_coarse]); hypre_ParCSRMatrixOwnsRowStarts(S2) = 0; C_diag = hypre_ParCSRMatrixDiag(S2); hypre_CSRMatrixI(C_diag) = C_diag_i; if (C_diag_i[num_coarse]) hypre_CSRMatrixJ(C_diag) = C_diag_j; C_offd = hypre_ParCSRMatrixOffd(S2); hypre_CSRMatrixI(C_offd) = C_offd_i; hypre_ParCSRMatrixOffd(S2) = C_offd; if (num_cols_offd_C) { if (C_offd_i[num_coarse]) hypre_CSRMatrixJ(C_offd) = C_offd_j; hypre_ParCSRMatrixColMapOffd(S2) = col_map_offd_C; } /*----------------------------------------------------------------------- * Free various arrays *-----------------------------------------------------------------------*/ hypre_TFree(C_temp_diag_j_array); hypre_TFree(C_temp_diag_data_array); hypre_TFree(C_temp_offd_j_array); hypre_TFree(C_temp_offd_data_array); hypre_TFree(S_marker_array); hypre_TFree(S_marker_offd_array); hypre_TFree(S_marker); hypre_TFree(S_marker_offd); hypre_TFree(S_ext_diag_i); hypre_TFree(fine_to_coarse); hypre_TFree(coarse_to_fine); if (S_ext_diag_size) { hypre_TFree(S_ext_diag_j); } hypre_TFree(S_ext_offd_i); if (S_ext_offd_size) { hypre_TFree(S_ext_offd_j); } if (num_cols_offd_S) { hypre_TFree(map_S_to_C); hypre_TFree(CF_marker_offd); hypre_TFree(fine_to_coarse_offd); } *C_ptr = S2; #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_CREATE_2NDS] += hypre_MPI_Wtime(); #endif hypre_TFree(prefix_sum_workspace); hypre_TFree(num_coarse_prefix_sum); return 0; } /*-------------------------------------------------------------------------- * hypre_BoomerAMGCorrectCFMarker : corrects CF_marker after aggr. coarsening *--------------------------------------------------------------------------*/ HYPRE_Int hypre_BoomerAMGCorrectCFMarker(HYPRE_Int *CF_marker, HYPRE_Int num_var, HYPRE_Int *new_CF_marker) { HYPRE_Int i, cnt; cnt = 0; for (i=0; i < num_var; i++) { if (CF_marker[i] > 0 ) { if (CF_marker[i] == 1) CF_marker[i] = new_CF_marker[cnt++]; else { CF_marker[i] = 1; cnt++;} } } return 0; } /*-------------------------------------------------------------------------- * hypre_BoomerAMGCorrectCFMarker2 : corrects CF_marker after aggr. coarsening, * but marks new F-points (previous C-points) as -2 *--------------------------------------------------------------------------*/ HYPRE_Int hypre_BoomerAMGCorrectCFMarker2(HYPRE_Int *CF_marker, HYPRE_Int num_var, HYPRE_Int *new_CF_marker) { HYPRE_Int i, cnt; cnt = 0; for (i=0; i < num_var; i++) { if (CF_marker[i] > 0 ) { if (new_CF_marker[cnt] == -1) CF_marker[i] = -2; else CF_marker[i] = 1; cnt++; } } return 0; }
82,474
34.18558
138
c
AMG
AMG-master/parcsr_ls/partial.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ #include "_hypre_parcsr_ls.h" #include "aux_interp.h" /*--------------------------------------------------------------------------- * hypre_BoomerAMGBuildPartialExtPIInterp * Comment: *--------------------------------------------------------------------------*/ HYPRE_Int hypre_BoomerAMGBuildPartialExtPIInterp(hypre_ParCSRMatrix *A, HYPRE_Int *CF_marker, hypre_ParCSRMatrix *S, HYPRE_Int *num_cpts_global, HYPRE_Int *num_old_cpts_global, HYPRE_Int num_functions, HYPRE_Int *dof_func, HYPRE_Int debug_flag, HYPRE_Real trunc_factor, HYPRE_Int max_elmts, HYPRE_Int *col_offd_S_to_A, hypre_ParCSRMatrix **P_ptr) { #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_PARTIAL_INTERP] -= hypre_MPI_Wtime(); #endif /* Communication Variables */ MPI_Comm comm = hypre_ParCSRMatrixComm(A); hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A); HYPRE_Int my_id, num_procs; /* Variables to store input variables */ hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); HYPRE_Real *A_diag_data = hypre_CSRMatrixData(A_diag); HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag); HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag); hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); HYPRE_Real *A_offd_data = hypre_CSRMatrixData(A_offd); HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd); HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd); /*HYPRE_Int num_cols_A_offd = hypre_CSRMatrixNumCols(A_offd); HYPRE_Int *col_map_offd = hypre_ParCSRMatrixColMapOffd(A);*/ HYPRE_Int n_fine = hypre_CSRMatrixNumRows(A_diag); HYPRE_Int col_1 = hypre_ParCSRMatrixFirstRowIndex(A); HYPRE_Int local_numrows = hypre_CSRMatrixNumRows(A_diag); HYPRE_Int col_n = col_1 + local_numrows; HYPRE_Int total_global_cpts, my_first_cpt; /* Variables to store strong connection matrix info */ hypre_CSRMatrix *S_diag = hypre_ParCSRMatrixDiag(S); HYPRE_Int *S_diag_i = hypre_CSRMatrixI(S_diag); HYPRE_Int *S_diag_j = hypre_CSRMatrixJ(S_diag); hypre_CSRMatrix *S_offd = hypre_ParCSRMatrixOffd(S); HYPRE_Int *S_offd_i = hypre_CSRMatrixI(S_offd); HYPRE_Int *S_offd_j = hypre_CSRMatrixJ(S_offd); /* Interpolation matrix P */ hypre_ParCSRMatrix *P; hypre_CSRMatrix *P_diag; hypre_CSRMatrix *P_offd; HYPRE_Real *P_diag_data = NULL; HYPRE_Int *P_diag_i, *P_diag_j = NULL; HYPRE_Real *P_offd_data = NULL; HYPRE_Int *P_offd_i, *P_offd_j = NULL; /*HYPRE_Int *col_map_offd_P = NULL;*/ HYPRE_Int P_diag_size; HYPRE_Int P_offd_size; /*HYPRE_Int *P_marker = NULL; HYPRE_Int *P_marker_offd = NULL;*/ HYPRE_Int *CF_marker_offd = NULL; HYPRE_Int *tmp_CF_marker_offd = NULL; HYPRE_Int *dof_func_offd = NULL; /* Full row information for columns of A that are off diag*/ hypre_CSRMatrix *A_ext; HYPRE_Real *A_ext_data; HYPRE_Int *A_ext_i; HYPRE_Int *A_ext_j; HYPRE_Int *fine_to_coarse = NULL; HYPRE_Int *fine_to_coarse_offd = NULL; HYPRE_Int *old_coarse_to_fine = NULL; HYPRE_Int full_off_procNodes; hypre_CSRMatrix *Sop; HYPRE_Int *Sop_i; HYPRE_Int *Sop_j; HYPRE_Int sgn; /* Variables to keep count of interpolatory points */ /*HYPRE_Int jj_counter, jj_counter_offd; HYPRE_Int jj_begin_row, jj_end_row; HYPRE_Int jj_begin_row_offd = 0; HYPRE_Int jj_end_row_offd = 0; HYPRE_Int coarse_counter, coarse_counter_offd; */ HYPRE_Int n_coarse_old; HYPRE_Int total_old_global_cpts; /* Interpolation weight variables */ HYPRE_Real sum, diagonal, distribute; /*HYPRE_Int strong_f_marker = -2;*/ /* Loop variables */ /*HYPRE_Int index;*/ HYPRE_Int cnt, old_cnt; HYPRE_Int start_indexing = 0; HYPRE_Int i; /*HYPRE_Int i, ii, i1, i2, j, jj, kk, k1, jj1;*/ /* Definitions */ HYPRE_Real zero = 0.0; HYPRE_Real one = 1.0; HYPRE_Real wall_time; HYPRE_Int max_num_threads; HYPRE_Int *P_diag_array = NULL; HYPRE_Int *P_offd_array = NULL; hypre_ParCSRCommPkg *extend_comm_pkg = NULL; if (debug_flag==4) wall_time = time_getWallclockSeconds(); /* BEGIN */ hypre_MPI_Comm_size(comm, &num_procs); hypre_MPI_Comm_rank(comm,&my_id); max_num_threads = hypre_NumThreads(); #ifdef HYPRE_NO_GLOBAL_PARTITION my_first_cpt = num_cpts_global[0]; /*my_first_old_cpt = num_old_cpts_global[0];*/ n_coarse_old = num_old_cpts_global[1] - num_old_cpts_global[0]; /*n_coarse = num_cpts_global[1] - num_cpts_global[0];*/ if (my_id == (num_procs -1)) { total_global_cpts = num_cpts_global[1]; total_old_global_cpts = num_old_cpts_global[1]; } hypre_MPI_Bcast(&total_global_cpts, 1, HYPRE_MPI_INT, num_procs-1, comm); hypre_MPI_Bcast(&total_old_global_cpts, 1, HYPRE_MPI_INT, num_procs-1, comm); #else my_first_cpt = num_cpts_global[my_id]; /*my_first_old_cpt = num_old_cpts_global[my_id];*/ total_global_cpts = num_cpts_global[num_procs]; total_old_global_cpts = num_old_cpts_global[num_procs]; n_coarse_old = num_old_cpts_global[my_id+1] - num_old_cpts_global[my_id]; /*n_coarse = num_cpts_global[my_id+1] - num_cpts_global[my_id];*/ #endif if (!comm_pkg) { hypre_MatvecCommPkgCreate(A); comm_pkg = hypre_ParCSRMatrixCommPkg(A); } /* Set up off processor information (specifically for neighbors of * neighbors */ full_off_procNodes = 0; if (num_procs > 1) { if (hypre_exchange_interp_data( &CF_marker_offd, &dof_func_offd, &A_ext, &full_off_procNodes, &Sop, &extend_comm_pkg, A, CF_marker, S, num_functions, dof_func, 1)) { #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_EXTENDED_I_INTERP] += hypre_MPI_Wtime(); #endif return hypre_error_flag; } A_ext_i = hypre_CSRMatrixI(A_ext); A_ext_j = hypre_CSRMatrixJ(A_ext); A_ext_data = hypre_CSRMatrixData(A_ext); Sop_i = hypre_CSRMatrixI(Sop); Sop_j = hypre_CSRMatrixJ(Sop); } /*----------------------------------------------------------------------- * First Pass: Determine size of P and fill in fine_to_coarse mapping. *-----------------------------------------------------------------------*/ /*----------------------------------------------------------------------- * Intialize counters and allocate mapping vector. *-----------------------------------------------------------------------*/ P_diag_i = hypre_CTAlloc(HYPRE_Int, n_coarse_old+1); P_offd_i = hypre_CTAlloc(HYPRE_Int, n_coarse_old+1); if (n_fine) { old_coarse_to_fine = hypre_CTAlloc(HYPRE_Int, n_coarse_old); fine_to_coarse = hypre_CTAlloc(HYPRE_Int, n_fine); /*P_marker = hypre_CTAlloc(HYPRE_Int, n_fine); */ } if (full_off_procNodes) { /*P_marker_offd = hypre_CTAlloc(HYPRE_Int, full_off_procNodes);*/ fine_to_coarse_offd = hypre_CTAlloc(HYPRE_Int, full_off_procNodes); tmp_CF_marker_offd = hypre_CTAlloc(HYPRE_Int, full_off_procNodes); } /*hypre_initialize_vecs(n_fine, full_off_procNodes, fine_to_coarse, fine_to_coarse_offd, P_marker, P_marker_offd, tmp_CF_marker_offd);*/ for (i=0; i < full_off_procNodes; i++) { fine_to_coarse_offd[i] = -1; tmp_CF_marker_offd[i] = -1; } cnt = 0; old_cnt = 0; for (i = 0; i < n_fine; i++) { fine_to_coarse[i] = -1; if (CF_marker[i] == 1) { fine_to_coarse[i] = cnt++; old_coarse_to_fine[old_cnt++] = i; } else if (CF_marker[i] == -2) { old_coarse_to_fine[old_cnt++] = i; } } P_diag_array = hypre_CTAlloc(HYPRE_Int, max_num_threads+1); P_offd_array = hypre_CTAlloc(HYPRE_Int, max_num_threads+1); /*----------------------------------------------------------------------- * Loop over fine grid. *-----------------------------------------------------------------------*/ #ifdef HYPRE_USING_OPENMP #pragma omp parallel private(i, diagonal, distribute, sgn, sum) #endif { HYPRE_Int ii, jj_counter, jj_counter_offd, jj, kk, i1, i2, k1, jj1; HYPRE_Int loc_col, jj_begin_row, jj_begin_row_offd; HYPRE_Int jj_end_row, jj_end_row_offd, strong_f_marker; HYPRE_Int size, rest, ne, ns; HYPRE_Int num_threads, my_thread_num; HYPRE_Int *P_marker = NULL; HYPRE_Int *P_marker_offd = NULL; strong_f_marker = -2; num_threads = hypre_NumActiveThreads(); my_thread_num = hypre_GetThreadNum(); size = n_coarse_old/num_threads; rest = n_coarse_old - size*num_threads; if (my_thread_num < rest) { ns = my_thread_num*(size+1); ne = (my_thread_num+1)*(size+1); } else { ns = my_thread_num*size+rest; ne = (my_thread_num+1)*size+rest; } if (n_fine) P_marker = hypre_CTAlloc(HYPRE_Int, n_fine); for (ii=0; ii < n_fine; ii++) P_marker[ii] = -1; if (full_off_procNodes) P_marker_offd = hypre_CTAlloc(HYPRE_Int, full_off_procNodes); for (ii=0; ii < full_off_procNodes; ii++) P_marker_offd[ii] = -1; /*coarse_counter = 0; coarse_counter_offd = 0;*/ jj_counter = start_indexing; jj_counter_offd = start_indexing; for (ii = ns; ii < ne; ii++) { jj_begin_row = jj_counter; jj_begin_row_offd = jj_counter_offd; /*P_diag_i[ii] = jj_counter; if (num_procs > 1) P_offd_i[ii] = jj_counter_offd;*/ i = old_coarse_to_fine[ii]; if (CF_marker[i] > 0) { jj_counter++; /*coarse_counter++;*/ } /*-------------------------------------------------------------------- * If i is an F-point, interpolation is from the C-points that * strongly influence i, or C-points that stronly influence F-points * that strongly influence i. *--------------------------------------------------------------------*/ else if (CF_marker[i] == -2) { for (jj = S_diag_i[i]; jj < S_diag_i[i+1]; jj++) { i1 = S_diag_j[jj]; if (CF_marker[i1] > 0) { /* i1 is a C point */ if (P_marker[i1] < jj_begin_row) { P_marker[i1] = jj_counter; jj_counter++; } } else if (CF_marker[i1] != -3) { /* i1 is a F point, loop through it's strong neighbors */ for (kk = S_diag_i[i1]; kk < S_diag_i[i1+1]; kk++) { k1 = S_diag_j[kk]; if (CF_marker[k1] > 0) { if(P_marker[k1] < jj_begin_row) { P_marker[k1] = jj_counter; jj_counter++; } } } if(num_procs > 1) { for (kk = S_offd_i[i1]; kk < S_offd_i[i1+1]; kk++) { if(col_offd_S_to_A) k1 = col_offd_S_to_A[S_offd_j[kk]]; else k1 = S_offd_j[kk]; if (CF_marker_offd[k1] > 0) { if(P_marker_offd[k1] < jj_begin_row_offd) { tmp_CF_marker_offd[k1] = 1; P_marker_offd[k1] = jj_counter_offd; jj_counter_offd++; } } } } } } /* Look at off diag strong connections of i */ if (num_procs > 1) { for (jj = S_offd_i[i]; jj < S_offd_i[i+1]; jj++) { i1 = S_offd_j[jj]; if(col_offd_S_to_A) i1 = col_offd_S_to_A[i1]; if (CF_marker_offd[i1] > 0) { if(P_marker_offd[i1] < jj_begin_row_offd) { tmp_CF_marker_offd[i1] = 1; P_marker_offd[i1] = jj_counter_offd; jj_counter_offd++; } } else if (CF_marker_offd[i1] != -3) { /* F point; look at neighbors of i1. Sop contains global col * numbers and entries that could be in S_diag or S_offd or * neither. */ for(kk = Sop_i[i1]; kk < Sop_i[i1+1]; kk++) { k1 = Sop_j[kk]; if(k1 >= col_1 && k1 < col_n) { /* In S_diag */ loc_col = k1-col_1; if(P_marker[loc_col] < jj_begin_row) { P_marker[loc_col] = jj_counter; jj_counter++; } } else { loc_col = -k1 - 1; if(P_marker_offd[loc_col] < jj_begin_row_offd) { P_marker_offd[loc_col] = jj_counter_offd; tmp_CF_marker_offd[loc_col] = 1; jj_counter_offd++; } } } } } } } P_diag_array[my_thread_num] = jj_counter; P_offd_array[my_thread_num] = jj_counter_offd; } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif if (my_thread_num == 0) { if (debug_flag==4) { wall_time = time_getWallclockSeconds() - wall_time; hypre_printf("Proc = %d determine structure %f\n", my_id, wall_time); fflush(NULL); } /*----------------------------------------------------------------------- * Allocate arrays. *-----------------------------------------------------------------------*/ if (debug_flag== 4) wall_time = time_getWallclockSeconds(); for (i=0; i < max_num_threads; i++) { P_diag_array[i+1] += P_diag_array[i]; P_offd_array[i+1] += P_offd_array[i]; } P_diag_size = P_diag_array[max_num_threads]; P_offd_size = P_offd_array[max_num_threads]; if (P_diag_size) { P_diag_j = hypre_CTAlloc(HYPRE_Int, P_diag_size); P_diag_data = hypre_CTAlloc(HYPRE_Real, P_diag_size); } if (P_offd_size) { P_offd_j = hypre_CTAlloc(HYPRE_Int, P_offd_size); P_offd_data = hypre_CTAlloc(HYPRE_Real, P_offd_size); } P_diag_i[n_coarse_old] = P_diag_size; P_offd_i[n_coarse_old] = P_offd_size; /* Fine to coarse mapping */ if(num_procs > 1) { for (i = 0; i < n_fine; i++) fine_to_coarse[i] += my_first_cpt; hypre_alt_insert_new_nodes(comm_pkg, extend_comm_pkg, fine_to_coarse, full_off_procNodes, fine_to_coarse_offd); for (i = 0; i < n_fine; i++) fine_to_coarse[i] -= my_first_cpt; } } for (i = 0; i < n_fine; i++) P_marker[i] = -1; for (i = 0; i < full_off_procNodes; i++) P_marker_offd[i] = -1; #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif jj_counter = start_indexing; jj_counter_offd = start_indexing; if (my_thread_num) { jj_counter = P_diag_array[my_thread_num-1]; jj_counter_offd = P_offd_array[my_thread_num-1]; } /*----------------------------------------------------------------------- * Loop over fine grid points. *-----------------------------------------------------------------------*/ for (ii = ns; ii < ne; ii++) { jj_begin_row = jj_counter; jj_begin_row_offd = jj_counter_offd; P_diag_i[ii] = jj_counter; P_offd_i[ii] = jj_counter_offd; i = old_coarse_to_fine[ii]; /*-------------------------------------------------------------------- * If i is a c-point, interpolation is the identity. *--------------------------------------------------------------------*/ if (CF_marker[i] > 0) { P_diag_j[jj_counter] = fine_to_coarse[i]; P_diag_data[jj_counter] = one; jj_counter++; } /*-------------------------------------------------------------------- * If i is an F-point, build interpolation. *--------------------------------------------------------------------*/ else if (CF_marker[i] == -2) { strong_f_marker--; for (jj = S_diag_i[i]; jj < S_diag_i[i+1]; jj++) { i1 = S_diag_j[jj]; /*-------------------------------------------------------------- * If neighbor i1 is a C-point, set column number in P_diag_j * and initialize interpolation weight to zero. *--------------------------------------------------------------*/ if (CF_marker[i1] >= 0) { if (P_marker[i1] < jj_begin_row) { P_marker[i1] = jj_counter; P_diag_j[jj_counter] = fine_to_coarse[i1]; P_diag_data[jj_counter] = zero; jj_counter++; } } else if (CF_marker[i1] != -3) { P_marker[i1] = strong_f_marker; for (kk = S_diag_i[i1]; kk < S_diag_i[i1+1]; kk++) { k1 = S_diag_j[kk]; if (CF_marker[k1] >= 0) { if(P_marker[k1] < jj_begin_row) { P_marker[k1] = jj_counter; P_diag_j[jj_counter] = fine_to_coarse[k1]; P_diag_data[jj_counter] = zero; jj_counter++; } } } if(num_procs > 1) { for (kk = S_offd_i[i1]; kk < S_offd_i[i1+1]; kk++) { if(col_offd_S_to_A) k1 = col_offd_S_to_A[S_offd_j[kk]]; else k1 = S_offd_j[kk]; if(CF_marker_offd[k1] >= 0) { if(P_marker_offd[k1] < jj_begin_row_offd) { P_marker_offd[k1] = jj_counter_offd; P_offd_j[jj_counter_offd] = k1; P_offd_data[jj_counter_offd] = zero; jj_counter_offd++; } } } } } } if ( num_procs > 1) { for (jj=S_offd_i[i]; jj < S_offd_i[i+1]; jj++) { i1 = S_offd_j[jj]; if(col_offd_S_to_A) i1 = col_offd_S_to_A[i1]; if ( CF_marker_offd[i1] >= 0) { if(P_marker_offd[i1] < jj_begin_row_offd) { P_marker_offd[i1] = jj_counter_offd; P_offd_j[jj_counter_offd] = i1; P_offd_data[jj_counter_offd] = zero; jj_counter_offd++; } } else if (CF_marker_offd[i1] != -3) { P_marker_offd[i1] = strong_f_marker; for(kk = Sop_i[i1]; kk < Sop_i[i1+1]; kk++) { k1 = Sop_j[kk]; /* Find local col number */ if(k1 >= col_1 && k1 < col_n) { loc_col = k1-col_1; if(P_marker[loc_col] < jj_begin_row) { P_marker[loc_col] = jj_counter; P_diag_j[jj_counter] = fine_to_coarse[loc_col]; P_diag_data[jj_counter] = zero; jj_counter++; } } else { loc_col = -k1 - 1; if(P_marker_offd[loc_col] < jj_begin_row_offd) { P_marker_offd[loc_col] = jj_counter_offd; P_offd_j[jj_counter_offd]=loc_col; P_offd_data[jj_counter_offd] = zero; jj_counter_offd++; } } } } } } jj_end_row = jj_counter; jj_end_row_offd = jj_counter_offd; diagonal = A_diag_data[A_diag_i[i]]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { /* i1 is a c-point and strongly influences i, accumulate * a_(i,i1) into interpolation weight */ i1 = A_diag_j[jj]; if (P_marker[i1] >= jj_begin_row) { P_diag_data[P_marker[i1]] += A_diag_data[jj]; } else if(P_marker[i1] == strong_f_marker) { sum = zero; sgn = 1; if(A_diag_data[A_diag_i[i1]] < 0) sgn = -1; /* Loop over row of A for point i1 and calculate the sum * of the connections to c-points that strongly incluence i. */ for(jj1 = A_diag_i[i1]+1; jj1 < A_diag_i[i1+1]; jj1++) { i2 = A_diag_j[jj1]; if((P_marker[i2] >= jj_begin_row || i2 == i) && (sgn*A_diag_data[jj1]) < 0) sum += A_diag_data[jj1]; } if(num_procs > 1) { for(jj1 = A_offd_i[i1]; jj1< A_offd_i[i1+1]; jj1++) { i2 = A_offd_j[jj1]; if(P_marker_offd[i2] >= jj_begin_row_offd && (sgn*A_offd_data[jj1]) < 0) sum += A_offd_data[jj1]; } } if(sum != 0) { distribute = A_diag_data[jj]/sum; /* Loop over row of A for point i1 and do the distribution */ for(jj1 = A_diag_i[i1]+1; jj1 < A_diag_i[i1+1]; jj1++) { i2 = A_diag_j[jj1]; if(P_marker[i2] >= jj_begin_row && (sgn*A_diag_data[jj1]) < 0) P_diag_data[P_marker[i2]] += distribute*A_diag_data[jj1]; if(i2 == i && (sgn*A_diag_data[jj1]) < 0) diagonal += distribute*A_diag_data[jj1]; } if(num_procs > 1) { for(jj1 = A_offd_i[i1]; jj1 < A_offd_i[i1+1]; jj1++) { i2 = A_offd_j[jj1]; if(P_marker_offd[i2] >= jj_begin_row_offd && (sgn*A_offd_data[jj1]) < 0) P_offd_data[P_marker_offd[i2]] += distribute*A_offd_data[jj1]; } } } else { diagonal += A_diag_data[jj]; } } /* neighbor i1 weakly influences i, accumulate a_(i,i1) into * diagonal */ else if (CF_marker[i1] != -3) { if(num_functions == 1 || dof_func[i] == dof_func[i1]) diagonal += A_diag_data[jj]; } } if(num_procs > 1) { for(jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { i1 = A_offd_j[jj]; if(P_marker_offd[i1] >= jj_begin_row_offd) P_offd_data[P_marker_offd[i1]] += A_offd_data[jj]; else if(P_marker_offd[i1] == strong_f_marker) { sum = zero; for(jj1 = A_ext_i[i1]; jj1 < A_ext_i[i1+1]; jj1++) { k1 = A_ext_j[jj1]; if(k1 >= col_1 && k1 < col_n) { /* diag */ loc_col = k1 - col_1; if(P_marker[loc_col] >= jj_begin_row || loc_col == i) sum += A_ext_data[jj1]; } else { loc_col = -k1 - 1; if(P_marker_offd[loc_col] >= jj_begin_row_offd) sum += A_ext_data[jj1]; } } if(sum != 0) { distribute = A_offd_data[jj] / sum; for(jj1 = A_ext_i[i1]; jj1 < A_ext_i[i1+1]; jj1++) { k1 = A_ext_j[jj1]; if(k1 >= col_1 && k1 < col_n) { /* diag */ loc_col = k1 - col_1; if(P_marker[loc_col] >= jj_begin_row) P_diag_data[P_marker[loc_col]] += distribute* A_ext_data[jj1]; if(loc_col == i) diagonal += distribute*A_ext_data[jj1]; } else { loc_col = -k1 - 1; if(P_marker_offd[loc_col] >= jj_begin_row_offd) P_offd_data[P_marker_offd[loc_col]] += distribute* A_ext_data[jj1]; } } } else { diagonal += A_offd_data[jj]; } } else if (CF_marker_offd[i1] != -3) { if(num_functions == 1 || dof_func[i] == dof_func_offd[i1]) diagonal += A_offd_data[jj]; } } } if (diagonal) { for(jj = jj_begin_row; jj < jj_end_row; jj++) P_diag_data[jj] /= -diagonal; for(jj = jj_begin_row_offd; jj < jj_end_row_offd; jj++) P_offd_data[jj] /= -diagonal; } } strong_f_marker--; } hypre_TFree(P_marker); hypre_TFree(P_marker_offd); } /* end parallel region */ if (debug_flag==4) { wall_time = time_getWallclockSeconds() - wall_time; hypre_printf("Proc = %d fill structure %f\n", my_id, wall_time); fflush(NULL); } /*----------------------------------------------------------------------- * Allocate arrays. *-----------------------------------------------------------------------*/ P = hypre_ParCSRMatrixCreate(comm, total_old_global_cpts, total_global_cpts, num_old_cpts_global, num_cpts_global, 0, P_diag_i[n_coarse_old], P_offd_i[n_coarse_old]); P_diag = hypre_ParCSRMatrixDiag(P); hypre_CSRMatrixData(P_diag) = P_diag_data; hypre_CSRMatrixI(P_diag) = P_diag_i; hypre_CSRMatrixJ(P_diag) = P_diag_j; P_offd = hypre_ParCSRMatrixOffd(P); hypre_CSRMatrixData(P_offd) = P_offd_data; hypre_CSRMatrixI(P_offd) = P_offd_i; hypre_CSRMatrixJ(P_offd) = P_offd_j; hypre_ParCSRMatrixOwnsRowStarts(P) = 0; /* Compress P, removing coefficients smaller than trunc_factor * Max */ if (trunc_factor != 0.0 || max_elmts > 0) { hypre_BoomerAMGInterpTruncation(P, trunc_factor, max_elmts); P_diag_data = hypre_CSRMatrixData(P_diag); P_diag_i = hypre_CSRMatrixI(P_diag); P_diag_j = hypre_CSRMatrixJ(P_diag); P_offd_data = hypre_CSRMatrixData(P_offd); P_offd_i = hypre_CSRMatrixI(P_offd); P_offd_j = hypre_CSRMatrixJ(P_offd); P_diag_size = P_diag_i[n_coarse_old]; P_offd_size = P_offd_i[n_coarse_old]; } /* This builds col_map, col_map should be monotone increasing and contain * global numbers. */ if(P_offd_size) { hypre_build_interp_colmap(P, full_off_procNodes, tmp_CF_marker_offd, fine_to_coarse_offd); } hypre_MatvecCommPkgCreate(P); for (i=0; i < n_fine; i++) if (CF_marker[i] < -1) CF_marker[i] = -1; *P_ptr = P; /* Deallocate memory */ hypre_TFree(fine_to_coarse); hypre_TFree(old_coarse_to_fine); hypre_TFree(P_diag_array); hypre_TFree(P_offd_array); if (num_procs > 1) { hypre_CSRMatrixDestroy(Sop); hypre_CSRMatrixDestroy(A_ext); hypre_TFree(fine_to_coarse_offd); hypre_TFree(CF_marker_offd); hypre_TFree(tmp_CF_marker_offd); if(num_functions > 1) hypre_TFree(dof_func_offd); hypre_MatvecCommPkgDestroy(extend_comm_pkg); } #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_PARTIAL_INTERP] += hypre_MPI_Wtime(); #endif return hypre_error_flag; } /*--------------------------------------------------------------------------- * hypre_BoomerAMGBuildPartialStdInterp * Comment: The interpolatory weighting can be changed with the sep_weight * variable. This can enable not separating negative and positive * off diagonals in the weight formula. *--------------------------------------------------------------------------*/ HYPRE_Int hypre_BoomerAMGBuildPartialStdInterp(hypre_ParCSRMatrix *A, HYPRE_Int *CF_marker, hypre_ParCSRMatrix *S, HYPRE_Int *num_cpts_global, HYPRE_Int *num_old_cpts_global, HYPRE_Int num_functions, HYPRE_Int *dof_func, HYPRE_Int debug_flag, HYPRE_Real trunc_factor, HYPRE_Int max_elmts, HYPRE_Int sep_weight, HYPRE_Int *col_offd_S_to_A, hypre_ParCSRMatrix **P_ptr) { /* Communication Variables */ MPI_Comm comm = hypre_ParCSRMatrixComm(A); hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A); HYPRE_Int my_id, num_procs; /* Variables to store input variables */ hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); HYPRE_Real *A_diag_data = hypre_CSRMatrixData(A_diag); HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag); HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag); hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); HYPRE_Real *A_offd_data = hypre_CSRMatrixData(A_offd); HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd); HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd); /*HYPRE_Int num_cols_A_offd = hypre_CSRMatrixNumCols(A_offd); HYPRE_Int *col_map_offd = hypre_ParCSRMatrixColMapOffd(A);*/ HYPRE_Int n_fine = hypre_CSRMatrixNumRows(A_diag); HYPRE_Int col_1 = hypre_ParCSRMatrixFirstRowIndex(A); HYPRE_Int local_numrows = hypre_CSRMatrixNumRows(A_diag); HYPRE_Int col_n = col_1 + local_numrows; HYPRE_Int total_global_cpts, my_first_cpt; /* Variables to store strong connection matrix info */ hypre_CSRMatrix *S_diag = hypre_ParCSRMatrixDiag(S); HYPRE_Int *S_diag_i = hypre_CSRMatrixI(S_diag); HYPRE_Int *S_diag_j = hypre_CSRMatrixJ(S_diag); hypre_CSRMatrix *S_offd = hypre_ParCSRMatrixOffd(S); HYPRE_Int *S_offd_i = hypre_CSRMatrixI(S_offd); HYPRE_Int *S_offd_j = hypre_CSRMatrixJ(S_offd); /* Interpolation matrix P */ hypre_ParCSRMatrix *P; hypre_CSRMatrix *P_diag; hypre_CSRMatrix *P_offd; HYPRE_Real *P_diag_data = NULL; HYPRE_Int *P_diag_i, *P_diag_j = NULL; HYPRE_Real *P_offd_data = NULL; HYPRE_Int *P_offd_i, *P_offd_j = NULL; /*HYPRE_Int *col_map_offd_P = NULL;*/ HYPRE_Int P_diag_size; HYPRE_Int P_offd_size; HYPRE_Int *P_marker = NULL; HYPRE_Int *P_marker_offd = NULL; HYPRE_Int *CF_marker_offd = NULL; HYPRE_Int *tmp_CF_marker_offd = NULL; HYPRE_Int *dof_func_offd = NULL; /* Full row information for columns of A that are off diag*/ hypre_CSRMatrix *A_ext; HYPRE_Real *A_ext_data; HYPRE_Int *A_ext_i; HYPRE_Int *A_ext_j; HYPRE_Int *fine_to_coarse = NULL; HYPRE_Int *fine_to_coarse_offd = NULL; HYPRE_Int *old_coarse_to_fine = NULL; HYPRE_Int loc_col; HYPRE_Int full_off_procNodes; hypre_CSRMatrix *Sop; HYPRE_Int *Sop_i; HYPRE_Int *Sop_j; /* Variables to keep count of interpolatory points */ HYPRE_Int jj_counter, jj_counter_offd; HYPRE_Int jj_begin_row, jj_end_row; HYPRE_Int jj_begin_row_offd = 0; HYPRE_Int jj_end_row_offd = 0; HYPRE_Int coarse_counter; HYPRE_Int n_coarse_old; HYPRE_Int total_old_global_cpts; HYPRE_Int *ihat = NULL; HYPRE_Int *ihat_offd = NULL; HYPRE_Int *ipnt = NULL; HYPRE_Int *ipnt_offd = NULL; HYPRE_Int strong_f_marker = -2; /* Interpolation weight variables */ HYPRE_Real *ahat = NULL; HYPRE_Real *ahat_offd = NULL; HYPRE_Real sum_pos, sum_pos_C, sum_neg, sum_neg_C, sum, sum_C; HYPRE_Real diagonal, distribute; HYPRE_Real alfa, beta; /* Loop variables */ /*HYPRE_Int index;*/ HYPRE_Int cnt, old_cnt; HYPRE_Int start_indexing = 0; HYPRE_Int i, ii, i1, j1, jj, kk, k1; HYPRE_Int cnt_c, cnt_f, cnt_c_offd, cnt_f_offd, indx; /* Definitions */ HYPRE_Real zero = 0.0; HYPRE_Real one = 1.0; HYPRE_Real wall_time; HYPRE_Real wall_1 = 0; HYPRE_Real wall_2 = 0; HYPRE_Real wall_3 = 0; hypre_ParCSRCommPkg *extend_comm_pkg = NULL; if (debug_flag== 4) wall_time = time_getWallclockSeconds(); /* BEGIN */ hypre_MPI_Comm_size(comm, &num_procs); hypre_MPI_Comm_rank(comm,&my_id); #ifdef HYPRE_NO_GLOBAL_PARTITION my_first_cpt = num_cpts_global[0]; /*my_first_old_cpt = num_old_cpts_global[0];*/ n_coarse_old = num_old_cpts_global[1] - num_old_cpts_global[0]; /*n_coarse = num_cpts_global[1] - num_cpts_global[0];*/ if (my_id == (num_procs -1)) { total_global_cpts = num_cpts_global[1]; total_old_global_cpts = num_old_cpts_global[1]; } hypre_MPI_Bcast(&total_global_cpts, 1, HYPRE_MPI_INT, num_procs-1, comm); hypre_MPI_Bcast(&total_old_global_cpts, 1, HYPRE_MPI_INT, num_procs-1, comm); #else my_first_cpt = num_cpts_global[my_id]; /*my_first_old_cpt = num_old_cpts_global[my_id];*/ total_global_cpts = num_cpts_global[num_procs]; total_old_global_cpts = num_old_cpts_global[num_procs]; n_coarse_old = num_old_cpts_global[my_id+1] - num_old_cpts_global[my_id]; /*n_coarse = num_cpts_global[my_id+1] - num_cpts_global[my_id];*/ #endif if (!comm_pkg) { hypre_MatvecCommPkgCreate(A); comm_pkg = hypre_ParCSRMatrixCommPkg(A); } /* Set up off processor information (specifically for neighbors of * neighbors */ full_off_procNodes = 0; if (num_procs > 1) { if (hypre_exchange_interp_data( &CF_marker_offd, &dof_func_offd, &A_ext, &full_off_procNodes, &Sop, &extend_comm_pkg, A, CF_marker, S, num_functions, dof_func, 0)) { #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_EXTENDED_I_INTERP] += hypre_MPI_Wtime(); #endif return hypre_error_flag; } A_ext_i = hypre_CSRMatrixI(A_ext); A_ext_j = hypre_CSRMatrixJ(A_ext); A_ext_data = hypre_CSRMatrixData(A_ext); Sop_i = hypre_CSRMatrixI(Sop); Sop_j = hypre_CSRMatrixJ(Sop); } /*----------------------------------------------------------------------- * First Pass: Determine size of P and fill in fine_to_coarse mapping. *-----------------------------------------------------------------------*/ /*----------------------------------------------------------------------- * Intialize counters and allocate mapping vector. *-----------------------------------------------------------------------*/ P_diag_i = hypre_CTAlloc(HYPRE_Int, n_coarse_old+1); P_offd_i = hypre_CTAlloc(HYPRE_Int, n_coarse_old+1); if (n_fine) { old_coarse_to_fine = hypre_CTAlloc(HYPRE_Int, n_coarse_old); fine_to_coarse = hypre_CTAlloc(HYPRE_Int, n_fine); P_marker = hypre_CTAlloc(HYPRE_Int, n_fine); } if (full_off_procNodes) { P_marker_offd = hypre_CTAlloc(HYPRE_Int, full_off_procNodes); fine_to_coarse_offd = hypre_CTAlloc(HYPRE_Int, full_off_procNodes); tmp_CF_marker_offd = hypre_CTAlloc(HYPRE_Int, full_off_procNodes); } hypre_initialize_vecs(n_fine, full_off_procNodes, fine_to_coarse, fine_to_coarse_offd, P_marker, P_marker_offd, tmp_CF_marker_offd); jj_counter = start_indexing; jj_counter_offd = start_indexing; coarse_counter = 0; cnt = 0; old_cnt = 0; for (i = 0; i < n_fine; i++) { fine_to_coarse[i] = -1; if (CF_marker[i] == 1) { fine_to_coarse[i] = cnt++; old_coarse_to_fine[old_cnt++] = i; } else if (CF_marker[i] == -2) { old_coarse_to_fine[old_cnt++] = i; } } /*----------------------------------------------------------------------- * Loop over fine grid. *-----------------------------------------------------------------------*/ for (ii = 0; ii < n_coarse_old; ii++) { P_diag_i[ii] = jj_counter; if (num_procs > 1) P_offd_i[ii] = jj_counter_offd; i = old_coarse_to_fine[ii]; if (CF_marker[i] > 0) { jj_counter++; coarse_counter++; } /*-------------------------------------------------------------------- * If i is an F-point, interpolation is from the C-points that * strongly influence i, or C-points that stronly influence F-points * that strongly influence i. *--------------------------------------------------------------------*/ else if (CF_marker[i] == -2) { for (jj = S_diag_i[i]; jj < S_diag_i[i+1]; jj++) { i1 = S_diag_j[jj]; if (CF_marker[i1] > 0) { /* i1 is a C point */ if (P_marker[i1] < P_diag_i[ii]) { P_marker[i1] = jj_counter; jj_counter++; } } else if (CF_marker[i1] != -3) { /* i1 is a F point, loop through it's strong neighbors */ for (kk = S_diag_i[i1]; kk < S_diag_i[i1+1]; kk++) { k1 = S_diag_j[kk]; if (CF_marker[k1] > 0) { if(P_marker[k1] < P_diag_i[ii]) { P_marker[k1] = jj_counter; jj_counter++; } } } if(num_procs > 1) { for (kk = S_offd_i[i1]; kk < S_offd_i[i1+1]; kk++) { if(col_offd_S_to_A) k1 = col_offd_S_to_A[S_offd_j[kk]]; else k1 = S_offd_j[kk]; if (CF_marker_offd[k1] > 0) { if(P_marker_offd[k1] < P_offd_i[ii]) { tmp_CF_marker_offd[k1] = 1; P_marker_offd[k1] = jj_counter_offd; jj_counter_offd++; } } } } } } /* Look at off diag strong connections of i */ if (num_procs > 1) { for (jj = S_offd_i[i]; jj < S_offd_i[i+1]; jj++) { i1 = S_offd_j[jj]; if(col_offd_S_to_A) i1 = col_offd_S_to_A[i1]; if (CF_marker_offd[i1] > 0) { if(P_marker_offd[i1] < P_offd_i[ii]) { tmp_CF_marker_offd[i1] = 1; P_marker_offd[i1] = jj_counter_offd; jj_counter_offd++; } } else if (CF_marker_offd[i1] != -3) { /* F point; look at neighbors of i1. Sop contains global col * numbers and entries that could be in S_diag or S_offd or * neither. */ for(kk = Sop_i[i1]; kk < Sop_i[i1+1]; kk++) { k1 = Sop_j[kk]; if(k1 >= col_1 && k1 < col_n) { /* In S_diag */ loc_col = k1-col_1; if(CF_marker[loc_col] >= 0) { if(P_marker[loc_col] < P_diag_i[ii]) { P_marker[loc_col] = jj_counter; jj_counter++; } } } else { loc_col = -k1 - 1; if(CF_marker_offd[loc_col] >= 0) { if(P_marker_offd[loc_col] < P_offd_i[ii]) { P_marker_offd[loc_col] = jj_counter_offd; tmp_CF_marker_offd[loc_col] = 1; jj_counter_offd++; } } } } } } } } } if (debug_flag==4) { wall_time = time_getWallclockSeconds() - wall_time; hypre_printf("Proc = %d determine structure %f\n", my_id, wall_time); fflush(NULL); } /*----------------------------------------------------------------------- * Allocate arrays. *-----------------------------------------------------------------------*/ P_diag_size = jj_counter; P_offd_size = jj_counter_offd; if (P_diag_size) { P_diag_j = hypre_CTAlloc(HYPRE_Int, P_diag_size); P_diag_data = hypre_CTAlloc(HYPRE_Real, P_diag_size); } if (P_offd_size) { P_offd_j = hypre_CTAlloc(HYPRE_Int, P_offd_size); P_offd_data = hypre_CTAlloc(HYPRE_Real, P_offd_size); } P_diag_i[n_coarse_old] = jj_counter; P_offd_i[n_coarse_old] = jj_counter_offd; jj_counter = start_indexing; jj_counter_offd = start_indexing; /* Fine to coarse mapping */ if(num_procs > 1) { for (i = 0; i < n_fine; i++) fine_to_coarse[i] += my_first_cpt; hypre_alt_insert_new_nodes(comm_pkg, extend_comm_pkg, fine_to_coarse, full_off_procNodes, fine_to_coarse_offd); for (i = 0; i < n_fine; i++) fine_to_coarse[i] -= my_first_cpt; } /* Initialize ahat, which is a modification to a, used in the standard * interpolation routine. */ if (n_fine) { ahat = hypre_CTAlloc(HYPRE_Real, n_fine); ihat = hypre_CTAlloc(HYPRE_Int, n_fine); ipnt = hypre_CTAlloc(HYPRE_Int, n_fine); } if (full_off_procNodes) { ahat_offd = hypre_CTAlloc(HYPRE_Real, full_off_procNodes); ihat_offd = hypre_CTAlloc(HYPRE_Int, full_off_procNodes); ipnt_offd = hypre_CTAlloc(HYPRE_Int, full_off_procNodes); } for (i = 0; i < n_fine; i++) { P_marker[i] = -1; ahat[i] = 0; ihat[i] = -1; } for (i = 0; i < full_off_procNodes; i++) { P_marker_offd[i] = -1; ahat_offd[i] = 0; ihat_offd[i] = -1; } /*----------------------------------------------------------------------- * Loop over fine grid points. *-----------------------------------------------------------------------*/ for (ii = 0; ii < n_coarse_old; ii++) { jj_begin_row = jj_counter; jj_begin_row_offd = jj_counter_offd; i = old_coarse_to_fine[ii]; /*-------------------------------------------------------------------- * If i is a c-point, interpolation is the identity. *--------------------------------------------------------------------*/ if (CF_marker[i] > 0) { P_diag_j[jj_counter] = fine_to_coarse[i]; P_diag_data[jj_counter] = one; jj_counter++; } /*-------------------------------------------------------------------- * If i is an F-point, build interpolation. *--------------------------------------------------------------------*/ else if (CF_marker[i] == -2) { if (debug_flag==4) wall_time = time_getWallclockSeconds(); strong_f_marker--; for (jj = S_diag_i[i]; jj < S_diag_i[i+1]; jj++) { i1 = S_diag_j[jj]; /*-------------------------------------------------------------- * If neighbor i1 is a C-point, set column number in P_diag_j * and initialize interpolation weight to zero. *--------------------------------------------------------------*/ if (CF_marker[i1] > 0) { if (P_marker[i1] < jj_begin_row) { P_marker[i1] = jj_counter; P_diag_j[jj_counter] = i1; P_diag_data[jj_counter] = zero; jj_counter++; } } else if (CF_marker[i1] != -3) { P_marker[i1] = strong_f_marker; for (kk = S_diag_i[i1]; kk < S_diag_i[i1+1]; kk++) { k1 = S_diag_j[kk]; if (CF_marker[k1] > 0) { if(P_marker[k1] < jj_begin_row) { P_marker[k1] = jj_counter; P_diag_j[jj_counter] = k1; P_diag_data[jj_counter] = zero; jj_counter++; } } } if(num_procs > 1) { for (kk = S_offd_i[i1]; kk < S_offd_i[i1+1]; kk++) { if(col_offd_S_to_A) k1 = col_offd_S_to_A[S_offd_j[kk]]; else k1 = S_offd_j[kk]; if(CF_marker_offd[k1] > 0) { if(P_marker_offd[k1] < jj_begin_row_offd) { P_marker_offd[k1] = jj_counter_offd; P_offd_j[jj_counter_offd] = k1; P_offd_data[jj_counter_offd] = zero; jj_counter_offd++; } } } } } } if ( num_procs > 1) { for (jj=S_offd_i[i]; jj < S_offd_i[i+1]; jj++) { i1 = S_offd_j[jj]; if(col_offd_S_to_A) i1 = col_offd_S_to_A[i1]; if ( CF_marker_offd[i1] > 0) { if(P_marker_offd[i1] < jj_begin_row_offd) { P_marker_offd[i1] = jj_counter_offd; P_offd_j[jj_counter_offd]=i1; P_offd_data[jj_counter_offd] = zero; jj_counter_offd++; } } else if (CF_marker_offd[i1] != -3) { P_marker_offd[i1] = strong_f_marker; for(kk = Sop_i[i1]; kk < Sop_i[i1+1]; kk++) { k1 = Sop_j[kk]; if(k1 >= col_1 && k1 < col_n) { loc_col = k1-col_1; if(CF_marker[loc_col] > 0) { if(P_marker[loc_col] < jj_begin_row) { P_marker[loc_col] = jj_counter; P_diag_j[jj_counter] = loc_col; P_diag_data[jj_counter] = zero; jj_counter++; } } } else { loc_col = -k1 - 1; if(CF_marker_offd[loc_col] > 0) { if(P_marker_offd[loc_col] < jj_begin_row_offd) { P_marker_offd[loc_col] = jj_counter_offd; P_offd_j[jj_counter_offd]=loc_col; P_offd_data[jj_counter_offd] = zero; jj_counter_offd++; } } } } } } } jj_end_row = jj_counter; jj_end_row_offd = jj_counter_offd; if (debug_flag==4) { wall_time = time_getWallclockSeconds() - wall_time; wall_1 += wall_time; fflush(NULL); } if (debug_flag==4) wall_time = time_getWallclockSeconds(); cnt_c = 0; cnt_f = jj_end_row-jj_begin_row; cnt_c_offd = 0; cnt_f_offd = jj_end_row_offd-jj_begin_row_offd; ihat[i] = cnt_f; ipnt[cnt_f] = i; ahat[cnt_f++] = A_diag_data[A_diag_i[i]]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { /* i1 is direct neighbor */ i1 = A_diag_j[jj]; if (P_marker[i1] != strong_f_marker) { indx = ihat[i1]; if (indx > -1) ahat[indx] += A_diag_data[jj]; else if (P_marker[i1] >= jj_begin_row) { ihat[i1] = cnt_c; ipnt[cnt_c] = i1; ahat[cnt_c++] += A_diag_data[jj]; } else if (CF_marker[i1] != -3) { ihat[i1] = cnt_f; ipnt[cnt_f] = i1; ahat[cnt_f++] += A_diag_data[jj]; } } else { if(num_functions == 1 || dof_func[i] == dof_func[i1]) { distribute = A_diag_data[jj]/A_diag_data[A_diag_i[i1]]; for (kk = A_diag_i[i1]+1; kk < A_diag_i[i1+1]; kk++) { k1 = A_diag_j[kk]; indx = ihat[k1]; if (indx > -1) ahat[indx] -= A_diag_data[kk]*distribute; else if (P_marker[k1] >= jj_begin_row) { ihat[k1] = cnt_c; ipnt[cnt_c] = k1; ahat[cnt_c++] -= A_diag_data[kk]*distribute; } else { ihat[k1] = cnt_f; ipnt[cnt_f] = k1; ahat[cnt_f++] -= A_diag_data[kk]*distribute; } } if(num_procs > 1) { for (kk = A_offd_i[i1]; kk < A_offd_i[i1+1]; kk++) { k1 = A_offd_j[kk]; indx = ihat_offd[k1]; if(num_functions == 1 || dof_func[i1] == dof_func_offd[k1]) { if (indx > -1) ahat_offd[indx] -= A_offd_data[kk]*distribute; else if (P_marker_offd[k1] >= jj_begin_row_offd) { ihat_offd[k1] = cnt_c_offd; ipnt_offd[cnt_c_offd] = k1; ahat_offd[cnt_c_offd++] -= A_offd_data[kk]*distribute; } else { ihat_offd[k1] = cnt_f_offd; ipnt_offd[cnt_f_offd] = k1; ahat_offd[cnt_f_offd++] -= A_offd_data[kk]*distribute; } } } } } } } if(num_procs > 1) { for(jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { i1 = A_offd_j[jj]; if(P_marker_offd[i1] != strong_f_marker) { indx = ihat_offd[i1]; if (indx > -1) ahat_offd[indx] += A_offd_data[jj]; else if (P_marker_offd[i1] >= jj_begin_row_offd) { ihat_offd[i1] = cnt_c_offd; ipnt_offd[cnt_c_offd] = i1; ahat_offd[cnt_c_offd++] += A_offd_data[jj]; } else if (CF_marker_offd[i1] != -3) { ihat_offd[i1] = cnt_f_offd; ipnt_offd[cnt_f_offd] = i1; ahat_offd[cnt_f_offd++] += A_offd_data[jj]; } } else { if(num_functions == 1 || dof_func[i] == dof_func_offd[i1]) { distribute = A_offd_data[jj]/A_ext_data[A_ext_i[i1]]; for (kk = A_ext_i[i1]+1; kk < A_ext_i[i1+1]; kk++) { k1 = A_ext_j[kk]; if(k1 >= col_1 && k1 < col_n) { /*diag*/ loc_col = k1 - col_1; indx = ihat[loc_col]; if (indx > -1) ahat[indx] -= A_ext_data[kk]*distribute; else if (P_marker[loc_col] >= jj_begin_row) { ihat[loc_col] = cnt_c; ipnt[cnt_c] = loc_col; ahat[cnt_c++] -= A_ext_data[kk]*distribute; } else { ihat[loc_col] = cnt_f; ipnt[cnt_f] = loc_col; ahat[cnt_f++] -= A_ext_data[kk]*distribute; } } else { loc_col = -k1 - 1; if(num_functions == 1 || dof_func_offd[loc_col] == dof_func_offd[i1]) { indx = ihat_offd[loc_col]; if (indx > -1) ahat_offd[indx] -= A_ext_data[kk]*distribute; else if(P_marker_offd[loc_col] >= jj_begin_row_offd) { ihat_offd[loc_col] = cnt_c_offd; ipnt_offd[cnt_c_offd] = loc_col; ahat_offd[cnt_c_offd++] -= A_ext_data[kk]*distribute; } else { ihat_offd[loc_col] = cnt_f_offd; ipnt_offd[cnt_f_offd] = loc_col; ahat_offd[cnt_f_offd++] -= A_ext_data[kk]*distribute; } } } } } } } } if (debug_flag==4) { wall_time = time_getWallclockSeconds() - wall_time; wall_2 += wall_time; fflush(NULL); } if (debug_flag==4) wall_time = time_getWallclockSeconds(); diagonal = ahat[cnt_c]; ahat[cnt_c] = 0; sum_pos = 0; sum_pos_C = 0; sum_neg = 0; sum_neg_C = 0; sum = 0; sum_C = 0; if(sep_weight == 1) { for (jj=0; jj < cnt_c; jj++) { if (ahat[jj] > 0) { sum_pos_C += ahat[jj]; } else { sum_neg_C += ahat[jj]; } } if(num_procs > 1) { for (jj=0; jj < cnt_c_offd; jj++) { if (ahat_offd[jj] > 0) { sum_pos_C += ahat_offd[jj]; } else { sum_neg_C += ahat_offd[jj]; } } } sum_pos = sum_pos_C; sum_neg = sum_neg_C; for (jj=cnt_c+1; jj < cnt_f; jj++) { if (ahat[jj] > 0) { sum_pos += ahat[jj]; } else { sum_neg += ahat[jj]; } ahat[jj] = 0; } if(num_procs > 1) { for (jj=cnt_c_offd; jj < cnt_f_offd; jj++) { if (ahat_offd[jj] > 0) { sum_pos += ahat_offd[jj]; } else { sum_neg += ahat_offd[jj]; } ahat_offd[jj] = 0; } } if (sum_neg_C*diagonal) alfa = sum_neg/sum_neg_C/diagonal; if (sum_pos_C*diagonal) beta = sum_pos/sum_pos_C/diagonal; /*----------------------------------------------------------------- * Set interpolation weight by dividing by the diagonal. *-----------------------------------------------------------------*/ for (jj = jj_begin_row; jj < jj_end_row; jj++) { j1 = ihat[P_diag_j[jj]]; if (ahat[j1] > 0) P_diag_data[jj] = -beta*ahat[j1]; else P_diag_data[jj] = -alfa*ahat[j1]; P_diag_j[jj] = fine_to_coarse[P_diag_j[jj]]; ahat[j1] = 0; } for (jj=0; jj < cnt_f; jj++) ihat[ipnt[jj]] = -1; if(num_procs > 1) { for (jj = jj_begin_row_offd; jj < jj_end_row_offd; jj++) { j1 = ihat_offd[P_offd_j[jj]]; if (ahat_offd[j1] > 0) P_offd_data[jj] = -beta*ahat_offd[j1]; else P_offd_data[jj] = -alfa*ahat_offd[j1]; ahat_offd[j1] = 0; } for (jj=0; jj < cnt_f_offd; jj++) ihat_offd[ipnt_offd[jj]] = -1; } } else { for (jj=0; jj < cnt_c; jj++) { sum_C += ahat[jj]; } if(num_procs > 1) { for (jj=0; jj < cnt_c_offd; jj++) { sum_C += ahat_offd[jj]; } } sum = sum_C; for (jj=cnt_c+1; jj < cnt_f; jj++) { sum += ahat[jj]; ahat[jj] = 0; } if(num_procs > 1) { for (jj=cnt_c_offd; jj < cnt_f_offd; jj++) { sum += ahat_offd[jj]; ahat_offd[jj] = 0; } } if (sum_C*diagonal) alfa = sum/sum_C/diagonal; /*----------------------------------------------------------------- * Set interpolation weight by dividing by the diagonal. *-----------------------------------------------------------------*/ for (jj = jj_begin_row; jj < jj_end_row; jj++) { j1 = ihat[P_diag_j[jj]]; P_diag_data[jj] = -alfa*ahat[j1]; P_diag_j[jj] = fine_to_coarse[P_diag_j[jj]]; ahat[j1] = 0; } for (jj=0; jj < cnt_f; jj++) ihat[ipnt[jj]] = -1; if(num_procs > 1) { for (jj = jj_begin_row_offd; jj < jj_end_row_offd; jj++) { j1 = ihat_offd[P_offd_j[jj]]; P_offd_data[jj] = -alfa*ahat_offd[j1]; ahat_offd[j1] = 0; } for (jj=0; jj < cnt_f_offd; jj++) ihat_offd[ipnt_offd[jj]] = -1; } } if (debug_flag==4) { wall_time = time_getWallclockSeconds() - wall_time; wall_3 += wall_time; fflush(NULL); } } } if (debug_flag==4) { hypre_printf("Proc = %d fill part 1 %f part 2 %f part 3 %f\n", my_id, wall_1, wall_2, wall_3); fflush(NULL); } P = hypre_ParCSRMatrixCreate(comm, total_old_global_cpts, total_global_cpts, num_old_cpts_global, num_cpts_global, 0, P_diag_i[n_coarse_old], P_offd_i[n_coarse_old]); P_diag = hypre_ParCSRMatrixDiag(P); hypre_CSRMatrixData(P_diag) = P_diag_data; hypre_CSRMatrixI(P_diag) = P_diag_i; hypre_CSRMatrixJ(P_diag) = P_diag_j; P_offd = hypre_ParCSRMatrixOffd(P); hypre_CSRMatrixData(P_offd) = P_offd_data; hypre_CSRMatrixI(P_offd) = P_offd_i; hypre_CSRMatrixJ(P_offd) = P_offd_j; hypre_ParCSRMatrixOwnsRowStarts(P) = 0; /* Compress P, removing coefficients smaller than trunc_factor * Max */ if (trunc_factor != 0.0 || max_elmts > 0) { hypre_BoomerAMGInterpTruncation(P, trunc_factor, max_elmts); P_diag_data = hypre_CSRMatrixData(P_diag); P_diag_i = hypre_CSRMatrixI(P_diag); P_diag_j = hypre_CSRMatrixJ(P_diag); P_offd_data = hypre_CSRMatrixData(P_offd); P_offd_i = hypre_CSRMatrixI(P_offd); P_offd_j = hypre_CSRMatrixJ(P_offd); P_diag_size = P_diag_i[n_coarse_old]; P_offd_size = P_offd_i[n_coarse_old]; } /* This builds col_map, col_map should be monotone increasing and contain * global numbers. */ if(P_offd_size) { hypre_build_interp_colmap(P, full_off_procNodes, tmp_CF_marker_offd, fine_to_coarse_offd); } hypre_MatvecCommPkgCreate(P); for (i=0; i < n_fine; i++) if (CF_marker[i] < -1) CF_marker[i] = -1; *P_ptr = P; /* Deallocate memory */ hypre_TFree(fine_to_coarse); hypre_TFree(old_coarse_to_fine); hypre_TFree(P_marker); hypre_TFree(ahat); hypre_TFree(ihat); hypre_TFree(ipnt); if (full_off_procNodes) { hypre_TFree(ahat_offd); hypre_TFree(ihat_offd); hypre_TFree(ipnt_offd); } if (num_procs > 1) { hypre_CSRMatrixDestroy(Sop); hypre_CSRMatrixDestroy(A_ext); hypre_TFree(fine_to_coarse_offd); hypre_TFree(P_marker_offd); hypre_TFree(CF_marker_offd); hypre_TFree(tmp_CF_marker_offd); if(num_functions > 1) hypre_TFree(dof_func_offd); hypre_MatvecCommPkgDestroy(extend_comm_pkg); } return hypre_error_flag; } /*--------------------------------------------------------------------------- * hypre_BoomerAMGBuildPartialExtInterp * Comment: *--------------------------------------------------------------------------*/ HYPRE_Int hypre_BoomerAMGBuildPartialExtInterp(hypre_ParCSRMatrix *A, HYPRE_Int *CF_marker, hypre_ParCSRMatrix *S, HYPRE_Int *num_cpts_global, HYPRE_Int *num_old_cpts_global, HYPRE_Int num_functions, HYPRE_Int *dof_func, HYPRE_Int debug_flag, HYPRE_Real trunc_factor, HYPRE_Int max_elmts, HYPRE_Int *col_offd_S_to_A, hypre_ParCSRMatrix **P_ptr) { /* Communication Variables */ MPI_Comm comm = hypre_ParCSRMatrixComm(A); hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A); HYPRE_Int my_id, num_procs; /* Variables to store input variables */ hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); HYPRE_Real *A_diag_data = hypre_CSRMatrixData(A_diag); HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag); HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag); hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); HYPRE_Real *A_offd_data = hypre_CSRMatrixData(A_offd); HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd); HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd); /*HYPRE_Int num_cols_A_offd = hypre_CSRMatrixNumCols(A_offd); HYPRE_Int *col_map_offd = hypre_ParCSRMatrixColMapOffd(A);*/ HYPRE_Int n_fine = hypre_CSRMatrixNumRows(A_diag); HYPRE_Int col_1 = hypre_ParCSRMatrixFirstRowIndex(A); HYPRE_Int local_numrows = hypre_CSRMatrixNumRows(A_diag); HYPRE_Int col_n = col_1 + local_numrows; HYPRE_Int total_global_cpts, my_first_cpt; /* Variables to store strong connection matrix info */ hypre_CSRMatrix *S_diag = hypre_ParCSRMatrixDiag(S); HYPRE_Int *S_diag_i = hypre_CSRMatrixI(S_diag); HYPRE_Int *S_diag_j = hypre_CSRMatrixJ(S_diag); hypre_CSRMatrix *S_offd = hypre_ParCSRMatrixOffd(S); HYPRE_Int *S_offd_i = hypre_CSRMatrixI(S_offd); HYPRE_Int *S_offd_j = hypre_CSRMatrixJ(S_offd); /* Interpolation matrix P */ hypre_ParCSRMatrix *P; hypre_CSRMatrix *P_diag; hypre_CSRMatrix *P_offd; HYPRE_Real *P_diag_data = NULL; HYPRE_Int *P_diag_i, *P_diag_j = NULL; HYPRE_Real *P_offd_data = NULL; HYPRE_Int *P_offd_i, *P_offd_j = NULL; /*HYPRE_Int *col_map_offd_P = NULL;*/ HYPRE_Int P_diag_size; HYPRE_Int P_offd_size; HYPRE_Int *P_marker = NULL; HYPRE_Int *P_marker_offd = NULL; HYPRE_Int *CF_marker_offd = NULL; HYPRE_Int *tmp_CF_marker_offd = NULL; HYPRE_Int *dof_func_offd = NULL; /* Full row information for columns of A that are off diag*/ hypre_CSRMatrix *A_ext; HYPRE_Real *A_ext_data; HYPRE_Int *A_ext_i; HYPRE_Int *A_ext_j; HYPRE_Int *fine_to_coarse = NULL; HYPRE_Int *fine_to_coarse_offd = NULL; HYPRE_Int *old_coarse_to_fine = NULL; HYPRE_Int loc_col; HYPRE_Int full_off_procNodes; hypre_CSRMatrix *Sop; HYPRE_Int *Sop_i; HYPRE_Int *Sop_j; HYPRE_Int sgn; /* Variables to keep count of interpolatory points */ HYPRE_Int jj_counter, jj_counter_offd; HYPRE_Int jj_begin_row, jj_end_row; HYPRE_Int jj_begin_row_offd = 0; HYPRE_Int jj_end_row_offd = 0; HYPRE_Int coarse_counter; HYPRE_Int n_coarse_old; HYPRE_Int total_old_global_cpts; /* Interpolation weight variables */ HYPRE_Real sum, diagonal, distribute; HYPRE_Int strong_f_marker = -2; /* Loop variables */ /*HYPRE_Int index;*/ HYPRE_Int cnt, old_cnt; HYPRE_Int start_indexing = 0; HYPRE_Int i, ii, i1, i2, jj, kk, k1, jj1; /* Definitions */ HYPRE_Real zero = 0.0; HYPRE_Real one = 1.0; HYPRE_Real wall_time; hypre_ParCSRCommPkg *extend_comm_pkg = NULL; if (debug_flag==4) wall_time = time_getWallclockSeconds(); /* BEGIN */ hypre_MPI_Comm_size(comm, &num_procs); hypre_MPI_Comm_rank(comm,&my_id); #ifdef HYPRE_NO_GLOBAL_PARTITION my_first_cpt = num_cpts_global[0]; /*my_first_old_cpt = num_old_cpts_global[0];*/ n_coarse_old = num_old_cpts_global[1] - num_old_cpts_global[0]; /*n_coarse = num_cpts_global[1] - num_cpts_global[0];*/ if (my_id == (num_procs -1)) { total_global_cpts = num_cpts_global[1]; total_old_global_cpts = num_old_cpts_global[1]; } hypre_MPI_Bcast(&total_global_cpts, 1, HYPRE_MPI_INT, num_procs-1, comm); hypre_MPI_Bcast(&total_old_global_cpts, 1, HYPRE_MPI_INT, num_procs-1, comm); #else my_first_cpt = num_cpts_global[my_id]; /*my_first_old_cpt = num_old_cpts_global[my_id];*/ total_global_cpts = num_cpts_global[num_procs]; total_old_global_cpts = num_old_cpts_global[num_procs]; n_coarse_old = num_old_cpts_global[my_id+1] - num_old_cpts_global[my_id]; /*n_coarse = num_cpts_global[my_id+1] - num_cpts_global[my_id];*/ #endif if (!comm_pkg) { hypre_MatvecCommPkgCreate(A); comm_pkg = hypre_ParCSRMatrixCommPkg(A); } /* Set up off processor information (specifically for neighbors of * neighbors */ full_off_procNodes = 0; if (num_procs > 1) { if (hypre_exchange_interp_data( &CF_marker_offd, &dof_func_offd, &A_ext, &full_off_procNodes, &Sop, &extend_comm_pkg, A, CF_marker, S, num_functions, dof_func, 1)) { #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_EXTENDED_I_INTERP] += hypre_MPI_Wtime(); #endif return hypre_error_flag; } A_ext_i = hypre_CSRMatrixI(A_ext); A_ext_j = hypre_CSRMatrixJ(A_ext); A_ext_data = hypre_CSRMatrixData(A_ext); Sop_i = hypre_CSRMatrixI(Sop); Sop_j = hypre_CSRMatrixJ(Sop); } /*----------------------------------------------------------------------- * First Pass: Determine size of P and fill in fine_to_coarse mapping. *-----------------------------------------------------------------------*/ /*----------------------------------------------------------------------- * Intialize counters and allocate mapping vector. *-----------------------------------------------------------------------*/ P_diag_i = hypre_CTAlloc(HYPRE_Int, n_coarse_old+1); P_offd_i = hypre_CTAlloc(HYPRE_Int, n_coarse_old+1); if (n_fine) { old_coarse_to_fine = hypre_CTAlloc(HYPRE_Int, n_coarse_old); fine_to_coarse = hypre_CTAlloc(HYPRE_Int, n_fine); P_marker = hypre_CTAlloc(HYPRE_Int, n_fine); } if (full_off_procNodes) { P_marker_offd = hypre_CTAlloc(HYPRE_Int, full_off_procNodes); fine_to_coarse_offd = hypre_CTAlloc(HYPRE_Int, full_off_procNodes); tmp_CF_marker_offd = hypre_CTAlloc(HYPRE_Int, full_off_procNodes); } hypre_initialize_vecs(n_fine, full_off_procNodes, fine_to_coarse, fine_to_coarse_offd, P_marker, P_marker_offd, tmp_CF_marker_offd); jj_counter = start_indexing; jj_counter_offd = start_indexing; coarse_counter = 0; cnt = 0; old_cnt = 0; for (i = 0; i < n_fine; i++) { fine_to_coarse[i] = -1; if (CF_marker[i] == 1) { fine_to_coarse[i] = cnt++; old_coarse_to_fine[old_cnt++] = i; } else if (CF_marker[i] == -2) { old_coarse_to_fine[old_cnt++] = i; } } /*----------------------------------------------------------------------- * Loop over fine grid. *-----------------------------------------------------------------------*/ for (ii = 0; ii < n_coarse_old; ii++) { P_diag_i[ii] = jj_counter; if (num_procs > 1) P_offd_i[ii] = jj_counter_offd; i = old_coarse_to_fine[ii]; if (CF_marker[i] > 0) { jj_counter++; coarse_counter++; } /*-------------------------------------------------------------------- * If i is an F-point, interpolation is from the C-points that * strongly influence i, or C-points that stronly influence F-points * that strongly influence i. *--------------------------------------------------------------------*/ else if (CF_marker[i] == -2) { for (jj = S_diag_i[i]; jj < S_diag_i[i+1]; jj++) { i1 = S_diag_j[jj]; if (CF_marker[i1] > 0) { /* i1 is a C point */ if (P_marker[i1] < P_diag_i[ii]) { P_marker[i1] = jj_counter; jj_counter++; } } else if (CF_marker[i1] != -3) { /* i1 is a F point, loop through it's strong neighbors */ for (kk = S_diag_i[i1]; kk < S_diag_i[i1+1]; kk++) { k1 = S_diag_j[kk]; if (CF_marker[k1] > 0) { if(P_marker[k1] < P_diag_i[ii]) { P_marker[k1] = jj_counter; jj_counter++; } } } if(num_procs > 1) { for (kk = S_offd_i[i1]; kk < S_offd_i[i1+1]; kk++) { if(col_offd_S_to_A) k1 = col_offd_S_to_A[S_offd_j[kk]]; else k1 = S_offd_j[kk]; if (CF_marker_offd[k1] > 0) { if(P_marker_offd[k1] < P_offd_i[ii]) { tmp_CF_marker_offd[k1] = 1; P_marker_offd[k1] = jj_counter_offd; jj_counter_offd++; } } } } } } /* Look at off diag strong connections of i */ if (num_procs > 1) { for (jj = S_offd_i[i]; jj < S_offd_i[i+1]; jj++) { i1 = S_offd_j[jj]; if(col_offd_S_to_A) i1 = col_offd_S_to_A[i1]; if (CF_marker_offd[i1] > 0) { if(P_marker_offd[i1] < P_offd_i[ii]) { tmp_CF_marker_offd[i1] = 1; P_marker_offd[i1] = jj_counter_offd; jj_counter_offd++; } } else if (CF_marker_offd[i1] != -3) { /* F point; look at neighbors of i1. Sop contains global col * numbers and entries that could be in S_diag or S_offd or * neither. */ for(kk = Sop_i[i1]; kk < Sop_i[i1+1]; kk++) { k1 = Sop_j[kk]; if(k1 >= col_1 && k1 < col_n) { /* In S_diag */ loc_col = k1-col_1; if(P_marker[loc_col] < P_diag_i[ii]) { P_marker[loc_col] = jj_counter; jj_counter++; } } else { loc_col = -k1 - 1; if(P_marker_offd[loc_col] < P_offd_i[ii]) { P_marker_offd[loc_col] = jj_counter_offd; tmp_CF_marker_offd[loc_col] = 1; jj_counter_offd++; } } } } } } } } if (debug_flag==4) { wall_time = time_getWallclockSeconds() - wall_time; hypre_printf("Proc = %d determine structure %f\n", my_id, wall_time); fflush(NULL); } /*----------------------------------------------------------------------- * Allocate arrays. *-----------------------------------------------------------------------*/ if (debug_flag== 4) wall_time = time_getWallclockSeconds(); P_diag_size = jj_counter; P_offd_size = jj_counter_offd; if (P_diag_size) { P_diag_j = hypre_CTAlloc(HYPRE_Int, P_diag_size); P_diag_data = hypre_CTAlloc(HYPRE_Real, P_diag_size); } if (P_offd_size) { P_offd_j = hypre_CTAlloc(HYPRE_Int, P_offd_size); P_offd_data = hypre_CTAlloc(HYPRE_Real, P_offd_size); } P_diag_i[n_coarse_old] = jj_counter; P_offd_i[n_coarse_old] = jj_counter_offd; jj_counter = start_indexing; jj_counter_offd = start_indexing; /* Fine to coarse mapping */ if(num_procs > 1) { for (i = 0; i < n_fine; i++) fine_to_coarse[i] += my_first_cpt; hypre_alt_insert_new_nodes(comm_pkg, extend_comm_pkg, fine_to_coarse, full_off_procNodes, fine_to_coarse_offd); for (i = 0; i < n_fine; i++) fine_to_coarse[i] -= my_first_cpt; } for (i = 0; i < n_fine; i++) P_marker[i] = -1; for (i = 0; i < full_off_procNodes; i++) P_marker_offd[i] = -1; /*----------------------------------------------------------------------- * Loop over fine grid points. *-----------------------------------------------------------------------*/ for (ii = 0; ii < n_coarse_old; ii++) { jj_begin_row = jj_counter; jj_begin_row_offd = jj_counter_offd; i = old_coarse_to_fine[ii]; /*-------------------------------------------------------------------- * If i is a c-point, interpolation is the identity. *--------------------------------------------------------------------*/ if (CF_marker[i] > 0) { P_diag_j[jj_counter] = fine_to_coarse[i]; P_diag_data[jj_counter] = one; jj_counter++; } /*-------------------------------------------------------------------- * If i is an F-point, build interpolation. *--------------------------------------------------------------------*/ else if (CF_marker[i] == -2) { strong_f_marker--; for (jj = S_diag_i[i]; jj < S_diag_i[i+1]; jj++) { i1 = S_diag_j[jj]; /*-------------------------------------------------------------- * If neighbor i1 is a C-point, set column number in P_diag_j * and initialize interpolation weight to zero. *--------------------------------------------------------------*/ if (CF_marker[i1] >= 0) { if (P_marker[i1] < jj_begin_row) { P_marker[i1] = jj_counter; P_diag_j[jj_counter] = fine_to_coarse[i1]; P_diag_data[jj_counter] = zero; jj_counter++; } } else if (CF_marker[i1] != -3) { P_marker[i1] = strong_f_marker; for (kk = S_diag_i[i1]; kk < S_diag_i[i1+1]; kk++) { k1 = S_diag_j[kk]; if (CF_marker[k1] >= 0) { if(P_marker[k1] < jj_begin_row) { P_marker[k1] = jj_counter; P_diag_j[jj_counter] = fine_to_coarse[k1]; P_diag_data[jj_counter] = zero; jj_counter++; } } } if(num_procs > 1) { for (kk = S_offd_i[i1]; kk < S_offd_i[i1+1]; kk++) { if(col_offd_S_to_A) k1 = col_offd_S_to_A[S_offd_j[kk]]; else k1 = S_offd_j[kk]; if(CF_marker_offd[k1] >= 0) { if(P_marker_offd[k1] < jj_begin_row_offd) { P_marker_offd[k1] = jj_counter_offd; P_offd_j[jj_counter_offd] = k1; P_offd_data[jj_counter_offd] = zero; jj_counter_offd++; } } } } } } if ( num_procs > 1) { for (jj=S_offd_i[i]; jj < S_offd_i[i+1]; jj++) { i1 = S_offd_j[jj]; if(col_offd_S_to_A) i1 = col_offd_S_to_A[i1]; if ( CF_marker_offd[i1] >= 0) { if(P_marker_offd[i1] < jj_begin_row_offd) { P_marker_offd[i1] = jj_counter_offd; P_offd_j[jj_counter_offd] = i1; P_offd_data[jj_counter_offd] = zero; jj_counter_offd++; } } else if (CF_marker_offd[i1] != -3) { P_marker_offd[i1] = strong_f_marker; for(kk = Sop_i[i1]; kk < Sop_i[i1+1]; kk++) { k1 = Sop_j[kk]; /* Find local col number */ if(k1 >= col_1 && k1 < col_n) { loc_col = k1-col_1; if(P_marker[loc_col] < jj_begin_row) { P_marker[loc_col] = jj_counter; P_diag_j[jj_counter] = fine_to_coarse[loc_col]; P_diag_data[jj_counter] = zero; jj_counter++; } } else { loc_col = -k1 - 1; if(P_marker_offd[loc_col] < jj_begin_row_offd) { P_marker_offd[loc_col] = jj_counter_offd; P_offd_j[jj_counter_offd]=loc_col; P_offd_data[jj_counter_offd] = zero; jj_counter_offd++; } } } } } } jj_end_row = jj_counter; jj_end_row_offd = jj_counter_offd; diagonal = A_diag_data[A_diag_i[i]]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { /* i1 is a c-point and strongly influences i, accumulate * a_(i,i1) into interpolation weight */ i1 = A_diag_j[jj]; if (P_marker[i1] >= jj_begin_row) { P_diag_data[P_marker[i1]] += A_diag_data[jj]; } else if(P_marker[i1] == strong_f_marker) { sum = zero; sgn = 1; if(A_diag_data[A_diag_i[i1]] < 0) sgn = -1; /* Loop over row of A for point i1 and calculate the sum * of the connections to c-points that strongly incluence i. */ for(jj1 = A_diag_i[i1]+1; jj1 < A_diag_i[i1+1]; jj1++) { i2 = A_diag_j[jj1]; if((P_marker[i2] >= jj_begin_row) && (sgn*A_diag_data[jj1]) < 0) sum += A_diag_data[jj1]; } if(num_procs > 1) { for(jj1 = A_offd_i[i1]; jj1< A_offd_i[i1+1]; jj1++) { i2 = A_offd_j[jj1]; if(P_marker_offd[i2] >= jj_begin_row_offd && (sgn*A_offd_data[jj1]) < 0) sum += A_offd_data[jj1]; } } if(sum != 0) { distribute = A_diag_data[jj]/sum; /* Loop over row of A for point i1 and do the distribution */ for(jj1 = A_diag_i[i1]+1; jj1 < A_diag_i[i1+1]; jj1++) { i2 = A_diag_j[jj1]; if(P_marker[i2] >= jj_begin_row && (sgn*A_diag_data[jj1]) < 0) P_diag_data[P_marker[i2]] += distribute*A_diag_data[jj1]; } if(num_procs > 1) { for(jj1 = A_offd_i[i1]; jj1 < A_offd_i[i1+1]; jj1++) { i2 = A_offd_j[jj1]; if(P_marker_offd[i2] >= jj_begin_row_offd && (sgn*A_offd_data[jj1]) < 0) P_offd_data[P_marker_offd[i2]] += distribute*A_offd_data[jj1]; } } } else { diagonal += A_diag_data[jj]; } } /* neighbor i1 weakly influences i, accumulate a_(i,i1) into * diagonal */ else if (CF_marker[i1] != -3) { if(num_functions == 1 || dof_func[i] == dof_func[i1]) diagonal += A_diag_data[jj]; } } if(num_procs > 1) { for(jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { i1 = A_offd_j[jj]; if(P_marker_offd[i1] >= jj_begin_row_offd) P_offd_data[P_marker_offd[i1]] += A_offd_data[jj]; else if(P_marker_offd[i1] == strong_f_marker) { sum = zero; for(jj1 = A_ext_i[i1]; jj1 < A_ext_i[i1+1]; jj1++) { k1 = A_ext_j[jj1]; if(k1 >= col_1 && k1 < col_n) { /* diag */ loc_col = k1 - col_1; if(P_marker[loc_col] >= jj_begin_row ) sum += A_ext_data[jj1]; } else { loc_col = -k1 - 1; if(P_marker_offd[loc_col] >= jj_begin_row_offd && (sgn*A_ext_data[jj1]) < 0) sum += A_ext_data[jj1]; } } if(sum != 0) { distribute = A_offd_data[jj] / sum; for(jj1 = A_ext_i[i1]; jj1 < A_ext_i[i1+1]; jj1++) { k1 = A_ext_j[jj1]; if(k1 >= col_1 && k1 < col_n) { /* diag */ loc_col = k1 - col_1; if(P_marker[loc_col] >= jj_begin_row) P_diag_data[P_marker[loc_col]] += distribute* A_ext_data[jj1]; } else { loc_col = -k1 - 1; if(P_marker_offd[loc_col] >= jj_begin_row_offd) P_offd_data[P_marker_offd[loc_col]] += distribute* A_ext_data[jj1]; } } } else { diagonal += A_offd_data[jj]; } } else if (CF_marker_offd[i1] != -3) { if(num_functions == 1 || dof_func[i] == dof_func_offd[i1]) diagonal += A_offd_data[jj]; } } } if (diagonal) { for(jj = jj_begin_row; jj < jj_end_row; jj++) P_diag_data[jj] /= -diagonal; for(jj = jj_begin_row_offd; jj < jj_end_row_offd; jj++) P_offd_data[jj] /= -diagonal; } } strong_f_marker--; } if (debug_flag==4) { wall_time = time_getWallclockSeconds() - wall_time; hypre_printf("Proc = %d fill structure %f\n", my_id, wall_time); fflush(NULL); } /*----------------------------------------------------------------------- * Allocate arrays. *-----------------------------------------------------------------------*/ P = hypre_ParCSRMatrixCreate(comm, total_old_global_cpts, total_global_cpts, num_old_cpts_global, num_cpts_global, 0, P_diag_i[n_coarse_old], P_offd_i[n_coarse_old]); P_diag = hypre_ParCSRMatrixDiag(P); hypre_CSRMatrixData(P_diag) = P_diag_data; hypre_CSRMatrixI(P_diag) = P_diag_i; hypre_CSRMatrixJ(P_diag) = P_diag_j; P_offd = hypre_ParCSRMatrixOffd(P); hypre_CSRMatrixData(P_offd) = P_offd_data; hypre_CSRMatrixI(P_offd) = P_offd_i; hypre_CSRMatrixJ(P_offd) = P_offd_j; hypre_ParCSRMatrixOwnsRowStarts(P) = 0; /* Compress P, removing coefficients smaller than trunc_factor * Max */ if (trunc_factor != 0.0 || max_elmts > 0) { hypre_BoomerAMGInterpTruncation(P, trunc_factor, max_elmts); P_diag_data = hypre_CSRMatrixData(P_diag); P_diag_i = hypre_CSRMatrixI(P_diag); P_diag_j = hypre_CSRMatrixJ(P_diag); P_offd_data = hypre_CSRMatrixData(P_offd); P_offd_i = hypre_CSRMatrixI(P_offd); P_offd_j = hypre_CSRMatrixJ(P_offd); P_diag_size = P_diag_i[n_coarse_old]; P_offd_size = P_offd_i[n_coarse_old]; } /* This builds col_map, col_map should be monotone increasing and contain * global numbers. */ if(P_offd_size) { hypre_build_interp_colmap(P, full_off_procNodes, tmp_CF_marker_offd, fine_to_coarse_offd); } hypre_MatvecCommPkgCreate(P); for (i=0; i < n_fine; i++) if (CF_marker[i] < -1) CF_marker[i] = -1; *P_ptr = P; /* Deallocate memory */ hypre_TFree(fine_to_coarse); hypre_TFree(old_coarse_to_fine); hypre_TFree(P_marker); if (num_procs > 1) { hypre_CSRMatrixDestroy(Sop); hypre_CSRMatrixDestroy(A_ext); hypre_TFree(fine_to_coarse_offd); hypre_TFree(P_marker_offd); hypre_TFree(CF_marker_offd); hypre_TFree(tmp_CF_marker_offd); if(num_functions > 1) hypre_TFree(dof_func_offd); hypre_MatvecCommPkgDestroy(extend_comm_pkg); } return hypre_error_flag; }
78,427
28.934351
95
c
AMG
AMG-master/parcsr_ls/pcg_par.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ #include "_hypre_parcsr_ls.h" /*-------------------------------------------------------------------------- * hypre_ParKrylovCAlloc *--------------------------------------------------------------------------*/ char * hypre_ParKrylovCAlloc( HYPRE_Int count, HYPRE_Int elt_size ) { return( hypre_CAlloc( count, elt_size ) ); } /*-------------------------------------------------------------------------- * hypre_ParKrylovFree *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParKrylovFree( char *ptr ) { HYPRE_Int ierr = 0; hypre_Free( ptr ); return ierr; } /*-------------------------------------------------------------------------- * hypre_ParKrylovCreateVector *--------------------------------------------------------------------------*/ void * hypre_ParKrylovCreateVector( void *vvector ) { hypre_ParVector *vector = (hypre_ParVector *) vvector; hypre_ParVector *new_vector; new_vector = hypre_ParVectorCreate( hypre_ParVectorComm(vector), hypre_ParVectorGlobalSize(vector), hypre_ParVectorPartitioning(vector) ); hypre_ParVectorSetPartitioningOwner(new_vector,0); hypre_ParVectorInitialize(new_vector); return ( (void *) new_vector ); } /*-------------------------------------------------------------------------- * hypre_ParKrylovCreateVectorArray *--------------------------------------------------------------------------*/ void * hypre_ParKrylovCreateVectorArray(HYPRE_Int n, void *vvector ) { hypre_ParVector *vector = (hypre_ParVector *) vvector; hypre_ParVector **new_vector; HYPRE_Int i; new_vector = hypre_CTAlloc(hypre_ParVector*,n); for (i=0; i < n; i++) { new_vector[i] = hypre_ParVectorCreate( hypre_ParVectorComm(vector), hypre_ParVectorGlobalSize(vector), hypre_ParVectorPartitioning(vector) ); hypre_ParVectorSetPartitioningOwner(new_vector[i],0); hypre_ParVectorInitialize(new_vector[i]); } return ( (void *) new_vector ); } /*-------------------------------------------------------------------------- * hypre_ParKrylovDestroyVector *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParKrylovDestroyVector( void *vvector ) { hypre_ParVector *vector = (hypre_ParVector *) vvector; return( hypre_ParVectorDestroy( vector ) ); } /*-------------------------------------------------------------------------- * hypre_ParKrylovMatvecCreate *--------------------------------------------------------------------------*/ void * hypre_ParKrylovMatvecCreate( void *A, void *x ) { void *matvec_data; matvec_data = NULL; return ( matvec_data ); } /*-------------------------------------------------------------------------- * hypre_ParKrylovMatvec *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParKrylovMatvec( void *matvec_data, HYPRE_Complex alpha, void *A, void *x, HYPRE_Complex beta, void *y ) { return ( hypre_ParCSRMatrixMatvec ( alpha, (hypre_ParCSRMatrix *) A, (hypre_ParVector *) x, beta, (hypre_ParVector *) y ) ); } /*-------------------------------------------------------------------------- * hypre_ParKrylovMatvecT *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParKrylovMatvecT(void *matvec_data, HYPRE_Complex alpha, void *A, void *x, HYPRE_Complex beta, void *y ) { return ( hypre_ParCSRMatrixMatvecT( alpha, (hypre_ParCSRMatrix *) A, (hypre_ParVector *) x, beta, (hypre_ParVector *) y ) ); } /*-------------------------------------------------------------------------- * hypre_ParKrylovMatvecDestroy *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParKrylovMatvecDestroy( void *matvec_data ) { return 0; } /*-------------------------------------------------------------------------- * hypre_ParKrylovInnerProd *--------------------------------------------------------------------------*/ HYPRE_Real hypre_ParKrylovInnerProd( void *x, void *y ) { return ( hypre_ParVectorInnerProd( (hypre_ParVector *) x, (hypre_ParVector *) y ) ); } /*-------------------------------------------------------------------------- * hypre_ParKrylovCopyVector *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParKrylovCopyVector( void *x, void *y ) { return ( hypre_ParVectorCopy( (hypre_ParVector *) x, (hypre_ParVector *) y ) ); } /*-------------------------------------------------------------------------- * hypre_ParKrylovClearVector *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParKrylovClearVector( void *x ) { return ( hypre_ParVectorSetConstantValues( (hypre_ParVector *) x, 0.0 ) ); } /*-------------------------------------------------------------------------- * hypre_ParKrylovScaleVector *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParKrylovScaleVector( HYPRE_Complex alpha, void *x ) { return ( hypre_ParVectorScale( alpha, (hypre_ParVector *) x ) ); } /*-------------------------------------------------------------------------- * hypre_ParKrylovAxpy *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParKrylovAxpy( HYPRE_Complex alpha, void *x, void *y ) { return ( hypre_ParVectorAxpy( alpha, (hypre_ParVector *) x, (hypre_ParVector *) y ) ); } /*-------------------------------------------------------------------------- * hypre_ParKrylovCommInfo *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParKrylovCommInfo( void *A, HYPRE_Int *my_id, HYPRE_Int *num_procs) { MPI_Comm comm = hypre_ParCSRMatrixComm ( (hypre_ParCSRMatrix *) A); hypre_MPI_Comm_size(comm,num_procs); hypre_MPI_Comm_rank(comm,my_id); return 0; } /*-------------------------------------------------------------------------- * hypre_ParKrylovIdentitySetup *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParKrylovIdentitySetup( void *vdata, void *A, void *b, void *x ) { return 0; } /*-------------------------------------------------------------------------- * hypre_ParKrylovIdentity *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParKrylovIdentity( void *vdata, void *A, void *b, void *x ) { return( hypre_ParKrylovCopyVector( b, x ) ); }
8,616
31.764259
83
c
AMG
AMG-master/parcsr_mv/HYPRE_parcsr_matrix.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /****************************************************************************** * * HYPRE_ParCSRMatrix interface * *****************************************************************************/ #include "_hypre_parcsr_mv.h" /*-------------------------------------------------------------------------- * HYPRE_ParCSRMatrixCreate *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParCSRMatrixCreate( MPI_Comm comm, HYPRE_Int global_num_rows, HYPRE_Int global_num_cols, HYPRE_Int *row_starts, HYPRE_Int *col_starts, HYPRE_Int num_cols_offd, HYPRE_Int num_nonzeros_diag, HYPRE_Int num_nonzeros_offd, HYPRE_ParCSRMatrix *matrix ) { if (!matrix) { hypre_error_in_arg(9); return hypre_error_flag; } *matrix = (HYPRE_ParCSRMatrix) hypre_ParCSRMatrixCreate(comm, global_num_rows, global_num_cols, row_starts, col_starts, num_cols_offd, num_nonzeros_diag, num_nonzeros_offd); return hypre_error_flag; } /*-------------------------------------------------------------------------- * HYPRE_ParCSRMatrixDestroy *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParCSRMatrixDestroy( HYPRE_ParCSRMatrix matrix ) { return( hypre_ParCSRMatrixDestroy( (hypre_ParCSRMatrix *) matrix ) ); } /*-------------------------------------------------------------------------- * HYPRE_ParCSRMatrixInitialize *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParCSRMatrixInitialize( HYPRE_ParCSRMatrix matrix ) { return ( hypre_ParCSRMatrixInitialize( (hypre_ParCSRMatrix *) matrix ) ); } /*-------------------------------------------------------------------------- * HYPRE_ParCSRMatrixRead *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParCSRMatrixRead( MPI_Comm comm, const char *file_name, HYPRE_ParCSRMatrix *matrix) { if (!matrix) { hypre_error_in_arg(3); return hypre_error_flag; } *matrix = (HYPRE_ParCSRMatrix) hypre_ParCSRMatrixRead( comm, file_name ); return hypre_error_flag; } /*-------------------------------------------------------------------------- * HYPRE_ParCSRMatrixPrint *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParCSRMatrixPrint( HYPRE_ParCSRMatrix matrix, const char *file_name ) { hypre_ParCSRMatrixPrint( (hypre_ParCSRMatrix *) matrix, file_name ); return hypre_error_flag; } /*-------------------------------------------------------------------------- * HYPRE_ParCSRMatrixGetComm *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParCSRMatrixGetComm( HYPRE_ParCSRMatrix matrix, MPI_Comm *comm ) { if (!matrix) { hypre_error_in_arg(1); return hypre_error_flag; } *comm = hypre_ParCSRMatrixComm((hypre_ParCSRMatrix *) matrix); return hypre_error_flag; } /*-------------------------------------------------------------------------- * HYPRE_ParCSRMatrixGetDims *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParCSRMatrixGetDims( HYPRE_ParCSRMatrix matrix, HYPRE_Int *M, HYPRE_Int *N ) { if (!matrix) { hypre_error_in_arg(1); return hypre_error_flag; } *M = hypre_ParCSRMatrixGlobalNumRows((hypre_ParCSRMatrix *) matrix); *N = hypre_ParCSRMatrixGlobalNumCols((hypre_ParCSRMatrix *) matrix); return hypre_error_flag; } /*-------------------------------------------------------------------------- * HYPRE_ParCSRMatrixGetRowPartitioning *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParCSRMatrixGetRowPartitioning( HYPRE_ParCSRMatrix matrix, HYPRE_Int **row_partitioning_ptr ) { HYPRE_Int *row_partitioning, *row_starts; HYPRE_Int num_procs, i; if (!matrix) { hypre_error_in_arg(1); return hypre_error_flag; } hypre_MPI_Comm_size(hypre_ParCSRMatrixComm((hypre_ParCSRMatrix *) matrix), &num_procs); row_starts = hypre_ParCSRMatrixRowStarts((hypre_ParCSRMatrix *) matrix); if (!row_starts) return -1; row_partitioning = hypre_CTAlloc(HYPRE_Int, num_procs+1); for (i=0; i < num_procs + 1; i++) row_partitioning[i] = row_starts[i]; *row_partitioning_ptr = row_partitioning; return hypre_error_flag; } /*-------------------------------------------------------------------------- * HYPRE_ParCSRMatrixGetColPartitioning *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParCSRMatrixGetColPartitioning( HYPRE_ParCSRMatrix matrix, HYPRE_Int **col_partitioning_ptr ) { HYPRE_Int *col_partitioning, *col_starts; HYPRE_Int num_procs, i; if (!matrix) { hypre_error_in_arg(1); return hypre_error_flag; } hypre_MPI_Comm_size(hypre_ParCSRMatrixComm((hypre_ParCSRMatrix *) matrix), &num_procs); col_starts = hypre_ParCSRMatrixColStarts((hypre_ParCSRMatrix *) matrix); if (!col_starts) return -1; col_partitioning = hypre_CTAlloc(HYPRE_Int, num_procs+1); for (i=0; i < num_procs + 1; i++) col_partitioning[i] = col_starts[i]; *col_partitioning_ptr = col_partitioning; return hypre_error_flag; } /*-------------------------------------------------------------------------- * HYPRE_ParCSRMatrixGetLocalRange *--------------------------------------------------------------------------*/ /** Returns range of rows and columns owned by this processor. Not collective. @return integer error code @param HYPRE_ParCSRMatrix matrix [IN] the matrix to be operated on. @param HYPRE_Int *row_start [OUT] the global number of the first row stored on this processor @param HYPRE_Int *row_end [OUT] the global number of the first row stored on this processor @param HYPRE_Int *col_start [OUT] the global number of the first column stored on this processor @param HYPRE_Int *col_end [OUT] the global number of the first column stored on this processor */ HYPRE_Int HYPRE_ParCSRMatrixGetLocalRange( HYPRE_ParCSRMatrix matrix, HYPRE_Int *row_start, HYPRE_Int *row_end, HYPRE_Int *col_start, HYPRE_Int *col_end ) { if (!matrix) { hypre_error_in_arg(1); return hypre_error_flag; } hypre_ParCSRMatrixGetLocalRange( (hypre_ParCSRMatrix *) matrix, row_start, row_end, col_start, col_end ); return hypre_error_flag; } /*-------------------------------------------------------------------------- * HYPRE_ParCSRMatrixGetRow *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParCSRMatrixGetRow( HYPRE_ParCSRMatrix matrix, HYPRE_Int row, HYPRE_Int *size, HYPRE_Int **col_ind, HYPRE_Complex **values ) { if (!matrix) { hypre_error_in_arg(1); return hypre_error_flag; } hypre_ParCSRMatrixGetRow( (hypre_ParCSRMatrix *) matrix, row, size, col_ind, values ); return hypre_error_flag; } /*-------------------------------------------------------------------------- * HYPRE_ParCSRMatrixRestoreRow *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParCSRMatrixRestoreRow( HYPRE_ParCSRMatrix matrix, HYPRE_Int row, HYPRE_Int *size, HYPRE_Int **col_ind, HYPRE_Complex **values ) { if (!matrix) { hypre_error_in_arg(1); return hypre_error_flag; } hypre_ParCSRMatrixRestoreRow( (hypre_ParCSRMatrix *) matrix, row, size, col_ind, values ); return hypre_error_flag; } /*-------------------------------------------------------------------------- * HYPRE_CSRMatrixToParCSRMatrix * Output argument (fifth argument): a new ParCSRmatrix. * Input arguments: MPI communicator, CSR matrix, and optional partitionings. * If you don't have partitionings, just pass a null pointer for the third * and fourth arguments and they will be computed. * Note that it is not possible to provide a null pointer if this is called * from Fortran code; so you must provide the paritionings from Fortran. *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_CSRMatrixToParCSRMatrix( MPI_Comm comm, HYPRE_CSRMatrix A_CSR, HYPRE_Int *row_partitioning, HYPRE_Int *col_partitioning, HYPRE_ParCSRMatrix *matrix) { if (!matrix) { hypre_error_in_arg(5); return hypre_error_flag; } *matrix = (HYPRE_ParCSRMatrix) hypre_CSRMatrixToParCSRMatrix( comm, (hypre_CSRMatrix *) A_CSR, row_partitioning, col_partitioning) ; return hypre_error_flag; } /*-------------------------------------------------------------------------- * HYPRE_CSRMatrixToParCSRMatrix_WithNewPartitioning * Output argument (third argument): a new ParCSRmatrix. * Input arguments: MPI communicator, CSR matrix. * Row and column partitionings are computed for the output matrix. *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_CSRMatrixToParCSRMatrix_WithNewPartitioning( MPI_Comm comm, HYPRE_CSRMatrix A_CSR, HYPRE_ParCSRMatrix *matrix ) { if (!matrix) { hypre_error_in_arg(3); return hypre_error_flag; } *matrix = (HYPRE_ParCSRMatrix) hypre_CSRMatrixToParCSRMatrix( comm, (hypre_CSRMatrix *) A_CSR, NULL, NULL ) ; return hypre_error_flag; } /*-------------------------------------------------------------------------- * HYPRE_ParCSRMatrixMatvec *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParCSRMatrixMatvec( HYPRE_Complex alpha, HYPRE_ParCSRMatrix A, HYPRE_ParVector x, HYPRE_Complex beta, HYPRE_ParVector y ) { return ( hypre_ParCSRMatrixMatvec( alpha, (hypre_ParCSRMatrix *) A, (hypre_ParVector *) x, beta, (hypre_ParVector *) y) ); } /*-------------------------------------------------------------------------- * HYPRE_ParCSRMatrixMatvecT *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParCSRMatrixMatvecT( HYPRE_Complex alpha, HYPRE_ParCSRMatrix A, HYPRE_ParVector x, HYPRE_Complex beta, HYPRE_ParVector y ) { return ( hypre_ParCSRMatrixMatvecT( alpha, (hypre_ParCSRMatrix *) A, (hypre_ParVector *) x, beta, (hypre_ParVector *) y) ); }
12,975
34.550685
84
c
AMG
AMG-master/parcsr_mv/HYPRE_parcsr_mv.h
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /****************************************************************************** * * Header file for HYPRE_parcsr_mv library * *****************************************************************************/ #ifndef HYPRE_PARCSR_MV_HEADER #define HYPRE_PARCSR_MV_HEADER #include "HYPRE_utilities.h" #include "HYPRE_seq_mv.h" #ifdef __cplusplus extern "C" { #endif /*-------------------------------------------------------------------------- * Structures *--------------------------------------------------------------------------*/ struct hypre_ParCSRMatrix_struct; typedef struct hypre_ParCSRMatrix_struct *HYPRE_ParCSRMatrix; struct hypre_ParVector_struct; typedef struct hypre_ParVector_struct *HYPRE_ParVector; /*-------------------------------------------------------------------------- * Prototypes *--------------------------------------------------------------------------*/ /* HYPRE_parcsr_matrix.c */ HYPRE_Int HYPRE_ParCSRMatrixCreate( MPI_Comm comm , HYPRE_Int global_num_rows , HYPRE_Int global_num_cols , HYPRE_Int *row_starts , HYPRE_Int *col_starts , HYPRE_Int num_cols_offd , HYPRE_Int num_nonzeros_diag , HYPRE_Int num_nonzeros_offd , HYPRE_ParCSRMatrix *matrix ); HYPRE_Int HYPRE_ParCSRMatrixDestroy( HYPRE_ParCSRMatrix matrix ); HYPRE_Int HYPRE_ParCSRMatrixInitialize( HYPRE_ParCSRMatrix matrix ); HYPRE_Int HYPRE_ParCSRMatrixRead( MPI_Comm comm , const char *file_name , HYPRE_ParCSRMatrix *matrix ); HYPRE_Int HYPRE_ParCSRMatrixPrint( HYPRE_ParCSRMatrix matrix , const char *file_name ); HYPRE_Int HYPRE_ParCSRMatrixGetComm( HYPRE_ParCSRMatrix matrix , MPI_Comm *comm ); HYPRE_Int HYPRE_ParCSRMatrixGetDims( HYPRE_ParCSRMatrix matrix , HYPRE_Int *M , HYPRE_Int *N ); HYPRE_Int HYPRE_ParCSRMatrixGetRowPartitioning( HYPRE_ParCSRMatrix matrix , HYPRE_Int **row_partitioning_ptr ); HYPRE_Int HYPRE_ParCSRMatrixGetColPartitioning( HYPRE_ParCSRMatrix matrix , HYPRE_Int **col_partitioning_ptr ); HYPRE_Int HYPRE_ParCSRMatrixGetLocalRange( HYPRE_ParCSRMatrix matrix , HYPRE_Int *row_start , HYPRE_Int *row_end , HYPRE_Int *col_start , HYPRE_Int *col_end ); HYPRE_Int HYPRE_ParCSRMatrixGetRow( HYPRE_ParCSRMatrix matrix , HYPRE_Int row , HYPRE_Int *size , HYPRE_Int **col_ind , HYPRE_Complex **values ); HYPRE_Int HYPRE_ParCSRMatrixRestoreRow( HYPRE_ParCSRMatrix matrix , HYPRE_Int row , HYPRE_Int *size , HYPRE_Int **col_ind , HYPRE_Complex **values ); HYPRE_Int HYPRE_CSRMatrixToParCSRMatrix( MPI_Comm comm , HYPRE_CSRMatrix A_CSR , HYPRE_Int *row_partitioning , HYPRE_Int *col_partitioning , HYPRE_ParCSRMatrix *matrix ); HYPRE_Int HYPRE_ParCSRMatrixMatvec( HYPRE_Complex alpha , HYPRE_ParCSRMatrix A , HYPRE_ParVector x , HYPRE_Complex beta , HYPRE_ParVector y ); HYPRE_Int HYPRE_ParCSRMatrixMatvecT( HYPRE_Complex alpha , HYPRE_ParCSRMatrix A , HYPRE_ParVector x , HYPRE_Complex beta , HYPRE_ParVector y ); /* HYPRE_parcsr_vector.c */ HYPRE_Int HYPRE_ParVectorCreate( MPI_Comm comm , HYPRE_Int global_size , HYPRE_Int *partitioning , HYPRE_ParVector *vector ); HYPRE_Int HYPRE_ParVectorDestroy( HYPRE_ParVector vector ); HYPRE_Int HYPRE_ParVectorInitialize( HYPRE_ParVector vector ); HYPRE_Int HYPRE_ParVectorRead( MPI_Comm comm , const char *file_name , HYPRE_ParVector *vector ); HYPRE_Int HYPRE_ParVectorPrint( HYPRE_ParVector vector , const char *file_name ); HYPRE_Int HYPRE_ParVectorSetConstantValues( HYPRE_ParVector vector , HYPRE_Complex value ); HYPRE_Int HYPRE_ParVectorSetRandomValues( HYPRE_ParVector vector , HYPRE_Int seed ); HYPRE_Int HYPRE_ParVectorCopy( HYPRE_ParVector x , HYPRE_ParVector y ); HYPRE_Int HYPRE_ParVectorScale( HYPRE_Complex value , HYPRE_ParVector x ); HYPRE_Int HYPRE_ParVectorInnerProd( HYPRE_ParVector x , HYPRE_ParVector y , HYPRE_Real *prod ); HYPRE_Int HYPRE_VectorToParVector( MPI_Comm comm , HYPRE_Vector b , HYPRE_Int *partitioning , HYPRE_ParVector *vector ); #ifdef __cplusplus } #endif #endif
4,801
56.855422
271
h
AMG
AMG-master/parcsr_mv/HYPRE_parcsr_vector.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /****************************************************************************** * * HYPRE_ParVector interface * *****************************************************************************/ #include "_hypre_parcsr_mv.h" /*-------------------------------------------------------------------------- * HYPRE_ParVectorCreate *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParVectorCreate( MPI_Comm comm, HYPRE_Int global_size, HYPRE_Int *partitioning, HYPRE_ParVector *vector ) { if (!vector) { hypre_error_in_arg(4); return hypre_error_flag; } *vector = (HYPRE_ParVector) hypre_ParVectorCreate(comm, global_size, partitioning) ; return hypre_error_flag; } /*-------------------------------------------------------------------------- * HYPRE_ParMultiVectorCreate *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParMultiVectorCreate( MPI_Comm comm, HYPRE_Int global_size, HYPRE_Int *partitioning, HYPRE_Int number_vectors, HYPRE_ParVector *vector ) { if (!vector) { hypre_error_in_arg(5); return hypre_error_flag; } *vector = (HYPRE_ParVector) hypre_ParMultiVectorCreate( comm, global_size, partitioning, number_vectors ); return hypre_error_flag; } /*-------------------------------------------------------------------------- * HYPRE_ParVectorDestroy *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParVectorDestroy( HYPRE_ParVector vector ) { return ( hypre_ParVectorDestroy( (hypre_ParVector *) vector ) ); } /*-------------------------------------------------------------------------- * HYPRE_ParVectorInitialize *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParVectorInitialize( HYPRE_ParVector vector ) { return ( hypre_ParVectorInitialize( (hypre_ParVector *) vector ) ); } /*-------------------------------------------------------------------------- * HYPRE_ParVectorRead *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParVectorRead( MPI_Comm comm, const char *file_name, HYPRE_ParVector *vector) { if (!vector) { hypre_error_in_arg(3); return hypre_error_flag; } *vector = (HYPRE_ParVector) hypre_ParVectorRead( comm, file_name ) ; return hypre_error_flag; } /*-------------------------------------------------------------------------- * HYPRE_ParVectorPrint *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParVectorPrint( HYPRE_ParVector vector, const char *file_name ) { return ( hypre_ParVectorPrint( (hypre_ParVector *) vector, file_name ) ); } /*-------------------------------------------------------------------------- * HYPRE_ParVectorSetConstantValues *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParVectorSetConstantValues( HYPRE_ParVector vector, HYPRE_Complex value ) { return ( hypre_ParVectorSetConstantValues( (hypre_ParVector *) vector, value ) ); } /*-------------------------------------------------------------------------- * HYPRE_ParVectorSetRandomValues *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParVectorSetRandomValues( HYPRE_ParVector vector, HYPRE_Int seed ) { return ( hypre_ParVectorSetRandomValues( (hypre_ParVector *) vector, seed ) ); } /*-------------------------------------------------------------------------- * HYPRE_ParVectorCopy *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParVectorCopy( HYPRE_ParVector x, HYPRE_ParVector y ) { return ( hypre_ParVectorCopy( (hypre_ParVector *) x, (hypre_ParVector *) y ) ); } /*-------------------------------------------------------------------------- * HYPRE_ParVectorCloneShallow *--------------------------------------------------------------------------*/ HYPRE_ParVector HYPRE_ParVectorCloneShallow( HYPRE_ParVector x ) { return ( (HYPRE_ParVector) hypre_ParVectorCloneShallow( (hypre_ParVector *) x ) ); } /*-------------------------------------------------------------------------- * HYPRE_ParVectorScale *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParVectorScale( HYPRE_Complex value, HYPRE_ParVector x) { return ( hypre_ParVectorScale( value, (hypre_ParVector *) x) ); } /*-------------------------------------------------------------------------- * HYPRE_ParVectorAxpy *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParVectorAxpy( HYPRE_Complex alpha, HYPRE_ParVector x, HYPRE_ParVector y ) { return hypre_ParVectorAxpy( alpha, (hypre_ParVector *)x, (hypre_ParVector *)y ); } /*-------------------------------------------------------------------------- * HYPRE_ParVectorInnerProd *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_ParVectorInnerProd( HYPRE_ParVector x, HYPRE_ParVector y, HYPRE_Real *prod) { if (!x) { hypre_error_in_arg(1); return hypre_error_flag; } if (!y) { hypre_error_in_arg(2); return hypre_error_flag; } *prod = hypre_ParVectorInnerProd( (hypre_ParVector *) x, (hypre_ParVector *) y) ; return hypre_error_flag; } /*-------------------------------------------------------------------------- * HYPRE_VectorToParVector *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_VectorToParVector( MPI_Comm comm, HYPRE_Vector b, HYPRE_Int *partitioning, HYPRE_ParVector *vector) { if (!vector) { hypre_error_in_arg(4); return hypre_error_flag; } *vector = (HYPRE_ParVector) hypre_VectorToParVector (comm, (hypre_Vector *) b, partitioning); return hypre_error_flag; }
7,715
32.402597
84
c
AMG
AMG-master/parcsr_mv/_hypre_parcsr_mv.h
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ #include "HYPRE_parcsr_mv.h" #ifndef hypre_PARCSR_MV_HEADER #define hypre_PARCSR_MV_HEADER #include "_hypre_utilities.h" #include "seq_mv.h" #ifdef __cplusplus extern "C" { #endif #ifndef HYPRE_PAR_CSR_COMMUNICATION_HEADER #define HYPRE_PAR_CSR_COMMUNICATION_HEADER /*-------------------------------------------------------------------------- * hypre_ParCSRCommPkg: * Structure containing information for doing communications *--------------------------------------------------------------------------*/ /*#define HYPRE_USING_PERSISTENT_COMM*/ // JSP: can be defined by configure #ifdef HYPRE_USING_PERSISTENT_COMM typedef enum CommPkgJobType { HYPRE_COMM_PKG_JOB_COMPLEX = 0, HYPRE_COMM_PKG_JOB_COMPLEX_TRANSPOSE, HYPRE_COMM_PKG_JOB_INT, HYPRE_COMM_PKG_JOB_INT_TRANSPOSE, NUM_OF_COMM_PKG_JOB_TYPE, } CommPkgJobType; typedef struct { void *send_data; void *recv_data; HYPRE_Int num_requests; hypre_MPI_Request *requests; HYPRE_Int own_send_data, own_recv_data; } hypre_ParCSRPersistentCommHandle; #endif typedef struct { MPI_Comm comm; HYPRE_Int num_sends; HYPRE_Int *send_procs; HYPRE_Int *send_map_starts; HYPRE_Int *send_map_elmts; HYPRE_Int num_recvs; HYPRE_Int *recv_procs; HYPRE_Int *recv_vec_starts; /* remote communication information */ hypre_MPI_Datatype *send_mpi_types; hypre_MPI_Datatype *recv_mpi_types; #ifdef HYPRE_USING_PERSISTENT_COMM hypre_ParCSRPersistentCommHandle *persistent_comm_handles[NUM_OF_COMM_PKG_JOB_TYPE]; #endif } hypre_ParCSRCommPkg; /*-------------------------------------------------------------------------- * hypre_ParCSRCommHandle: *--------------------------------------------------------------------------*/ typedef struct { hypre_ParCSRCommPkg *comm_pkg; void *send_data; void *recv_data; HYPRE_Int num_requests; hypre_MPI_Request *requests; } hypre_ParCSRCommHandle; /*-------------------------------------------------------------------------- * Accessor macros: hypre_ParCSRCommPkg *--------------------------------------------------------------------------*/ #define hypre_ParCSRCommPkgComm(comm_pkg) (comm_pkg -> comm) #define hypre_ParCSRCommPkgNumSends(comm_pkg) (comm_pkg -> num_sends) #define hypre_ParCSRCommPkgSendProcs(comm_pkg) (comm_pkg -> send_procs) #define hypre_ParCSRCommPkgSendProc(comm_pkg, i) (comm_pkg -> send_procs[i]) #define hypre_ParCSRCommPkgSendMapStarts(comm_pkg) (comm_pkg -> send_map_starts) #define hypre_ParCSRCommPkgSendMapStart(comm_pkg,i)(comm_pkg -> send_map_starts[i]) #define hypre_ParCSRCommPkgSendMapElmts(comm_pkg) (comm_pkg -> send_map_elmts) #define hypre_ParCSRCommPkgSendMapElmt(comm_pkg,i) (comm_pkg -> send_map_elmts[i]) #define hypre_ParCSRCommPkgNumRecvs(comm_pkg) (comm_pkg -> num_recvs) #define hypre_ParCSRCommPkgRecvProcs(comm_pkg) (comm_pkg -> recv_procs) #define hypre_ParCSRCommPkgRecvProc(comm_pkg, i) (comm_pkg -> recv_procs[i]) #define hypre_ParCSRCommPkgRecvVecStarts(comm_pkg) (comm_pkg -> recv_vec_starts) #define hypre_ParCSRCommPkgRecvVecStart(comm_pkg,i)(comm_pkg -> recv_vec_starts[i]) #define hypre_ParCSRCommPkgSendMPITypes(comm_pkg) (comm_pkg -> send_mpi_types) #define hypre_ParCSRCommPkgSendMPIType(comm_pkg,i) (comm_pkg -> send_mpi_types[i]) #define hypre_ParCSRCommPkgRecvMPITypes(comm_pkg) (comm_pkg -> recv_mpi_types) #define hypre_ParCSRCommPkgRecvMPIType(comm_pkg,i) (comm_pkg -> recv_mpi_types[i]) /*-------------------------------------------------------------------------- * Accessor macros: hypre_ParCSRCommHandle *--------------------------------------------------------------------------*/ #define hypre_ParCSRCommHandleCommPkg(comm_handle) (comm_handle -> comm_pkg) #define hypre_ParCSRCommHandleSendData(comm_handle) (comm_handle -> send_data) #define hypre_ParCSRCommHandleRecvData(comm_handle) (comm_handle -> recv_data) #define hypre_ParCSRCommHandleNumRequests(comm_handle) (comm_handle -> num_requests) #define hypre_ParCSRCommHandleRequests(comm_handle) (comm_handle -> requests) #define hypre_ParCSRCommHandleRequest(comm_handle, i) (comm_handle -> requests[i]) #endif /* HYPRE_PAR_CSR_COMMUNICATION_HEADER */ #ifndef hypre_PARCSR_ASSUMED_PART #define hypre_PARCSR_ASSUMED_PART typedef struct { HYPRE_Int length; HYPRE_Int row_start; HYPRE_Int row_end; HYPRE_Int storage_length; HYPRE_Int *proc_list; HYPRE_Int *row_start_list; HYPRE_Int *row_end_list; HYPRE_Int *sort_index; } hypre_IJAssumedPart; #endif /* hypre_PARCSR_ASSUMED_PART */ #ifndef hypre_NEW_COMMPKG #define hypre_NEW_COMMPKG typedef struct { HYPRE_Int length; HYPRE_Int storage_length; HYPRE_Int *id; HYPRE_Int *vec_starts; HYPRE_Int element_storage_length; HYPRE_Int *elements; HYPRE_Real *d_elements; /* Is this used anywhere? */ void *v_elements; } hypre_ProcListElements; #endif /* hypre_NEW_COMMPKG */ /****************************************************************************** * * Header info for Parallel Vector data structure * *****************************************************************************/ #ifndef hypre_PAR_VECTOR_HEADER #define hypre_PAR_VECTOR_HEADER /*-------------------------------------------------------------------------- * hypre_ParVector *--------------------------------------------------------------------------*/ #ifndef HYPRE_PAR_VECTOR_STRUCT #define HYPRE_PAR_VECTOR_STRUCT #endif typedef struct hypre_ParVector_struct { MPI_Comm comm; HYPRE_Int global_size; HYPRE_Int first_index; HYPRE_Int last_index; HYPRE_Int *partitioning; HYPRE_Int actual_local_size; /* stores actual length of data in local vector to allow memory manipulations for temporary vectors*/ hypre_Vector *local_vector; /* Does the Vector create/destroy `data'? */ HYPRE_Int owns_data; HYPRE_Int owns_partitioning; hypre_IJAssumedPart *assumed_partition; /* only populated if no_global_partition option is used (compile-time option) AND this partition needed (for setting off-proc elements, for example)*/ } hypre_ParVector; /*-------------------------------------------------------------------------- * Accessor functions for the Vector structure *--------------------------------------------------------------------------*/ #define hypre_ParVectorComm(vector) ((vector) -> comm) #define hypre_ParVectorGlobalSize(vector) ((vector) -> global_size) #define hypre_ParVectorFirstIndex(vector) ((vector) -> first_index) #define hypre_ParVectorLastIndex(vector) ((vector) -> last_index) #define hypre_ParVectorPartitioning(vector) ((vector) -> partitioning) #define hypre_ParVectorActualLocalSize(vector) ((vector) -> actual_local_size) #define hypre_ParVectorLocalVector(vector) ((vector) -> local_vector) #define hypre_ParVectorOwnsData(vector) ((vector) -> owns_data) #define hypre_ParVectorOwnsPartitioning(vector) ((vector) -> owns_partitioning) #define hypre_ParVectorNumVectors(vector)\ (hypre_VectorNumVectors( hypre_ParVectorLocalVector(vector) )) #define hypre_ParVectorAssumedPartition(vector) ((vector) -> assumed_partition) #endif /****************************************************************************** * * Header info for Parallel CSR Matrix data structures * * Note: this matrix currently uses 0-based indexing. * *****************************************************************************/ #ifndef hypre_PAR_CSR_MATRIX_HEADER #define hypre_PAR_CSR_MATRIX_HEADER /*-------------------------------------------------------------------------- * Parallel CSR Matrix *--------------------------------------------------------------------------*/ #ifndef HYPRE_PAR_CSR_MATRIX_STRUCT #define HYPRE_PAR_CSR_MATRIX_STRUCT #endif typedef struct hypre_ParCSRMatrix_struct { MPI_Comm comm; HYPRE_Int global_num_rows; HYPRE_Int global_num_cols; HYPRE_Int first_row_index; HYPRE_Int first_col_diag; /* need to know entire local range in case row_starts and col_starts are null (i.e., bgl) AHB 6/05*/ HYPRE_Int last_row_index; HYPRE_Int last_col_diag; hypre_CSRMatrix *diag; hypre_CSRMatrix *offd; hypre_CSRMatrix *diagT, *offdT; /* JSP: transposed matrices are created lazily and optional */ HYPRE_Int *col_map_offd; /* maps columns of offd to global columns */ HYPRE_Int *row_starts; /* array of length num_procs+1, row_starts[i] contains the global number of the first row on proc i, first_row_index = row_starts[my_id], row_starts[num_procs] = global_num_rows */ HYPRE_Int *col_starts; /* array of length num_procs+1, col_starts[i] contains the global number of the first column of diag on proc i, first_col_diag = col_starts[my_id], col_starts[num_procs] = global_num_cols */ hypre_ParCSRCommPkg *comm_pkg; hypre_ParCSRCommPkg *comm_pkgT; /* Does the ParCSRMatrix create/destroy `diag', `offd', `col_map_offd'? */ HYPRE_Int owns_data; /* Does the ParCSRMatrix create/destroy `row_starts', `col_starts'? */ HYPRE_Int owns_row_starts; HYPRE_Int owns_col_starts; HYPRE_Int num_nonzeros; HYPRE_Real d_num_nonzeros; /* Buffers used by GetRow to hold row currently being accessed. AJC, 4/99 */ HYPRE_Int *rowindices; HYPRE_Complex *rowvalues; HYPRE_Int getrowactive; hypre_IJAssumedPart *assumed_partition; /* only populated if no_global_partition option is used (compile-time option)*/ } hypre_ParCSRMatrix; /*-------------------------------------------------------------------------- * Accessor functions for the Parallel CSR Matrix structure *--------------------------------------------------------------------------*/ #define hypre_ParCSRMatrixComm(matrix) ((matrix) -> comm) #define hypre_ParCSRMatrixGlobalNumRows(matrix) ((matrix) -> global_num_rows) #define hypre_ParCSRMatrixGlobalNumCols(matrix) ((matrix) -> global_num_cols) #define hypre_ParCSRMatrixFirstRowIndex(matrix) ((matrix) -> first_row_index) #define hypre_ParCSRMatrixFirstColDiag(matrix) ((matrix) -> first_col_diag) #define hypre_ParCSRMatrixLastRowIndex(matrix) ((matrix) -> last_row_index) #define hypre_ParCSRMatrixLastColDiag(matrix) ((matrix) -> last_col_diag) #define hypre_ParCSRMatrixDiag(matrix) ((matrix) -> diag) #define hypre_ParCSRMatrixOffd(matrix) ((matrix) -> offd) #define hypre_ParCSRMatrixDiagT(matrix) ((matrix) -> diagT) #define hypre_ParCSRMatrixOffdT(matrix) ((matrix) -> offdT) #define hypre_ParCSRMatrixColMapOffd(matrix) ((matrix) -> col_map_offd) #define hypre_ParCSRMatrixRowStarts(matrix) ((matrix) -> row_starts) #define hypre_ParCSRMatrixColStarts(matrix) ((matrix) -> col_starts) #define hypre_ParCSRMatrixCommPkg(matrix) ((matrix) -> comm_pkg) #define hypre_ParCSRMatrixCommPkgT(matrix) ((matrix) -> comm_pkgT) #define hypre_ParCSRMatrixOwnsData(matrix) ((matrix) -> owns_data) #define hypre_ParCSRMatrixOwnsRowStarts(matrix) ((matrix) -> owns_row_starts) #define hypre_ParCSRMatrixOwnsColStarts(matrix) ((matrix) -> owns_col_starts) #define hypre_ParCSRMatrixNumRows(matrix) \ hypre_CSRMatrixNumRows(hypre_ParCSRMatrixDiag(matrix)) #define hypre_ParCSRMatrixNumCols(matrix) \ hypre_CSRMatrixNumCols(hypre_ParCSRMatrixDiag(matrix)) #define hypre_ParCSRMatrixNumNonzeros(matrix) ((matrix) -> num_nonzeros) #define hypre_ParCSRMatrixDNumNonzeros(matrix) ((matrix) -> d_num_nonzeros) #define hypre_ParCSRMatrixRowindices(matrix) ((matrix) -> rowindices) #define hypre_ParCSRMatrixRowvalues(matrix) ((matrix) -> rowvalues) #define hypre_ParCSRMatrixGetrowactive(matrix) ((matrix) -> getrowactive) #define hypre_ParCSRMatrixAssumedPartition(matrix) ((matrix) -> assumed_partition) #endif /* HYPRE_parcsr_matrix.c */ HYPRE_Int HYPRE_ParCSRMatrixCreate ( MPI_Comm comm , HYPRE_Int global_num_rows , HYPRE_Int global_num_cols , HYPRE_Int *row_starts , HYPRE_Int *col_starts , HYPRE_Int num_cols_offd , HYPRE_Int num_nonzeros_diag , HYPRE_Int num_nonzeros_offd , HYPRE_ParCSRMatrix *matrix ); HYPRE_Int HYPRE_ParCSRMatrixDestroy ( HYPRE_ParCSRMatrix matrix ); HYPRE_Int HYPRE_ParCSRMatrixInitialize ( HYPRE_ParCSRMatrix matrix ); HYPRE_Int HYPRE_ParCSRMatrixRead ( MPI_Comm comm , const char *file_name , HYPRE_ParCSRMatrix *matrix ); HYPRE_Int HYPRE_ParCSRMatrixPrint ( HYPRE_ParCSRMatrix matrix , const char *file_name ); HYPRE_Int HYPRE_ParCSRMatrixGetComm ( HYPRE_ParCSRMatrix matrix , MPI_Comm *comm ); HYPRE_Int HYPRE_ParCSRMatrixGetDims ( HYPRE_ParCSRMatrix matrix , HYPRE_Int *M , HYPRE_Int *N ); HYPRE_Int HYPRE_ParCSRMatrixGetRowPartitioning ( HYPRE_ParCSRMatrix matrix , HYPRE_Int **row_partitioning_ptr ); HYPRE_Int HYPRE_ParCSRMatrixGetColPartitioning ( HYPRE_ParCSRMatrix matrix , HYPRE_Int **col_partitioning_ptr ); HYPRE_Int HYPRE_ParCSRMatrixGetLocalRange ( HYPRE_ParCSRMatrix matrix , HYPRE_Int *row_start , HYPRE_Int *row_end , HYPRE_Int *col_start , HYPRE_Int *col_end ); HYPRE_Int HYPRE_ParCSRMatrixGetRow ( HYPRE_ParCSRMatrix matrix , HYPRE_Int row , HYPRE_Int *size , HYPRE_Int **col_ind , HYPRE_Complex **values ); HYPRE_Int HYPRE_ParCSRMatrixRestoreRow ( HYPRE_ParCSRMatrix matrix , HYPRE_Int row , HYPRE_Int *size , HYPRE_Int **col_ind , HYPRE_Complex **values ); HYPRE_Int HYPRE_CSRMatrixToParCSRMatrix ( MPI_Comm comm , HYPRE_CSRMatrix A_CSR , HYPRE_Int *row_partitioning , HYPRE_Int *col_partitioning , HYPRE_ParCSRMatrix *matrix ); HYPRE_Int HYPRE_CSRMatrixToParCSRMatrix_WithNewPartitioning ( MPI_Comm comm , HYPRE_CSRMatrix A_CSR , HYPRE_ParCSRMatrix *matrix ); HYPRE_Int HYPRE_ParCSRMatrixMatvec ( HYPRE_Complex alpha , HYPRE_ParCSRMatrix A , HYPRE_ParVector x , HYPRE_Complex beta , HYPRE_ParVector y ); HYPRE_Int HYPRE_ParCSRMatrixMatvecT ( HYPRE_Complex alpha , HYPRE_ParCSRMatrix A , HYPRE_ParVector x , HYPRE_Complex beta , HYPRE_ParVector y ); /* HYPRE_parcsr_vector.c */ HYPRE_Int HYPRE_ParVectorCreate ( MPI_Comm comm , HYPRE_Int global_size , HYPRE_Int *partitioning , HYPRE_ParVector *vector ); HYPRE_Int HYPRE_ParMultiVectorCreate ( MPI_Comm comm , HYPRE_Int global_size , HYPRE_Int *partitioning , HYPRE_Int number_vectors , HYPRE_ParVector *vector ); HYPRE_Int HYPRE_ParVectorDestroy ( HYPRE_ParVector vector ); HYPRE_Int HYPRE_ParVectorInitialize ( HYPRE_ParVector vector ); HYPRE_Int HYPRE_ParVectorRead ( MPI_Comm comm , const char *file_name , HYPRE_ParVector *vector ); HYPRE_Int HYPRE_ParVectorPrint ( HYPRE_ParVector vector , const char *file_name ); HYPRE_Int HYPRE_ParVectorSetConstantValues ( HYPRE_ParVector vector , HYPRE_Complex value ); HYPRE_Int HYPRE_ParVectorSetRandomValues ( HYPRE_ParVector vector , HYPRE_Int seed ); HYPRE_Int HYPRE_ParVectorCopy ( HYPRE_ParVector x , HYPRE_ParVector y ); HYPRE_ParVector HYPRE_ParVectorCloneShallow ( HYPRE_ParVector x ); HYPRE_Int HYPRE_ParVectorScale ( HYPRE_Complex value , HYPRE_ParVector x ); HYPRE_Int HYPRE_ParVectorAxpy ( HYPRE_Complex alpha , HYPRE_ParVector x , HYPRE_ParVector y ); HYPRE_Int HYPRE_ParVectorInnerProd ( HYPRE_ParVector x , HYPRE_ParVector y , HYPRE_Real *prod ); HYPRE_Int HYPRE_VectorToParVector ( MPI_Comm comm , HYPRE_Vector b , HYPRE_Int *partitioning , HYPRE_ParVector *vector ); /* new_commpkg.c */ HYPRE_Int hypre_PrintCommpkg ( hypre_ParCSRMatrix *A , const char *file_name ); HYPRE_Int hypre_NewCommPkgCreate_core ( MPI_Comm comm , HYPRE_Int *col_map_off_d , HYPRE_Int first_col_diag , HYPRE_Int col_start , HYPRE_Int col_end , HYPRE_Int num_cols_off_d , HYPRE_Int global_num_cols , HYPRE_Int *p_num_recvs , HYPRE_Int **p_recv_procs , HYPRE_Int **p_recv_vec_starts , HYPRE_Int *p_num_sends , HYPRE_Int **p_send_procs , HYPRE_Int **p_send_map_starts , HYPRE_Int **p_send_map_elements , hypre_IJAssumedPart *apart ); HYPRE_Int hypre_NewCommPkgCreate ( hypre_ParCSRMatrix *parcsr_A ); HYPRE_Int hypre_NewCommPkgDestroy ( hypre_ParCSRMatrix *parcsr_A ); HYPRE_Int hypre_RangeFillResponseIJDetermineRecvProcs ( void *p_recv_contact_buf , HYPRE_Int contact_size , HYPRE_Int contact_proc , void *ro , MPI_Comm comm , void **p_send_response_buf , HYPRE_Int *response_message_size ); HYPRE_Int hypre_FillResponseIJDetermineSendProcs ( void *p_recv_contact_buf , HYPRE_Int contact_size , HYPRE_Int contact_proc , void *ro , MPI_Comm comm , void **p_send_response_buf , HYPRE_Int *response_message_size ); /* par_csr_assumed_part.c */ HYPRE_Int hypre_LocateAssummedPartition ( MPI_Comm comm , HYPRE_Int row_start , HYPRE_Int row_end , HYPRE_Int global_first_row , HYPRE_Int global_num_rows , hypre_IJAssumedPart *part , HYPRE_Int myid ); HYPRE_Int hypre_ParCSRMatrixCreateAssumedPartition ( hypre_ParCSRMatrix *matrix ); HYPRE_Int hypre_AssumedPartitionDestroy ( hypre_IJAssumedPart *apart ); HYPRE_Int hypre_GetAssumedPartitionProcFromRow ( MPI_Comm comm , HYPRE_Int row , HYPRE_Int global_first_row , HYPRE_Int global_num_rows , HYPRE_Int *proc_id ); HYPRE_Int hypre_GetAssumedPartitionRowRange ( MPI_Comm comm , HYPRE_Int proc_id , HYPRE_Int global_first_row , HYPRE_Int global_num_rows , HYPRE_Int *row_start , HYPRE_Int *row_end ); HYPRE_Int hypre_ParVectorCreateAssumedPartition ( hypre_ParVector *vector ); /* par_csr_communication.c */ hypre_ParCSRCommHandle *hypre_ParCSRCommHandleCreate ( HYPRE_Int job , hypre_ParCSRCommPkg *comm_pkg , void *send_data , void *recv_data ); HYPRE_Int hypre_ParCSRCommHandleDestroy ( hypre_ParCSRCommHandle *comm_handle ); void hypre_MatvecCommPkgCreate_core ( MPI_Comm comm , HYPRE_Int *col_map_offd , HYPRE_Int first_col_diag , HYPRE_Int *col_starts , HYPRE_Int num_cols_diag , HYPRE_Int num_cols_offd , HYPRE_Int firstColDiag , HYPRE_Int *colMapOffd , HYPRE_Int data , HYPRE_Int *p_num_recvs , HYPRE_Int **p_recv_procs , HYPRE_Int **p_recv_vec_starts , HYPRE_Int *p_num_sends , HYPRE_Int **p_send_procs , HYPRE_Int **p_send_map_starts , HYPRE_Int **p_send_map_elmts ); HYPRE_Int hypre_MatvecCommPkgCreate ( hypre_ParCSRMatrix *A ); HYPRE_Int hypre_MatvecCommPkgDestroy ( hypre_ParCSRCommPkg *comm_pkg ); HYPRE_Int hypre_BuildCSRMatrixMPIDataType ( HYPRE_Int num_nonzeros , HYPRE_Int num_rows , HYPRE_Complex *a_data , HYPRE_Int *a_i , HYPRE_Int *a_j , hypre_MPI_Datatype *csr_matrix_datatype ); HYPRE_Int hypre_BuildCSRJDataType ( HYPRE_Int num_nonzeros , HYPRE_Complex *a_data , HYPRE_Int *a_j , hypre_MPI_Datatype *csr_jdata_datatype ); /* par_csr_matop.c */ void hypre_ParMatmul_RowSizes ( HYPRE_Int **C_diag_i , HYPRE_Int **C_offd_i , HYPRE_Int *A_diag_i , HYPRE_Int *A_diag_j , HYPRE_Int *A_offd_i , HYPRE_Int *A_offd_j , HYPRE_Int *B_diag_i , HYPRE_Int *B_diag_j , HYPRE_Int *B_offd_i , HYPRE_Int *B_offd_j , HYPRE_Int *B_ext_diag_i , HYPRE_Int *B_ext_diag_j , HYPRE_Int *B_ext_offd_i , HYPRE_Int *B_ext_offd_j , HYPRE_Int *map_B_to_C , HYPRE_Int *C_diag_size , HYPRE_Int *C_offd_size , HYPRE_Int num_rows_diag_A , HYPRE_Int num_cols_offd_A , HYPRE_Int allsquare , HYPRE_Int num_cols_diag_B , HYPRE_Int num_cols_offd_B , HYPRE_Int num_cols_offd_C ); hypre_ParCSRMatrix *hypre_ParMatmul ( hypre_ParCSRMatrix *A , hypre_ParCSRMatrix *B ); void hypre_ParCSRMatrixExtractBExt_Arrays ( HYPRE_Int **pB_ext_i , HYPRE_Int **pB_ext_j , HYPRE_Complex **pB_ext_data , HYPRE_Int **pB_ext_row_map , HYPRE_Int *num_nonzeros , HYPRE_Int data , HYPRE_Int find_row_map , MPI_Comm comm , hypre_ParCSRCommPkg *comm_pkg , HYPRE_Int num_cols_B , HYPRE_Int num_recvs , HYPRE_Int num_sends , HYPRE_Int first_col_diag , HYPRE_Int *row_starts , HYPRE_Int *recv_vec_starts , HYPRE_Int *send_map_starts , HYPRE_Int *send_map_elmts , HYPRE_Int *diag_i , HYPRE_Int *diag_j , HYPRE_Int *offd_i , HYPRE_Int *offd_j , HYPRE_Int *col_map_offd , HYPRE_Real *diag_data , HYPRE_Real *offd_data ); void hypre_ParCSRMatrixExtractBExt_Arrays_Overlap ( HYPRE_Int **pB_ext_i , HYPRE_Int **pB_ext_j , HYPRE_Complex **pB_ext_data , HYPRE_Int **pB_ext_row_map , HYPRE_Int *num_nonzeros , HYPRE_Int data , HYPRE_Int find_row_map , MPI_Comm comm , hypre_ParCSRCommPkg *comm_pkg , HYPRE_Int num_cols_B , HYPRE_Int num_recvs , HYPRE_Int num_sends , HYPRE_Int first_col_diag , HYPRE_Int *row_starts , HYPRE_Int *recv_vec_starts , HYPRE_Int *send_map_starts , HYPRE_Int *send_map_elmts , HYPRE_Int *diag_i , HYPRE_Int *diag_j , HYPRE_Int *offd_i , HYPRE_Int *offd_j , HYPRE_Int *col_map_offd , HYPRE_Real *diag_data , HYPRE_Real *offd_data, hypre_ParCSRCommHandle **comm_handle_idx, hypre_ParCSRCommHandle **comm_handle_data, HYPRE_Int *CF_marker, HYPRE_Int *CF_marker_offd, HYPRE_Int skip_fine, HYPRE_Int skip_same_sign ); hypre_CSRMatrix *hypre_ParCSRMatrixExtractBExt ( hypre_ParCSRMatrix *B , hypre_ParCSRMatrix *A , HYPRE_Int data ); hypre_CSRMatrix *hypre_ParCSRMatrixExtractBExt_Overlap ( hypre_ParCSRMatrix *B , hypre_ParCSRMatrix *A , HYPRE_Int data, hypre_ParCSRCommHandle **comm_handle_idx, hypre_ParCSRCommHandle **comm_handle_data, HYPRE_Int *CF_marker, HYPRE_Int *CF_marker_offd, HYPRE_Int skip_fine, HYPRE_Int skip_same_sign ); HYPRE_Int hypre_ParCSRMatrixTranspose ( hypre_ParCSRMatrix *A , hypre_ParCSRMatrix **AT_ptr , HYPRE_Int data ); void hypre_ParCSRMatrixGenSpanningTree ( hypre_ParCSRMatrix *G_csr , HYPRE_Int **indices , HYPRE_Int G_type ); void hypre_ParCSRMatrixExtractSubmatrices ( hypre_ParCSRMatrix *A_csr , HYPRE_Int *indices2 , hypre_ParCSRMatrix ***submatrices ); void hypre_ParCSRMatrixExtractRowSubmatrices ( hypre_ParCSRMatrix *A_csr , HYPRE_Int *indices2 , hypre_ParCSRMatrix ***submatrices ); HYPRE_Complex hypre_ParCSRMatrixLocalSumElts ( hypre_ParCSRMatrix *A ); HYPRE_Int hypre_ParCSRMatrixAminvDB ( hypre_ParCSRMatrix *A , hypre_ParCSRMatrix *B , HYPRE_Complex *d , hypre_ParCSRMatrix **C_ptr ); hypre_ParCSRMatrix *hypre_ParTMatmul ( hypre_ParCSRMatrix *A , hypre_ParCSRMatrix *B ); #ifdef HYPRE_USING_PERSISTENT_COMM hypre_ParCSRPersistentCommHandle * hypre_ParCSRCommPkgGetPersistentCommHandle(HYPRE_Int job, hypre_ParCSRCommPkg *comm_pkg); hypre_ParCSRPersistentCommHandle * hypre_ParCSRPersistentCommHandleCreate(HYPRE_Int job, hypre_ParCSRCommPkg *comm_pkg, void *send_data, void *recv_data); void hypre_ParCSRPersistentCommHandleDestroy(hypre_ParCSRPersistentCommHandle *comm_handle); void hypre_ParCSRPersistentCommHandleStart(hypre_ParCSRPersistentCommHandle *comm_handle); void hypre_ParCSRPersistentCommHandleWait(hypre_ParCSRPersistentCommHandle *comm_handle); #endif /* par_csr_matop_marked.c */ void hypre_ParMatmul_RowSizes_Marked ( HYPRE_Int **C_diag_i , HYPRE_Int **C_offd_i , HYPRE_Int **B_marker , HYPRE_Int *A_diag_i , HYPRE_Int *A_diag_j , HYPRE_Int *A_offd_i , HYPRE_Int *A_offd_j , HYPRE_Int *B_diag_i , HYPRE_Int *B_diag_j , HYPRE_Int *B_offd_i , HYPRE_Int *B_offd_j , HYPRE_Int *B_ext_diag_i , HYPRE_Int *B_ext_diag_j , HYPRE_Int *B_ext_offd_i , HYPRE_Int *B_ext_offd_j , HYPRE_Int *map_B_to_C , HYPRE_Int *C_diag_size , HYPRE_Int *C_offd_size , HYPRE_Int num_rows_diag_A , HYPRE_Int num_cols_offd_A , HYPRE_Int allsquare , HYPRE_Int num_cols_diag_B , HYPRE_Int num_cols_offd_B , HYPRE_Int num_cols_offd_C , HYPRE_Int *CF_marker , HYPRE_Int *dof_func , HYPRE_Int *dof_func_offd ); hypre_ParCSRMatrix *hypre_ParMatmul_FC ( hypre_ParCSRMatrix *A , hypre_ParCSRMatrix *P , HYPRE_Int *CF_marker , HYPRE_Int *dof_func , HYPRE_Int *dof_func_offd ); void hypre_ParMatScaleDiagInv_F ( hypre_ParCSRMatrix *C , hypre_ParCSRMatrix *A , HYPRE_Complex weight , HYPRE_Int *CF_marker ); hypre_ParCSRMatrix *hypre_ParMatMinus_F ( hypre_ParCSRMatrix *P , hypre_ParCSRMatrix *C , HYPRE_Int *CF_marker ); void hypre_ParCSRMatrixZero_F ( hypre_ParCSRMatrix *P , HYPRE_Int *CF_marker ); void hypre_ParCSRMatrixCopy_C ( hypre_ParCSRMatrix *P , hypre_ParCSRMatrix *C , HYPRE_Int *CF_marker ); void hypre_ParCSRMatrixDropEntries ( hypre_ParCSRMatrix *C , hypre_ParCSRMatrix *P , HYPRE_Int *CF_marker ); /* par_csr_matrix.c */ hypre_ParCSRMatrix *hypre_ParCSRMatrixCreate ( MPI_Comm comm , HYPRE_Int global_num_rows , HYPRE_Int global_num_cols , HYPRE_Int *row_starts , HYPRE_Int *col_starts , HYPRE_Int num_cols_offd , HYPRE_Int num_nonzeros_diag , HYPRE_Int num_nonzeros_offd ); HYPRE_Int hypre_ParCSRMatrixDestroy ( hypre_ParCSRMatrix *matrix ); HYPRE_Int hypre_ParCSRMatrixInitialize ( hypre_ParCSRMatrix *matrix ); HYPRE_Int hypre_ParCSRMatrixSetNumNonzeros ( hypre_ParCSRMatrix *matrix ); HYPRE_Int hypre_ParCSRMatrixSetDNumNonzeros ( hypre_ParCSRMatrix *matrix ); HYPRE_Int hypre_ParCSRMatrixSetDataOwner ( hypre_ParCSRMatrix *matrix , HYPRE_Int owns_data ); HYPRE_Int hypre_ParCSRMatrixSetRowStartsOwner ( hypre_ParCSRMatrix *matrix , HYPRE_Int owns_row_starts ); HYPRE_Int hypre_ParCSRMatrixSetColStartsOwner ( hypre_ParCSRMatrix *matrix , HYPRE_Int owns_col_starts ); hypre_ParCSRMatrix *hypre_ParCSRMatrixRead ( MPI_Comm comm , const char *file_name ); HYPRE_Int hypre_ParCSRMatrixPrint ( hypre_ParCSRMatrix *matrix , const char *file_name ); HYPRE_Int hypre_ParCSRMatrixPrintIJ ( const hypre_ParCSRMatrix *matrix , const HYPRE_Int base_i , const HYPRE_Int base_j , const char *filename ); HYPRE_Int hypre_ParCSRMatrixReadIJ ( MPI_Comm comm , const char *filename , HYPRE_Int *base_i_ptr , HYPRE_Int *base_j_ptr , hypre_ParCSRMatrix **matrix_ptr ); HYPRE_Int hypre_ParCSRMatrixGetLocalRange ( hypre_ParCSRMatrix *matrix , HYPRE_Int *row_start , HYPRE_Int *row_end , HYPRE_Int *col_start , HYPRE_Int *col_end ); HYPRE_Int hypre_ParCSRMatrixGetRow ( hypre_ParCSRMatrix *mat , HYPRE_Int row , HYPRE_Int *size , HYPRE_Int **col_ind , HYPRE_Complex **values ); HYPRE_Int hypre_ParCSRMatrixRestoreRow ( hypre_ParCSRMatrix *matrix , HYPRE_Int row , HYPRE_Int *size , HYPRE_Int **col_ind , HYPRE_Complex **values ); hypre_ParCSRMatrix *hypre_CSRMatrixToParCSRMatrix ( MPI_Comm comm , hypre_CSRMatrix *A , HYPRE_Int *row_starts , HYPRE_Int *col_starts ); HYPRE_Int GenerateDiagAndOffd ( hypre_CSRMatrix *A , hypre_ParCSRMatrix *matrix , HYPRE_Int first_col_diag , HYPRE_Int last_col_diag ); hypre_CSRMatrix *hypre_MergeDiagAndOffd ( hypre_ParCSRMatrix *par_matrix ); hypre_CSRMatrix *hypre_ParCSRMatrixToCSRMatrixAll ( hypre_ParCSRMatrix *par_matrix ); HYPRE_Int hypre_ParCSRMatrixCopy ( hypre_ParCSRMatrix *A , hypre_ParCSRMatrix *B , HYPRE_Int copy_data ); HYPRE_Int hypre_FillResponseParToCSRMatrix ( void *p_recv_contact_buf , HYPRE_Int contact_size , HYPRE_Int contact_proc , void *ro , MPI_Comm comm , void **p_send_response_buf , HYPRE_Int *response_message_size ); hypre_ParCSRMatrix *hypre_ParCSRMatrixCompleteClone ( hypre_ParCSRMatrix *A ); hypre_ParCSRMatrix *hypre_ParCSRMatrixUnion ( hypre_ParCSRMatrix *A , hypre_ParCSRMatrix *B ); /* par_csr_matvec.c */ // y = alpha*A*x + beta*b HYPRE_Int hypre_ParCSRMatrixMatvecOutOfPlace ( HYPRE_Complex alpha , hypre_ParCSRMatrix *A , hypre_ParVector *x , HYPRE_Complex beta , hypre_ParVector *b, hypre_ParVector *y ); // y = alpha*A*x + beta*y HYPRE_Int hypre_ParCSRMatrixMatvec ( HYPRE_Complex alpha , hypre_ParCSRMatrix *A , hypre_ParVector *x , HYPRE_Complex beta , hypre_ParVector *y ); HYPRE_Int hypre_ParCSRMatrixMatvecT ( HYPRE_Complex alpha , hypre_ParCSRMatrix *A , hypre_ParVector *x , HYPRE_Complex beta , hypre_ParVector *y ); HYPRE_Int hypre_ParCSRMatrixMatvec_FF ( HYPRE_Complex alpha , hypre_ParCSRMatrix *A , hypre_ParVector *x , HYPRE_Complex beta , hypre_ParVector *y , HYPRE_Int *CF_marker , HYPRE_Int fpt ); /* par_vector.c */ hypre_ParVector *hypre_ParVectorCreate ( MPI_Comm comm , HYPRE_Int global_size , HYPRE_Int *partitioning ); hypre_ParVector *hypre_ParMultiVectorCreate ( MPI_Comm comm , HYPRE_Int global_size , HYPRE_Int *partitioning , HYPRE_Int num_vectors ); HYPRE_Int hypre_ParVectorDestroy ( hypre_ParVector *vector ); HYPRE_Int hypre_ParVectorInitialize ( hypre_ParVector *vector ); HYPRE_Int hypre_ParVectorSetDataOwner ( hypre_ParVector *vector , HYPRE_Int owns_data ); HYPRE_Int hypre_ParVectorSetPartitioningOwner ( hypre_ParVector *vector , HYPRE_Int owns_partitioning ); HYPRE_Int hypre_ParVectorSetNumVectors ( hypre_ParVector *vector , HYPRE_Int num_vectors ); hypre_ParVector *hypre_ParVectorRead ( MPI_Comm comm , const char *file_name ); HYPRE_Int hypre_ParVectorPrint ( hypre_ParVector *vector , const char *file_name ); HYPRE_Int hypre_ParVectorSetConstantValues ( hypre_ParVector *v , HYPRE_Complex value ); HYPRE_Int hypre_ParVectorSetRandomValues ( hypre_ParVector *v , HYPRE_Int seed ); HYPRE_Int hypre_ParVectorCopy ( hypre_ParVector *x , hypre_ParVector *y ); hypre_ParVector *hypre_ParVectorCloneShallow ( hypre_ParVector *x ); HYPRE_Int hypre_ParVectorScale ( HYPRE_Complex alpha , hypre_ParVector *y ); HYPRE_Int hypre_ParVectorAxpy ( HYPRE_Complex alpha , hypre_ParVector *x , hypre_ParVector *y ); HYPRE_Real hypre_ParVectorInnerProd ( hypre_ParVector *x , hypre_ParVector *y ); hypre_ParVector *hypre_VectorToParVector ( MPI_Comm comm , hypre_Vector *v , HYPRE_Int *vec_starts ); hypre_Vector *hypre_ParVectorToVectorAll ( hypre_ParVector *par_v ); HYPRE_Int hypre_ParVectorPrintIJ ( hypre_ParVector *vector , HYPRE_Int base_j , const char *filename ); HYPRE_Int hypre_ParVectorReadIJ ( MPI_Comm comm , const char *filename , HYPRE_Int *base_j_ptr , hypre_ParVector **vector_ptr ); HYPRE_Int hypre_FillResponseParToVectorAll ( void *p_recv_contact_buf , HYPRE_Int contact_size , HYPRE_Int contact_proc , void *ro , MPI_Comm comm , void **p_send_response_buf , HYPRE_Int *response_message_size ); HYPRE_Complex hypre_ParVectorLocalSumElts ( hypre_ParVector *vector ); #ifdef __cplusplus } #endif #endif
31,325
60.303327
812
h
AMG
AMG-master/parcsr_mv/headers.h
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ #include <stdlib.h> #include <stdio.h> #include <math.h> #include "HYPRE.h" #include "parcsr_mv.h"
1,030
34.551724
81
h
AMG
AMG-master/parcsr_mv/new_commpkg.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /*---------------------------------------------------- * Communication package that uses an assumed partition * AHB 6/04 *-----------------------------------------------------*/ #include "_hypre_parcsr_mv.h" /* some debugging tools*/ #define mydebug 0 /*==========================================================================*/ HYPRE_Int hypre_PrintCommpkg(hypre_ParCSRMatrix *A, const char *file_name) { HYPRE_Int num_sends, num_recvs; HYPRE_Int *recv_vec_starts, *recv_procs; HYPRE_Int *send_map_starts, *send_map_elements, *send_procs; HYPRE_Int i; HYPRE_Int my_id; MPI_Comm comm; hypre_ParCSRCommPkg *comm_pkg; char new_file[80]; FILE *fp; comm_pkg = hypre_ParCSRMatrixCommPkg(A); comm = hypre_ParCSRCommPkgComm(comm_pkg); num_recvs = hypre_ParCSRCommPkgNumRecvs(comm_pkg); recv_procs = hypre_ParCSRCommPkgRecvProcs(comm_pkg); recv_vec_starts = hypre_ParCSRCommPkgRecvVecStarts(comm_pkg); num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); send_procs = hypre_ParCSRCommPkgSendProcs(comm_pkg); send_map_starts = hypre_ParCSRCommPkgSendMapStarts(comm_pkg); send_map_elements = hypre_ParCSRCommPkgSendMapElmts(comm_pkg); hypre_MPI_Comm_rank(comm, &my_id); hypre_sprintf(new_file,"%s.%d",file_name,my_id); fp = fopen(new_file, "w"); hypre_fprintf(fp, "num_recvs = %d\n", num_recvs); for (i=0; i < num_recvs; i++) { hypre_fprintf(fp, "recv_proc [start, end] = %d [%d, %d] \n", recv_procs[i], recv_vec_starts[i], recv_vec_starts[i+1]-1); } hypre_fprintf(fp, "num_sends = %d\n", num_sends); for (i=0; i < num_sends; i++) { hypre_fprintf(fp, "send_proc [start, end] = %d [%d, %d] \n", send_procs[i], send_map_starts[i], send_map_starts[i+1]-1); } for (i = 0; i< send_map_starts[num_sends]; i++) { hypre_fprintf(fp, "send_map_elements (%d) = %d\n", i, send_map_elements[i]); } fclose(fp); return hypre_error_flag; } /*------------------------------------------------------------------ * hypre_NewCommPkgCreate_core * * This does the work for hypre_NewCommPkgCreate - we have to split it * off so that it can also be used for block matrices. *--------------------------------------------------------------------------*/ HYPRE_Int hypre_NewCommPkgCreate_core( /* input args: */ MPI_Comm comm, HYPRE_Int *col_map_off_d, HYPRE_Int first_col_diag, HYPRE_Int col_start, HYPRE_Int col_end, HYPRE_Int num_cols_off_d, HYPRE_Int global_num_cols, /* pointers to output args: */ HYPRE_Int *p_num_recvs, HYPRE_Int **p_recv_procs, HYPRE_Int **p_recv_vec_starts, HYPRE_Int *p_num_sends, HYPRE_Int **p_send_procs, HYPRE_Int ** p_send_map_starts, HYPRE_Int **p_send_map_elements, hypre_IJAssumedPart *apart) { HYPRE_Int num_procs, myid; HYPRE_Int j, i; HYPRE_Int range_start, range_end; HYPRE_Int size; HYPRE_Int count; HYPRE_Int num_recvs, *recv_procs = NULL, *recv_vec_starts=NULL; HYPRE_Int tmp_id, prev_id; HYPRE_Int num_sends; HYPRE_Int ex_num_contacts, *ex_contact_procs=NULL, *ex_contact_vec_starts=NULL; HYPRE_Int *ex_contact_buf=NULL; HYPRE_Int num_ranges, upper_bound; HYPRE_Int *response_buf = NULL, *response_buf_starts=NULL; HYPRE_Int max_response_size; hypre_DataExchangeResponse response_obj1, response_obj2; hypre_ProcListElements send_proc_obj; #if mydebug HYPRE_Int tmp_int, index; #endif hypre_MPI_Comm_size(comm, &num_procs ); hypre_MPI_Comm_rank(comm, &myid ); #if mydebug hypre_printf("myid = %i, my assumed local range: [%i, %i]\n", myid, apart->row_start, apart->row_end); for (i=0; i<apart.length; i++) { hypre_printf("myid = %d, proc %d owns assumed partition range = [%d, %d]\n", myid, apart->proc_list[i], apart->row_start_list[i], apart->row_end_list[i]); } hypre_printf("myid = %d, length of apart = %d\n", myid, apart->length); #endif /*----------------------------------------------------------- * Everyone knows where their assumed range is located * (because of the assumed partition object (apart). * For the comm. package, each proc must know it's receive * procs (who it will receive data from and how much data) * and its send procs * (who it will send data to) and the indices of the elements * to be sent. This is based on the non-zero * entries in its rows. Each proc should know this from the user. *-----------------------------------------------------------*/ /*------------------------------------------------------------ * First, get the receive processors * each par_csr matrix will have a certain number of columns * (num_cols_off_d) given in col_map_offd[] for which it needs * data from another processor. * *------------------------------------------------------------*/ /*calculate the assumed receive processors*/ /* need to populate num_recvs, *recv_procs, and *recv_vec_starts (correlates to starts in col_map_off_d for recv_procs) for the comm. package*/ /*create contact information*/ ex_num_contacts = 0; /*estimate the storage needed*/ if (num_cols_off_d > 0 && (apart->row_end - apart->row_start) > 0 ) { size = col_map_off_d[num_cols_off_d-1] - col_map_off_d[0]; size = (size/(apart->row_end - apart->row_start)) + 2; } else { size = 0; } /*we will contact each with a range of cols that we need*/ /* it is ok to contact yourself - because then there doesn't need to be separate code */ ex_contact_procs = hypre_CTAlloc(HYPRE_Int, size); ex_contact_vec_starts = hypre_CTAlloc(HYPRE_Int, size+1); ex_contact_buf = hypre_CTAlloc(HYPRE_Int, size*2); range_end = -1; for (i=0; i< num_cols_off_d; i++) { if (col_map_off_d[i] > range_end) { hypre_GetAssumedPartitionProcFromRow(comm, col_map_off_d[i], 0, global_num_cols, &tmp_id); if (ex_num_contacts == size) /*need more space? */ { size += 20; ex_contact_procs = hypre_TReAlloc(ex_contact_procs, HYPRE_Int, size); ex_contact_vec_starts = hypre_TReAlloc(ex_contact_vec_starts, HYPRE_Int, size+1); ex_contact_buf = hypre_TReAlloc(ex_contact_buf, HYPRE_Int, size*2); } /* end of prev. range */ if (ex_num_contacts > 0) ex_contact_buf[ex_num_contacts*2 - 1] = col_map_off_d[i-1]; /*start new range*/ ex_contact_procs[ex_num_contacts] = tmp_id; ex_contact_vec_starts[ex_num_contacts] = ex_num_contacts*2; ex_contact_buf[ex_num_contacts*2] = col_map_off_d[i]; ex_num_contacts++; hypre_GetAssumedPartitionRowRange(comm, tmp_id, 0, global_num_cols, &range_start, &range_end); } } /*finish the starts*/ ex_contact_vec_starts[ex_num_contacts] = ex_num_contacts*2; /*finish the last range*/ if (ex_num_contacts > 0) ex_contact_buf[ex_num_contacts*2 - 1] = col_map_off_d[num_cols_off_d-1]; /*don't allocate space for responses */ /*create response object*/ response_obj1.fill_response = hypre_RangeFillResponseIJDetermineRecvProcs; response_obj1.data1 = apart; /* this is necessary so we can fill responses*/ response_obj1.data2 = NULL; max_response_size = 6; /* 6 means we can fit 3 ranges*/ hypre_DataExchangeList(ex_num_contacts, ex_contact_procs, ex_contact_buf, ex_contact_vec_starts, sizeof(HYPRE_Int), sizeof(HYPRE_Int), &response_obj1, max_response_size, 1, comm, (void**) &response_buf, &response_buf_starts); /*now create recv_procs[] and recv_vec_starts[] and num_recvs from the complete data in response_buf - this array contains a proc_id followed by an upper bound for the range. */ /*initialize */ num_recvs = 0; size = ex_num_contacts+20; /* num of recv procs should be roughly similar size to number of contacts - add a buffer of 20*/ recv_procs = hypre_CTAlloc(HYPRE_Int, size); recv_vec_starts = hypre_CTAlloc(HYPRE_Int, size+1); recv_vec_starts[0] = 0; /*how many ranges were returned?*/ num_ranges = response_buf_starts[ex_num_contacts]; num_ranges = num_ranges/2; prev_id = -1; j = 0; count = 0; /* loop through ranges */ for (i=0; i<num_ranges; i++) { upper_bound = response_buf[i*2+1]; count = 0; /* loop through off_d entries - counting how many are in the range */ while (j < num_cols_off_d && col_map_off_d[j] <= upper_bound) { j++; count++; } if (count > 0) { /*add the range if the proc id != myid*/ tmp_id = response_buf[i*2]; if (tmp_id != myid) { if (tmp_id != prev_id) /*increment the number of recvs */ { /*check size of recv buffers*/ if (num_recvs == size) { size+=20; recv_procs = hypre_TReAlloc(recv_procs,HYPRE_Int, size); recv_vec_starts = hypre_TReAlloc(recv_vec_starts,HYPRE_Int, size+1); } recv_vec_starts[num_recvs+1] = j; /*the new start is at this element*/ recv_procs[num_recvs] = tmp_id; /*add the new processor*/ num_recvs++; } else { /*same processor - just change the vec starts*/ recv_vec_starts[num_recvs] = j; /*the new start is at this element*/ } } prev_id = tmp_id; } } #if mydebug for (i=0; i < num_recvs; i++) { hypre_printf("myid = %d, recv proc = %d, vec_starts = [%d : %d]\n", myid, recv_procs[i], recv_vec_starts[i],recv_vec_starts[i+1]-1); } #endif /*------------------------------------------------------------ * determine the send processors * each processor contacts its recv procs to let them * know they are a send processor * *-------------------------------------------------------------*/ /* the contact information is the recv_processor infomation - so nothing more to do to generate contact info*/ /* the response we expect is just a confirmation*/ hypre_TFree(response_buf); hypre_TFree(response_buf_starts); response_buf = NULL; response_buf_starts = NULL; /*build the response object*/ /*estimate for inital storage allocation that we send to as many procs as we recv from + pad by 5*/ send_proc_obj.length = 0; send_proc_obj.storage_length = num_recvs + 5; send_proc_obj.id = hypre_CTAlloc(HYPRE_Int, send_proc_obj.storage_length); send_proc_obj.vec_starts = hypre_CTAlloc(HYPRE_Int, send_proc_obj.storage_length + 1); send_proc_obj.vec_starts[0] = 0; send_proc_obj.element_storage_length = num_cols_off_d; send_proc_obj.elements = hypre_CTAlloc(HYPRE_Int, send_proc_obj.element_storage_length); response_obj2.fill_response = hypre_FillResponseIJDetermineSendProcs; response_obj2.data1 = NULL; response_obj2.data2 = &send_proc_obj; /*this is where we keep info from contacts*/ max_response_size = 0; hypre_DataExchangeList(num_recvs, recv_procs, col_map_off_d, recv_vec_starts, sizeof(HYPRE_Int), sizeof(HYPRE_Int), &response_obj2, max_response_size, 2, comm, (void **) &response_buf, &response_buf_starts); num_sends = send_proc_obj.length; /*send procs are in send_proc_object.id */ /*send proc starts are in send_proc_obj.vec_starts */ #if mydebug hypre_printf("myid = %d, num_sends = %d\n", myid, num_sends); for (i=0; i < num_sends; i++) { tmp_int = send_proc_obj.vec_starts[i+1] - send_proc_obj.vec_starts[i]; index = send_proc_obj.vec_starts[i]; for (j=0; j< tmp_int; j++) { hypre_printf("myid = %d, send proc = %d, send element = %d\n",myid, send_proc_obj.id[i],send_proc_obj.elements[index+j]); } } #endif /*----------------------------------------------------------- * We need to sort the send procs and send elements (to produce * the same result as with the standard comm package) * 11/07/05 *-----------------------------------------------------------*/ { HYPRE_Int *orig_order; HYPRE_Int *orig_send_map_starts; HYPRE_Int *orig_send_elements; HYPRE_Int ct, sz, pos; orig_order = hypre_CTAlloc(HYPRE_Int, num_sends); orig_send_map_starts = hypre_CTAlloc(HYPRE_Int, num_sends+1); orig_send_elements = hypre_CTAlloc(HYPRE_Int, send_proc_obj.vec_starts[num_sends]); orig_send_map_starts[0] = 0; /* copy send map starts and elements */ for (i=0; i< num_sends; i++) { orig_order[i] = i; orig_send_map_starts[i+1] = send_proc_obj.vec_starts[i+1]; } for (i=0; i< send_proc_obj.vec_starts[num_sends]; i++) { orig_send_elements[i] = send_proc_obj.elements[i]; } /* sort processor ids - keep track of original order */ hypre_qsort2i( send_proc_obj.id, orig_order, 0, num_sends-1 ); /* now rearrange vec starts and send elements to correspond to proc ids */ ct = 0; for (i=0; i< num_sends; i++) { pos = orig_order[i]; sz = orig_send_map_starts[pos + 1] - orig_send_map_starts[pos]; send_proc_obj.vec_starts[i+1] = ct + sz; for (j = 0; j< sz; j++) { send_proc_obj.elements[ct +j] = orig_send_elements[orig_send_map_starts[pos]+j]; } ct += sz; } /* clean up */ hypre_TFree(orig_order); hypre_TFree(orig_send_elements); hypre_TFree(orig_send_map_starts); } /*----------------------------------------------------------- * Return output info for setting up the comm package *-----------------------------------------------------------*/ if (!num_recvs) { hypre_TFree(recv_procs); recv_procs = NULL; } if (!num_sends) { hypre_TFree(send_proc_obj.id); send_proc_obj.id = NULL; } *p_num_recvs = num_recvs; *p_recv_procs = recv_procs; *p_recv_vec_starts = recv_vec_starts; *p_num_sends = num_sends; *p_send_procs = send_proc_obj.id; *p_send_map_starts = send_proc_obj.vec_starts; /*send map elements have global index - need local instead*/ if (num_sends) { for (i=0; i<send_proc_obj.vec_starts[num_sends]; i++) { send_proc_obj.elements[i] -= first_col_diag; } } else { hypre_TFree(send_proc_obj.elements); send_proc_obj.elements = NULL; } *p_send_map_elements = send_proc_obj.elements; /*----------------------------------------------------------- * Clean up *-----------------------------------------------------------*/ if(ex_contact_procs) hypre_TFree(ex_contact_procs); if(ex_contact_vec_starts) hypre_TFree(ex_contact_vec_starts); hypre_TFree(ex_contact_buf); if(response_buf) hypre_TFree(response_buf); if(response_buf_starts) hypre_TFree(response_buf_starts); /* don't free send_proc_obj.id,send_proc_obj.vec_starts,send_proc_obj.elements; recv_procs, recv_vec_starts. These are aliased to the comm package and will be destroyed there */ return hypre_error_flag; } #if 0 /* now this is incorporated into the std comm pkg routine - it is not deleted here in in case driver_commpkg.c is to be used for testing commpkg setups */ /*------------------------------------------------------------------ * hypre_NewCommPkgCreate * this is an alternate way of constructing the comm package * (compare to hypre_MatvecCommPkgCreate() in par_csr_communication.c * that should be more scalable *-------------------------------------------------------------------*/ HYPRE_Int hypre_NewCommPkgCreate( hypre_ParCSRMatrix *parcsr_A) { HYPRE_Int row_start=0, row_end=0, col_start = 0, col_end = 0; HYPRE_Int num_recvs, *recv_procs, *recv_vec_starts; HYPRE_Int num_sends, *send_procs, *send_map_starts; HYPRE_Int *send_map_elements; HYPRE_Int num_cols_off_d; HYPRE_Int *col_map_off_d; HYPRE_Int first_col_diag; HYPRE_Int global_num_cols; MPI_Comm comm; hypre_ParCSRCommPkg *comm_pkg; hypre_IJAssumedPart *apart; /*----------------------------------------------------------- * get parcsr_A information *----------------------------------------------------------*/ hypre_ParCSRMatrixGetLocalRange( parcsr_A, &row_start, &row_end , &col_start, &col_end ); col_map_off_d = hypre_ParCSRMatrixColMapOffd(parcsr_A); num_cols_off_d = hypre_CSRMatrixNumCols(hypre_ParCSRMatrixOffd(parcsr_A)); global_num_cols = hypre_ParCSRMatrixGlobalNumCols(parcsr_A); comm = hypre_ParCSRMatrixComm(parcsr_A); first_col_diag = hypre_ParCSRMatrixFirstColDiag(parcsr_A); /* Create the assumed partition */ if (hypre_ParCSRMatrixAssumedPartition(parcsr_A) == NULL) { hypre_ParCSRMatrixCreateAssumedPartition(parcsr_A); } apart = hypre_ParCSRMatrixAssumedPartition(parcsr_A); /*----------------------------------------------------------- * get commpkg info information *----------------------------------------------------------*/ hypre_NewCommPkgCreate_core( comm, col_map_off_d, first_col_diag, col_start, col_end, num_cols_off_d, global_num_cols, &num_recvs, &recv_procs, &recv_vec_starts, &num_sends, &send_procs, &send_map_starts, &send_map_elements, apart); if (!num_recvs) { hypre_TFree(recv_procs); recv_procs = NULL; } if (!num_sends) { hypre_TFree(send_procs); hypre_TFree(send_map_elements); send_procs = NULL; send_map_elements = NULL; } /*----------------------------------------------------------- * setup commpkg *----------------------------------------------------------*/ comm_pkg = hypre_CTAlloc(hypre_ParCSRCommPkg, 1); hypre_ParCSRCommPkgComm(comm_pkg) = comm; hypre_ParCSRCommPkgNumRecvs(comm_pkg) = num_recvs; hypre_ParCSRCommPkgRecvProcs(comm_pkg) = recv_procs; hypre_ParCSRCommPkgRecvVecStarts(comm_pkg) = recv_vec_starts; hypre_ParCSRCommPkgNumSends(comm_pkg) = num_sends; hypre_ParCSRCommPkgSendProcs(comm_pkg) = send_procs; hypre_ParCSRCommPkgSendMapStarts(comm_pkg) = send_map_starts; hypre_ParCSRCommPkgSendMapElmts(comm_pkg) = send_map_elements; hypre_ParCSRMatrixCommPkg(parcsr_A) = comm_pkg; return hypre_error_flag; } #endif /*------------------------------------------------------------------ * hypre_NewCommPkgDestroy * Destroy the comm package *------------------------------------------------------------------*/ HYPRE_Int hypre_NewCommPkgDestroy(hypre_ParCSRMatrix *parcsr_A) { hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(parcsr_A); /*even if num_sends and num_recvs = 0, storage may have been allocated */ if (hypre_ParCSRCommPkgSendProcs(comm_pkg)) { hypre_TFree(hypre_ParCSRCommPkgSendProcs(comm_pkg)); } if (hypre_ParCSRCommPkgSendMapElmts(comm_pkg)) { hypre_TFree(hypre_ParCSRCommPkgSendMapElmts(comm_pkg)); } if (hypre_ParCSRCommPkgSendMapStarts(comm_pkg)) { hypre_TFree(hypre_ParCSRCommPkgSendMapStarts(comm_pkg)); } if (hypre_ParCSRCommPkgRecvProcs(comm_pkg)) { hypre_TFree(hypre_ParCSRCommPkgRecvProcs(comm_pkg)); } if (hypre_ParCSRCommPkgRecvVecStarts(comm_pkg)) { hypre_TFree(hypre_ParCSRCommPkgRecvVecStarts(comm_pkg)); } hypre_TFree(comm_pkg); hypre_ParCSRMatrixCommPkg(parcsr_A) = NULL; /*this gets freed again in destroy parscr since there are two comm packages now*/ return hypre_error_flag; } /*-------------------------------------------------------------------- * hypre_RangeFillResponseIJDetermineRecvProcs * Fill response function for determining the recv. processors * data exchange *--------------------------------------------------------------------*/ HYPRE_Int hypre_RangeFillResponseIJDetermineRecvProcs(void *p_recv_contact_buf, HYPRE_Int contact_size, HYPRE_Int contact_proc, void *ro, MPI_Comm comm, void **p_send_response_buf, HYPRE_Int *response_message_size) { HYPRE_Int myid, tmp_id, row_end; HYPRE_Int j; HYPRE_Int row_val, index, size; HYPRE_Int *send_response_buf = (HYPRE_Int *) *p_send_response_buf; HYPRE_Int *recv_contact_buf = (HYPRE_Int * ) p_recv_contact_buf; hypre_DataExchangeResponse *response_obj = (hypre_DataExchangeResponse*)ro; hypre_IJAssumedPart *part = (hypre_IJAssumedPart*)response_obj->data1; HYPRE_Int overhead = response_obj->send_response_overhead; /*------------------------------------------------------------------- * we are getting a range of off_d entries - need to see if we own them * or how many ranges to send back - send back * with format [proc_id end_row proc_id #end_row proc_id #end_row etc...]. *----------------------------------------------------------------------*/ hypre_MPI_Comm_rank(comm, &myid ); /* populate send_response_buf */ index = 0; /*count entries in send_response_buf*/ j = 0; /*marks which partition of the assumed partition we are in */ row_val = recv_contact_buf[0]; /*beginning of range*/ row_end = part->row_end_list[part->sort_index[j]]; tmp_id = part->proc_list[part->sort_index[j]]; /*check storage in send_buf for adding the ranges */ size = 2*(part->length); if ( response_obj->send_response_storage < size ) { response_obj->send_response_storage = hypre_max(size, 20); send_response_buf = hypre_TReAlloc( send_response_buf, HYPRE_Int, response_obj->send_response_storage + overhead ); *p_send_response_buf = send_response_buf; /* needed when using ReAlloc */ } while (row_val > row_end) /*which partition to start in */ { j++; row_end = part->row_end_list[part->sort_index[j]]; tmp_id = part->proc_list[part->sort_index[j]]; } /*add this range*/ send_response_buf[index++] = tmp_id; send_response_buf[index++] = row_end; j++; /*increase j to look in next partition */ /*any more? - now compare with end of range value*/ row_val = recv_contact_buf[1]; /*end of range*/ while ( j < part->length && row_val > row_end ) { row_end = part->row_end_list[part->sort_index[j]]; tmp_id = part->proc_list[part->sort_index[j]]; send_response_buf[index++] = tmp_id; send_response_buf[index++] = row_end; j++; } *response_message_size = index; *p_send_response_buf = send_response_buf; return hypre_error_flag; } /*-------------------------------------------------------------------- * hypre_FillResponseIJDetermineSendProcs * Fill response function for determining the send processors * data exchange *--------------------------------------------------------------------*/ HYPRE_Int hypre_FillResponseIJDetermineSendProcs(void *p_recv_contact_buf, HYPRE_Int contact_size, HYPRE_Int contact_proc, void *ro, MPI_Comm comm, void **p_send_response_buf, HYPRE_Int *response_message_size ) { HYPRE_Int myid; HYPRE_Int i, index, count, elength; HYPRE_Int *recv_contact_buf = (HYPRE_Int * ) p_recv_contact_buf; hypre_DataExchangeResponse *response_obj = (hypre_DataExchangeResponse*)ro; hypre_ProcListElements *send_proc_obj = (hypre_ProcListElements*)response_obj->data2; hypre_MPI_Comm_rank(comm, &myid ); /*check to see if we need to allocate more space in send_proc_obj for ids*/ if (send_proc_obj->length == send_proc_obj->storage_length) { send_proc_obj->storage_length +=20; /*add space for 20 more processors*/ send_proc_obj->id = hypre_TReAlloc(send_proc_obj->id,HYPRE_Int, send_proc_obj->storage_length); send_proc_obj->vec_starts = hypre_TReAlloc(send_proc_obj->vec_starts,HYPRE_Int, send_proc_obj->storage_length + 1); } /*initialize*/ count = send_proc_obj->length; index = send_proc_obj->vec_starts[count]; /*this is the number of elements*/ /*send proc*/ send_proc_obj->id[count] = contact_proc; /*do we need more storage for the elements?*/ if (send_proc_obj->element_storage_length < index + contact_size) { elength = hypre_max(contact_size, 50); elength += index; send_proc_obj->elements = hypre_TReAlloc(send_proc_obj->elements, HYPRE_Int, elength); send_proc_obj->element_storage_length = elength; } /*populate send_proc_obj*/ for (i=0; i< contact_size; i++) { send_proc_obj->elements[index++] = recv_contact_buf[i]; } send_proc_obj->vec_starts[count+1] = index; send_proc_obj->length++; /*output - no message to return (confirmation) */ *response_message_size = 0; return hypre_error_flag; }
27,350
30.914819
126
c
AMG
AMG-master/parcsr_mv/new_commpkg.h
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ #ifndef hypre_NEW_COMMPKG #define hypre_NEW_COMMPKG typedef struct { HYPRE_Int length; HYPRE_Int storage_length; HYPRE_Int *id; HYPRE_Int *vec_starts; HYPRE_Int element_storage_length; HYPRE_Int *elements; HYPRE_Real *d_elements; /* Is this used anywhere? */ void *v_elements; } hypre_ProcListElements; #endif /* hypre_NEW_COMMPKG */
1,343
36.333333
81
h
AMG
AMG-master/parcsr_mv/par_csr_assumed_part.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /*---------------------------------------------------- * Functions for the IJ assumed partition * (Some of these were formerly in new_commpkg.c) * AHB 4/06 *-----------------------------------------------------*/ #include "_hypre_parcsr_mv.h" /* This is used only in the function below */ #define CONTACT(a,b) (contact_list[(a)*3+(b)]) /*-------------------------------------------------------------------- * hypre_LocateAssummedPartition * Reconcile assumed partition with actual partition. Essentially * each processor ends of with a partition of its assumed partition. *--------------------------------------------------------------------*/ HYPRE_Int hypre_LocateAssummedPartition(MPI_Comm comm, HYPRE_Int row_start, HYPRE_Int row_end, HYPRE_Int global_first_row, HYPRE_Int global_num_rows, hypre_IJAssumedPart *part, HYPRE_Int myid) { HYPRE_Int i; HYPRE_Int *contact_list; HYPRE_Int contact_list_length, contact_list_storage; HYPRE_Int contact_row_start[2], contact_row_end[2], contact_ranges; HYPRE_Int owner_start, owner_end; HYPRE_Int tmp_row_start, tmp_row_end, complete; /*HYPRE_Int locate_row_start[2]; */ HYPRE_Int locate_ranges; HYPRE_Int locate_row_count, rows_found; HYPRE_Int tmp_range[2]; HYPRE_Int *si, *sortme; const HYPRE_Int flag1 = 17; hypre_MPI_Request *requests; hypre_MPI_Status status0, *statuses; /*----------------------------------------------------------- * Contact ranges - * which rows do I have that others are assumed responsible for? * (at most two ranges - maybe none) *-----------------------------------------------------------*/ contact_row_start[0]=0; contact_row_end[0]=0; contact_row_start[1]=0; contact_row_end[1]=0; contact_ranges = 0; if (row_start <= row_end ) { /*must own at least one row*/ if ( part->row_end < row_start || row_end < part->row_start ) { /*no overlap - so all of my rows and only one range*/ contact_row_start[0] = row_start; contact_row_end[0] = row_end; contact_ranges++; } else /* the two regions overlap - so one or two ranges */ { /* check for contact rows on the low end of the local range */ if (row_start < part->row_start) { contact_row_start[0] = row_start; contact_row_end[0] = part->row_start - 1; contact_ranges++; } if (part->row_end < row_end) /* check the high end */ { if (contact_ranges) /* already found one range */ { contact_row_start[1] = part->row_end +1; contact_row_end[1] = row_end; } else { contact_row_start[0] = part->row_end +1; contact_row_end[0] = row_end; } contact_ranges++; } } } /*----------------------------------------------------------- * Contact: find out who is assumed responsible for these * ranges of contact rows and contact them * *-----------------------------------------------------------*/ contact_list_length = 0; contact_list_storage = 5; contact_list = hypre_TAlloc(HYPRE_Int, contact_list_storage*3); /*each contact needs 3 ints */ for (i=0; i<contact_ranges; i++) { /*get start and end row owners */ hypre_GetAssumedPartitionProcFromRow(comm, contact_row_start[i], global_first_row, global_num_rows, &owner_start); hypre_GetAssumedPartitionProcFromRow(comm, contact_row_end[i], global_first_row, global_num_rows, &owner_end); if (owner_start == owner_end) /* same processor owns the whole range */ { if (contact_list_length == contact_list_storage) { /*allocate more space*/ contact_list_storage += 5; contact_list = hypre_TReAlloc(contact_list, HYPRE_Int, (contact_list_storage*3)); } CONTACT(contact_list_length, 0) = owner_start; /*proc #*/ CONTACT(contact_list_length, 1) = contact_row_start[i]; /* start row */ CONTACT(contact_list_length, 2) = contact_row_end[i]; /*end row */ contact_list_length++; } else { complete = 0; while (!complete) { hypre_GetAssumedPartitionRowRange(comm, owner_start, global_first_row, global_num_rows, &tmp_row_start, &tmp_row_end); if (tmp_row_end >= contact_row_end[i]) { tmp_row_end = contact_row_end[i]; complete = 1; } if (tmp_row_start < contact_row_start[i]) { tmp_row_start = contact_row_start[i]; } if (contact_list_length == contact_list_storage) { /*allocate more space*/ contact_list_storage += 5; contact_list = hypre_TReAlloc(contact_list, HYPRE_Int, (contact_list_storage*3)); } CONTACT(contact_list_length, 0) = owner_start; /*proc #*/ CONTACT(contact_list_length, 1) = tmp_row_start; /* start row */ CONTACT(contact_list_length, 2) = tmp_row_end; /*end row */ contact_list_length++; owner_start++; /*processors are seqential */ } } } requests = hypre_CTAlloc(hypre_MPI_Request, contact_list_length); statuses = hypre_CTAlloc(hypre_MPI_Status, contact_list_length); /*send out messages */ for (i=0; i< contact_list_length; i++) { hypre_MPI_Isend(&CONTACT(i,1) ,2, HYPRE_MPI_INT, CONTACT(i,0), flag1 , comm, &requests[i]); /*hypre_MPI_COMM_WORLD, &requests[i]);*/ } /*----------------------------------------------------------- * Locate ranges - * which rows in my assumed range do I not own * (at most two ranges - maybe none) * locate_row_count = total number of rows I must locate *-----------------------------------------------------------*/ locate_row_count = 0; /*locate_row_start[0]=0; locate_row_start[1]=0;*/ locate_ranges = 0; if (part->row_end < row_start || row_end < part->row_start ) /*no overlap - so all of my assumed rows */ { /*locate_row_start[0] = part->row_start;*/ locate_ranges++; locate_row_count += part->row_end - part->row_start + 1; } else /* the two regions overlap */ { if (part->row_start < row_start) {/* check for locate rows on the low end of the local range */ /*locate_row_start[0] = part->row_start;*/ locate_ranges++; locate_row_count += (row_start-1) - part->row_start + 1; } if (row_end < part->row_end) /* check the high end */ { /*if (locate_ranges)*/ /* already have one range */ /*{ locate_row_start[1] = row_end +1; } else { locate_row_start[0] = row_end +1; }*/ locate_ranges++; locate_row_count += part->row_end - (row_end + 1) + 1; } } /*----------------------------------------------------------- * Receive messages from other procs telling us where * all our locate rows actually reside *-----------------------------------------------------------*/ /* we will keep a partition of our assumed partition - list ourselves first. We will sort later with an additional index. In practice, this should only contain a few processors */ /*which part do I own?*/ tmp_row_start = hypre_max(part->row_start, row_start); tmp_row_end = hypre_min(row_end, part->row_end); if (tmp_row_start <= tmp_row_end) { part->proc_list[0] = myid; part->row_start_list[0] = tmp_row_start; part->row_end_list[0] = tmp_row_end; part->length++; } /* now look for messages that tell us which processor has our locate rows */ /* these will be blocking receives as we know how many to expect and they should be waiting (and we don't want to continue on without them) */ rows_found = 0; while (rows_found != locate_row_count) { hypre_MPI_Recv( tmp_range, 2 , HYPRE_MPI_INT, hypre_MPI_ANY_SOURCE, flag1 , comm, &status0); /*flag1 , hypre_MPI_COMM_WORLD, &status0);*/ if (part->length==part->storage_length) { part->storage_length+=10; part->proc_list = hypre_TReAlloc(part->proc_list, HYPRE_Int, part->storage_length); part->row_start_list = hypre_TReAlloc(part->row_start_list, HYPRE_Int, part->storage_length); part->row_end_list = hypre_TReAlloc(part->row_end_list, HYPRE_Int, part->storage_length); } part->row_start_list[part->length] = tmp_range[0]; part->row_end_list[part->length] = tmp_range[1]; part->proc_list[part->length] = status0.hypre_MPI_SOURCE; rows_found += tmp_range[1]- tmp_range[0] + 1; part->length++; } /*In case the partition of the assumed partition is longish, we would like to know the sorted order */ si= hypre_CTAlloc(HYPRE_Int, part->length); sortme = hypre_CTAlloc(HYPRE_Int, part->length); for (i=0; i<part->length; i++) { si[i] = i; sortme[i] = part->row_start_list[i]; } hypre_qsort2i( sortme, si, 0, (part->length)-1); part->sort_index = si; /*free the requests */ hypre_MPI_Waitall(contact_list_length, requests, statuses); hypre_TFree(statuses); hypre_TFree(requests); hypre_TFree(sortme); hypre_TFree(contact_list); return hypre_error_flag; } /*-------------------------------------------------------------------- * hypre_ParCSRMatrixCreateAssumedPartition - * Each proc gets it own range. Then * each needs to reconcile its actual range with its assumed * range - the result is essentila a partition of its assumed range - * this is the assumed partition. *--------------------------------------------------------------------*/ HYPRE_Int hypre_ParCSRMatrixCreateAssumedPartition( hypre_ParCSRMatrix *matrix) { HYPRE_Int global_num_cols; HYPRE_Int myid; HYPRE_Int row_start=0, row_end=0, col_start = 0, col_end = 0; MPI_Comm comm; hypre_IJAssumedPart *apart; global_num_cols = hypre_ParCSRMatrixGlobalNumCols(matrix); comm = hypre_ParCSRMatrixComm(matrix); /* find out my actualy range of rows and columns */ hypre_ParCSRMatrixGetLocalRange( matrix, &row_start, &row_end , &col_start, &col_end ); hypre_MPI_Comm_rank(comm, &myid ); /* allocate space */ apart = hypre_CTAlloc(hypre_IJAssumedPart, 1); /* get my assumed partitioning - we want partitioning of the vector that the matrix multiplies - so we use the col start and end */ hypre_GetAssumedPartitionRowRange( comm, myid, 0, global_num_cols, &(apart->row_start), &(apart->row_end)); /*allocate some space for the partition of the assumed partition */ apart->length = 0; /*room for 10 owners of the assumed partition*/ apart->storage_length = 10; /*need to be >=1 */ apart->proc_list = hypre_TAlloc(HYPRE_Int, apart->storage_length); apart->row_start_list = hypre_TAlloc(HYPRE_Int, apart->storage_length); apart->row_end_list = hypre_TAlloc(HYPRE_Int, apart->storage_length); /* now we want to reconcile our actual partition with the assumed partition */ hypre_LocateAssummedPartition(comm, col_start, col_end, 0, global_num_cols, apart, myid); /* this partition will be saved in the matrix data structure until the matrix is destroyed */ hypre_ParCSRMatrixAssumedPartition(matrix) = apart; return hypre_error_flag; } /*-------------------------------------------------------------------- * hypre_AssumedPartitionDestroy *--------------------------------------------------------------------*/ HYPRE_Int hypre_AssumedPartitionDestroy(hypre_IJAssumedPart *apart ) { if(apart->storage_length > 0) { hypre_TFree(apart->proc_list); hypre_TFree(apart->row_start_list); hypre_TFree(apart->row_end_list); hypre_TFree(apart->sort_index); } hypre_TFree(apart); return hypre_error_flag; } /*-------------------------------------------------------------------- * hypre_GetAssumedPartitionProcFromRow * Assumed partition for IJ case. Given a particular row j, return * the processor that is assumed to own that row. *--------------------------------------------------------------------*/ HYPRE_Int hypre_GetAssumedPartitionProcFromRow( MPI_Comm comm, HYPRE_Int row, HYPRE_Int global_first_row, HYPRE_Int global_num_rows, HYPRE_Int *proc_id) { HYPRE_Int num_procs; HYPRE_Int size, switch_row, extra; hypre_MPI_Comm_size(comm, &num_procs ); /*hypre_MPI_Comm_size(hypre_MPI_COMM_WORLD, &num_procs );*/ /* j = floor[(row*p/N] - this overflows*/ /* *proc_id = (row*num_procs)/global_num_rows;*/ /* this looks a bit odd, but we have to be very careful that this function and the next are inverses - and rounding errors make this difficult!!!!! */ size = global_num_rows /num_procs; extra = global_num_rows - size*num_procs; switch_row = global_first_row + (size + 1)*extra; if (row >= switch_row) { *proc_id = extra + (row - switch_row)/size; } else { *proc_id = (row - global_first_row)/(size+1); } return hypre_error_flag; } /*-------------------------------------------------------------------- * hypre_GetAssumedPartitionRowRange * Assumed partition for IJ case. Given a particular processor id, return * the assumed range of rows ([row_start, row_end]) for that processor. *--------------------------------------------------------------------*/ HYPRE_Int hypre_GetAssumedPartitionRowRange( MPI_Comm comm, HYPRE_Int proc_id, HYPRE_Int global_first_row, HYPRE_Int global_num_rows, HYPRE_Int *row_start, HYPRE_Int* row_end) { HYPRE_Int num_procs; HYPRE_Int size, extra; hypre_MPI_Comm_size(comm, &num_procs ); /*hypre_MPI_Comm_size(hypre_MPI_COMM_WORLD, &num_procs );*/ /* this may look non-intuitive, but we have to be very careful that this function and the next are inverses - and avoiding overflow and rounding errors makes this difficult! */ size = global_num_rows /num_procs; extra = global_num_rows - size*num_procs; *row_start = global_first_row + size*proc_id; *row_start += hypre_min(proc_id, extra); *row_end = global_first_row + size*(proc_id+1); *row_end += hypre_min(proc_id+1, extra); *row_end = *row_end - 1; return hypre_error_flag; } /*-------------------------------------------------------------------- * hypre_ParVectorCreateAssumedPartition - * Essentially the same as for a matrix! * Each proc gets it own range. Then * each needs to reconcile its actual range with its assumed * range - the result is essentila a partition of its assumed range - * this is the assumed partition. *--------------------------------------------------------------------*/ HYPRE_Int hypre_ParVectorCreateAssumedPartition( hypre_ParVector *vector) { HYPRE_Int global_num; HYPRE_Int myid; HYPRE_Int start=0, end=0; MPI_Comm comm; hypre_IJAssumedPart *apart; global_num = hypre_ParVectorGlobalSize(vector); comm = hypre_ParVectorComm(vector); /* find out my actualy range of rows */ start = hypre_ParVectorFirstIndex(vector); end = hypre_ParVectorLastIndex(vector); hypre_MPI_Comm_rank(comm, &myid ); /* allocate space */ apart = hypre_CTAlloc(hypre_IJAssumedPart, 1); /* get my assumed partitioning - we want partitioning of the vector that the matrix multiplies - so we use the col start and end */ hypre_GetAssumedPartitionRowRange( comm, myid, 0, global_num, &(apart->row_start), &(apart->row_end)); /*allocate some space for the partition of the assumed partition */ apart->length = 0; /*room for 10 owners of the assumed partition*/ apart->storage_length = 10; /*need to be >=1 */ apart->proc_list = hypre_TAlloc(HYPRE_Int, apart->storage_length); apart->row_start_list = hypre_TAlloc(HYPRE_Int, apart->storage_length); apart->row_end_list = hypre_TAlloc(HYPRE_Int, apart->storage_length); /* now we want to reconcile our actual partition with the assumed partition */ hypre_LocateAssummedPartition(comm, start, end, 0, global_num, apart, myid); /* this partition will be saved in the vector data structure until the vector is destroyed */ hypre_ParVectorAssumedPartition(vector) = apart; return hypre_error_flag; }
17,884
31.400362
103
c
AMG
AMG-master/parcsr_mv/par_csr_assumed_part.h
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ #ifndef hypre_PARCSR_ASSUMED_PART #define hypre_PARCSR_ASSUMED_PART typedef struct { HYPRE_Int length; HYPRE_Int row_start; HYPRE_Int row_end; HYPRE_Int storage_length; HYPRE_Int *proc_list; HYPRE_Int *row_start_list; HYPRE_Int *row_end_list; HYPRE_Int *sort_index; } hypre_IJAssumedPart; #endif /* hypre_PARCSR_ASSUMED_PART */
1,422
36.447368
81
h
AMG
AMG-master/parcsr_mv/par_csr_communication.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ #include "_hypre_parcsr_mv.h" /*==========================================================================*/ #ifdef HYPRE_USING_PERSISTENT_COMM static CommPkgJobType getJobTypeOf(HYPRE_Int job) { CommPkgJobType job_type = HYPRE_COMM_PKG_JOB_COMPLEX; switch (job) { case 1: job_type = HYPRE_COMM_PKG_JOB_COMPLEX; break; case 2: job_type = HYPRE_COMM_PKG_JOB_COMPLEX_TRANSPOSE; break; case 11: job_type = HYPRE_COMM_PKG_JOB_INT; break; case 12: job_type = HYPRE_COMM_PKG_JOB_INT_TRANSPOSE; break; } // switch (job) return job_type; } /** * When send_data and recv_data are NULL, buffers are internally allocated * and CommHandle owns the buffer */ hypre_ParCSRPersistentCommHandle * hypre_ParCSRPersistentCommHandleCreate( HYPRE_Int job, hypre_ParCSRCommPkg *comm_pkg, void *send_data, void *recv_data) { HYPRE_Int i; hypre_ParCSRPersistentCommHandle *comm_handle = hypre_CTAlloc(hypre_ParCSRPersistentCommHandle, 1); if (!send_data) comm_handle->own_send_data = 1; if (!recv_data) comm_handle->own_recv_data = 1; CommPkgJobType job_type = getJobTypeOf(job); HYPRE_Int num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); HYPRE_Int num_recvs = hypre_ParCSRCommPkgNumRecvs(comm_pkg); MPI_Comm comm = hypre_ParCSRCommPkgComm(comm_pkg); HYPRE_Int num_requests = num_sends + num_recvs; hypre_MPI_Request *requests = hypre_CTAlloc(hypre_MPI_Request, num_requests); hypre_ParCSRCommHandleNumRequests(comm_handle) = num_requests; hypre_ParCSRCommHandleRequests(comm_handle) = requests; switch (job_type) { case HYPRE_COMM_PKG_JOB_COMPLEX: if (!send_data) { send_data = hypre_TAlloc(HYPRE_Complex, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends)); } if (!recv_data) { recv_data = hypre_TAlloc(HYPRE_Complex, hypre_ParCSRCommPkgRecvVecStart(comm_pkg, num_recvs)); } for (i = 0; i < num_recvs; ++i) { HYPRE_Int ip = hypre_ParCSRCommPkgRecvProc(comm_pkg, i); HYPRE_Int vec_start = hypre_ParCSRCommPkgRecvVecStart(comm_pkg, i); HYPRE_Int vec_len = hypre_ParCSRCommPkgRecvVecStart(comm_pkg, i + 1) - vec_start; hypre_MPI_Recv_init((HYPRE_Complex *)recv_data + vec_start, vec_len, HYPRE_MPI_COMPLEX, ip, 0, comm, requests + i); } for (i = 0; i < num_sends; ++i) { HYPRE_Int ip = hypre_ParCSRCommPkgSendProc(comm_pkg, i); HYPRE_Int vec_start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); HYPRE_Int vec_len = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i + 1) - vec_start; hypre_MPI_Send_init((HYPRE_Complex *)send_data + vec_start, vec_len, HYPRE_MPI_COMPLEX, ip, 0, comm, requests + num_recvs + i); } break; case HYPRE_COMM_PKG_JOB_COMPLEX_TRANSPOSE: if (!recv_data) { recv_data = hypre_TAlloc(HYPRE_Complex, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends)); } if (!send_data) { send_data = hypre_TAlloc(HYPRE_Complex, hypre_ParCSRCommPkgRecvVecStart(comm_pkg, num_recvs)); } for (i = 0; i < num_sends; ++i) { HYPRE_Int ip = hypre_ParCSRCommPkgSendProc(comm_pkg, i); HYPRE_Int vec_start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); HYPRE_Int vec_len = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i + 1) - vec_start; hypre_MPI_Recv_init((HYPRE_Complex *)recv_data + vec_start, vec_len, HYPRE_MPI_COMPLEX, ip, 0, comm, requests + i); } for (i = 0; i < num_recvs; ++i) { HYPRE_Int ip = hypre_ParCSRCommPkgRecvProc(comm_pkg, i); HYPRE_Int vec_start = hypre_ParCSRCommPkgRecvVecStart(comm_pkg, i); HYPRE_Int vec_len = hypre_ParCSRCommPkgRecvVecStart(comm_pkg, i + 1) - vec_start; hypre_MPI_Send_init((HYPRE_Complex *)send_data + vec_start, vec_len, HYPRE_MPI_COMPLEX, ip, 0, comm, requests + num_sends + i); } break; case HYPRE_COMM_PKG_JOB_INT: if (!send_data) { send_data = hypre_TAlloc(HYPRE_Int, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends)); } if (!recv_data) { recv_data = hypre_TAlloc(HYPRE_Int, hypre_ParCSRCommPkgRecvVecStart(comm_pkg, num_recvs)); } for (i = 0; i < num_recvs; ++i) { HYPRE_Int ip = hypre_ParCSRCommPkgRecvProc(comm_pkg, i); HYPRE_Int vec_start = hypre_ParCSRCommPkgRecvVecStart(comm_pkg, i); HYPRE_Int vec_len = hypre_ParCSRCommPkgRecvVecStart(comm_pkg, i + 1) - vec_start; hypre_MPI_Recv_init((HYPRE_Int *)recv_data + vec_start, vec_len, HYPRE_MPI_INT, ip, 0, comm, requests + i); } for (i = 0; i < num_sends; ++i) { HYPRE_Int ip = hypre_ParCSRCommPkgSendProc(comm_pkg, i); HYPRE_Int vec_start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); HYPRE_Int vec_len = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i + 1) - vec_start; hypre_MPI_Send_init((HYPRE_Int *)send_data + vec_start, vec_len, HYPRE_MPI_INT, ip, 0, comm, requests + num_recvs + i); } break; case HYPRE_COMM_PKG_JOB_INT_TRANSPOSE: if (!recv_data) { recv_data = hypre_TAlloc(HYPRE_Int, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends)); } if (!send_data) { send_data = hypre_TAlloc(HYPRE_Int, hypre_ParCSRCommPkgRecvVecStart(comm_pkg, num_recvs)); } for (i = 0; i < num_sends; ++i) { HYPRE_Int ip = hypre_ParCSRCommPkgSendProc(comm_pkg, i); HYPRE_Int vec_start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); HYPRE_Int vec_len = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i + 1) - vec_start; hypre_MPI_Recv_init((HYPRE_Int *)recv_data + vec_start, vec_len, HYPRE_MPI_INT, ip, 0, comm, requests + i); } for (i = 0; i < num_recvs; ++i) { HYPRE_Int ip = hypre_ParCSRCommPkgRecvProc(comm_pkg, i); HYPRE_Int vec_start = hypre_ParCSRCommPkgRecvVecStart(comm_pkg, i); HYPRE_Int vec_len = hypre_ParCSRCommPkgRecvVecStart(comm_pkg, i + 1) - vec_start; hypre_MPI_Send_init((HYPRE_Int *)send_data + vec_start, vec_len, HYPRE_MPI_INT, ip, 0, comm, requests + num_sends + i); } break; default: hypre_assert(1 == 0); break; } // switch (job_type) hypre_ParCSRCommHandleRecvData(comm_handle) = recv_data; hypre_ParCSRCommHandleSendData(comm_handle) = send_data; return ( comm_handle ); } hypre_ParCSRPersistentCommHandle * hypre_ParCSRCommPkgGetPersistentCommHandle( HYPRE_Int job, hypre_ParCSRCommPkg *comm_pkg ) { CommPkgJobType type = getJobTypeOf(job); if (!comm_pkg->persistent_comm_handles[type]) { comm_pkg->persistent_comm_handles[type] = hypre_ParCSRPersistentCommHandleCreate(job, comm_pkg, NULL, NULL); // data is owned by persistent comm handle } return comm_pkg->persistent_comm_handles[type]; } void hypre_ParCSRPersistentCommHandleDestroy( hypre_ParCSRPersistentCommHandle *comm_handle ) { if (comm_handle->own_send_data) { hypre_TFree(comm_handle->send_data); } if (comm_handle->own_recv_data) { hypre_TFree(comm_handle->recv_data); } hypre_TFree(comm_handle->requests); hypre_TFree(comm_handle); } void hypre_ParCSRPersistentCommHandleStart( hypre_ParCSRPersistentCommHandle *comm_handle ) { if (hypre_ParCSRCommHandleNumRequests(comm_handle) > 0) { HYPRE_Int ret = hypre_MPI_Startall(hypre_ParCSRCommHandleNumRequests(comm_handle), hypre_ParCSRCommHandleRequests(comm_handle)); if (hypre_MPI_SUCCESS != ret) { hypre_error_w_msg(HYPRE_ERROR_GENERIC,"MPI error\n"); /*hypre_printf("MPI error %d in %s (%s, line %u)\n", ret, __FUNCTION__, __FILE__, __LINE__);*/ } } } void hypre_ParCSRPersistentCommHandleWait( hypre_ParCSRPersistentCommHandle *comm_handle ) { if (hypre_ParCSRCommHandleNumRequests(comm_handle) > 0) { HYPRE_Int ret = hypre_MPI_Waitall(hypre_ParCSRCommHandleNumRequests(comm_handle), hypre_ParCSRCommHandleRequests(comm_handle), hypre_MPI_STATUSES_IGNORE); if (hypre_MPI_SUCCESS != ret) { hypre_error_w_msg(HYPRE_ERROR_GENERIC,"MPI error\n"); /*hypre_printf("MPI error %d in %s (%s, line %u)\n", ret, __FUNCTION__, __FILE__, __LINE__);*/ } } } #endif // HYPRE_USING_PERSISTENT_COMM hypre_ParCSRCommHandle * hypre_ParCSRCommHandleCreate ( HYPRE_Int job, hypre_ParCSRCommPkg *comm_pkg, void *send_data, void *recv_data ) { HYPRE_Int num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); HYPRE_Int num_recvs = hypre_ParCSRCommPkgNumRecvs(comm_pkg); MPI_Comm comm = hypre_ParCSRCommPkgComm(comm_pkg); hypre_ParCSRCommHandle *comm_handle; HYPRE_Int num_requests; hypre_MPI_Request *requests; HYPRE_Int i, j; HYPRE_Int my_id, num_procs; HYPRE_Int ip, vec_start, vec_len; /*-------------------------------------------------------------------- * hypre_Initialize sets up a communication handle, * posts receives and initiates sends. It always requires num_sends, * num_recvs, recv_procs and send_procs to be set in comm_pkg. * There are different options for job: * job = 1 : is used to initialize communication exchange for the parts * of vector needed to perform a Matvec, it requires send_data * and recv_data to be doubles, recv_vec_starts and * send_map_starts need to be set in comm_pkg. * job = 2 : is used to initialize communication exchange for the parts * of vector needed to perform a MatvecT, it requires send_data * and recv_data to be doubles, recv_vec_starts and * send_map_starts need to be set in comm_pkg. * job = 11: similar to job = 1, but exchanges data of type HYPRE_Int (not HYPRE_Complex), * requires send_data and recv_data to be ints * recv_vec_starts and send_map_starts need to be set in comm_pkg. * job = 12: similar to job = 1, but exchanges data of type HYPRE_Int (not HYPRE_Complex), * requires send_data and recv_data to be ints * recv_vec_starts and send_map_starts need to be set in comm_pkg. * default: ignores send_data and recv_data, requires send_mpi_types * and recv_mpi_types to be set in comm_pkg. * datatypes need to point to absolute * addresses, e.g. generated using hypre_MPI_Address . *--------------------------------------------------------------------*/ num_requests = num_sends + num_recvs; requests = hypre_CTAlloc(hypre_MPI_Request, num_requests); hypre_MPI_Comm_size(comm,&num_procs); hypre_MPI_Comm_rank(comm,&my_id); j = 0; switch (job) { case 1: { HYPRE_Complex *d_send_data = (HYPRE_Complex *) send_data; HYPRE_Complex *d_recv_data = (HYPRE_Complex *) recv_data; for (i = 0; i < num_recvs; i++) { ip = hypre_ParCSRCommPkgRecvProc(comm_pkg, i); vec_start = hypre_ParCSRCommPkgRecvVecStart(comm_pkg,i); vec_len = hypre_ParCSRCommPkgRecvVecStart(comm_pkg,i+1)-vec_start; hypre_MPI_Irecv(&d_recv_data[vec_start], vec_len, HYPRE_MPI_COMPLEX, ip, 0, comm, &requests[j++]); } for (i = 0; i < num_sends; i++) { vec_start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); vec_len = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1)-vec_start; ip = hypre_ParCSRCommPkgSendProc(comm_pkg, i); hypre_MPI_Isend(&d_send_data[vec_start], vec_len, HYPRE_MPI_COMPLEX, ip, 0, comm, &requests[j++]); } break; } case 2: { HYPRE_Complex *d_send_data = (HYPRE_Complex *) send_data; HYPRE_Complex *d_recv_data = (HYPRE_Complex *) recv_data; for (i = 0; i < num_sends; i++) { vec_start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); vec_len = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1) - vec_start; ip = hypre_ParCSRCommPkgSendProc(comm_pkg, i); hypre_MPI_Irecv(&d_recv_data[vec_start], vec_len, HYPRE_MPI_COMPLEX, ip, 0, comm, &requests[j++]); } for (i = 0; i < num_recvs; i++) { ip = hypre_ParCSRCommPkgRecvProc(comm_pkg, i); vec_start = hypre_ParCSRCommPkgRecvVecStart(comm_pkg,i); vec_len = hypre_ParCSRCommPkgRecvVecStart(comm_pkg,i+1)-vec_start; hypre_MPI_Isend(&d_send_data[vec_start], vec_len, HYPRE_MPI_COMPLEX, ip, 0, comm, &requests[j++]); } break; } case 11: { HYPRE_Int *i_send_data = (HYPRE_Int *) send_data; HYPRE_Int *i_recv_data = (HYPRE_Int *) recv_data; for (i = 0; i < num_recvs; i++) { ip = hypre_ParCSRCommPkgRecvProc(comm_pkg, i); vec_start = hypre_ParCSRCommPkgRecvVecStart(comm_pkg,i); vec_len = hypre_ParCSRCommPkgRecvVecStart(comm_pkg,i+1)-vec_start; hypre_MPI_Irecv(&i_recv_data[vec_start], vec_len, HYPRE_MPI_INT, ip, 0, comm, &requests[j++]); } for (i = 0; i < num_sends; i++) { vec_start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); vec_len = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1)-vec_start; ip = hypre_ParCSRCommPkgSendProc(comm_pkg, i); hypre_MPI_Isend(&i_send_data[vec_start], vec_len, HYPRE_MPI_INT, ip, 0, comm, &requests[j++]); } break; } case 12: { HYPRE_Int *i_send_data = (HYPRE_Int *) send_data; HYPRE_Int *i_recv_data = (HYPRE_Int *) recv_data; for (i = 0; i < num_sends; i++) { vec_start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); vec_len = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1) - vec_start; ip = hypre_ParCSRCommPkgSendProc(comm_pkg, i); hypre_MPI_Irecv(&i_recv_data[vec_start], vec_len, HYPRE_MPI_INT, ip, 0, comm, &requests[j++]); } for (i = 0; i < num_recvs; i++) { ip = hypre_ParCSRCommPkgRecvProc(comm_pkg, i); vec_start = hypre_ParCSRCommPkgRecvVecStart(comm_pkg,i); vec_len = hypre_ParCSRCommPkgRecvVecStart(comm_pkg,i+1)-vec_start; hypre_MPI_Isend(&i_send_data[vec_start], vec_len, HYPRE_MPI_INT, ip, 0, comm, &requests[j++]); } break; } } /*-------------------------------------------------------------------- * set up comm_handle and return *--------------------------------------------------------------------*/ comm_handle = hypre_CTAlloc(hypre_ParCSRCommHandle, 1); hypre_ParCSRCommHandleCommPkg(comm_handle) = comm_pkg; hypre_ParCSRCommHandleSendData(comm_handle) = send_data; hypre_ParCSRCommHandleRecvData(comm_handle) = recv_data; hypre_ParCSRCommHandleNumRequests(comm_handle) = num_requests; hypre_ParCSRCommHandleRequests(comm_handle) = requests; return ( comm_handle ); } HYPRE_Int hypre_ParCSRCommHandleDestroy( hypre_ParCSRCommHandle *comm_handle ) { hypre_MPI_Status *status0; if ( comm_handle==NULL ) return hypre_error_flag; if (hypre_ParCSRCommHandleNumRequests(comm_handle)) { status0 = hypre_CTAlloc(hypre_MPI_Status, hypre_ParCSRCommHandleNumRequests(comm_handle)); hypre_MPI_Waitall(hypre_ParCSRCommHandleNumRequests(comm_handle), hypre_ParCSRCommHandleRequests(comm_handle), status0); hypre_TFree(status0); } hypre_TFree(hypre_ParCSRCommHandleRequests(comm_handle)); hypre_TFree(comm_handle); return hypre_error_flag; } /* hypre_MatCommPkgCreate_core does all the communications and computations for hypre_MatCommPkgCreate ( hypre_ParCSRMatrix *A) and hypre_BoolMatCommPkgCreate ( hypre_ParCSRBooleanMatrix *A) To support both data types, it has hardly any data structures other than HYPRE_Int*. */ void hypre_MatvecCommPkgCreate_core( /* input args: */ MPI_Comm comm, HYPRE_Int * col_map_offd, HYPRE_Int first_col_diag, HYPRE_Int * col_starts, HYPRE_Int num_cols_diag, HYPRE_Int num_cols_offd, HYPRE_Int firstColDiag, HYPRE_Int * colMapOffd, HYPRE_Int data, /* = 1 for a matrix with floating-point data, = 0 for Boolean matrix */ /* pointers to output args: */ HYPRE_Int * p_num_recvs, HYPRE_Int ** p_recv_procs, HYPRE_Int ** p_recv_vec_starts, HYPRE_Int * p_num_sends, HYPRE_Int ** p_send_procs, HYPRE_Int ** p_send_map_starts, HYPRE_Int ** p_send_map_elmts ) { HYPRE_Int i, j; HYPRE_Int num_procs, my_id, proc_num, num_elmts; HYPRE_Int local_info, offd_col; HYPRE_Int *proc_mark, *proc_add, *tmp, *recv_buf, *displs, *info; /* outputs: */ HYPRE_Int num_recvs, * recv_procs, * recv_vec_starts; HYPRE_Int num_sends, * send_procs, * send_map_starts, * send_map_elmts; HYPRE_Int ip, vec_start, vec_len, num_requests; hypre_MPI_Request *requests; hypre_MPI_Status *status; hypre_MPI_Comm_size(comm, &num_procs); hypre_MPI_Comm_rank(comm, &my_id); proc_mark = hypre_CTAlloc(HYPRE_Int, num_procs); proc_add = hypre_CTAlloc(HYPRE_Int, num_procs); info = hypre_CTAlloc(HYPRE_Int, num_procs); /* ---------------------------------------------------------------------- * determine which processors to receive from (set proc_mark) and num_recvs, * at the end of the loop proc_mark[i] contains the number of elements to be * received from Proc. i * ---------------------------------------------------------------------*/ for (i=0; i < num_procs; i++) proc_add[i] = 0; proc_num = 0; if (num_cols_offd) offd_col = col_map_offd[0]; num_recvs=0; j = 0; for (i=0; i < num_cols_offd; i++) { if (num_cols_diag) proc_num = hypre_min(num_procs-1,offd_col / num_cols_diag); while (col_starts[proc_num] > offd_col ) proc_num = proc_num-1; while (col_starts[proc_num+1]-1 < offd_col ) proc_num = proc_num+1; proc_mark[num_recvs] = proc_num; j = i; while (col_starts[proc_num+1] > offd_col) { proc_add[num_recvs]++; if (j < num_cols_offd-1) { j++; offd_col = col_map_offd[j]; } else { j++; offd_col = col_starts[num_procs]; } } num_recvs++; if (j < num_cols_offd) i = j-1; else i=j; } local_info = 2*num_recvs; hypre_MPI_Allgather(&local_info, 1, HYPRE_MPI_INT, info, 1, HYPRE_MPI_INT, comm); /* ---------------------------------------------------------------------- * generate information to be sent: tmp contains for each recv_proc: * id of recv_procs, number of elements to be received for this processor, * indices of elements (in this order) * ---------------------------------------------------------------------*/ displs = hypre_CTAlloc(HYPRE_Int, num_procs+1); displs[0] = 0; for (i=1; i < num_procs+1; i++) displs[i] = displs[i-1]+info[i-1]; recv_buf = hypre_CTAlloc(HYPRE_Int, displs[num_procs]); recv_procs = NULL; tmp = NULL; if (num_recvs) { recv_procs = hypre_CTAlloc(HYPRE_Int, num_recvs); tmp = hypre_CTAlloc(HYPRE_Int, local_info); } recv_vec_starts = hypre_CTAlloc(HYPRE_Int, num_recvs+1); j = 0; if (num_recvs) recv_vec_starts[0] = 0; for (i=0; i < num_recvs; i++) { num_elmts = proc_add[i]; recv_procs[i] = proc_mark[i]; recv_vec_starts[i+1] = recv_vec_starts[i]+num_elmts; tmp[j++] = proc_mark[i]; tmp[j++] = num_elmts; } hypre_MPI_Allgatherv(tmp,local_info,HYPRE_MPI_INT,recv_buf,info, displs,HYPRE_MPI_INT,comm); /* ---------------------------------------------------------------------- * determine num_sends and number of elements to be sent * ---------------------------------------------------------------------*/ num_sends = 0; num_elmts = 0; proc_add[0] = 0; for (i=0; i < num_procs; i++) { j = displs[i]; while ( j < displs[i+1]) { if (recv_buf[j++] == my_id) { proc_mark[num_sends] = i; num_sends++; proc_add[num_sends] = proc_add[num_sends-1]+recv_buf[j]; break; } j++; } } /* ---------------------------------------------------------------------- * determine send_procs and actual elements to be send (in send_map_elmts) * and send_map_starts whose i-th entry points to the beginning of the * elements to be send to proc. i * ---------------------------------------------------------------------*/ send_procs = NULL; send_map_elmts = NULL; if (num_sends) { send_procs = hypre_CTAlloc(HYPRE_Int, num_sends); send_map_elmts = hypre_CTAlloc(HYPRE_Int, proc_add[num_sends]); } send_map_starts = hypre_CTAlloc(HYPRE_Int, num_sends+1); num_requests = num_recvs+num_sends; if (num_requests) { requests = hypre_CTAlloc(hypre_MPI_Request, num_requests); status = hypre_CTAlloc(hypre_MPI_Status, num_requests); } if (num_sends) send_map_starts[0] = 0; for (i=0; i < num_sends; i++) { send_map_starts[i+1] = proc_add[i+1]; send_procs[i] = proc_mark[i]; } j=0; for (i=0; i < num_sends; i++) { vec_start = send_map_starts[i]; vec_len = send_map_starts[i+1] - vec_start; ip = send_procs[i]; hypre_MPI_Irecv(&send_map_elmts[vec_start], vec_len, HYPRE_MPI_INT, ip, 0, comm, &requests[j++]); } for (i=0; i < num_recvs; i++) { vec_start = recv_vec_starts[i]; vec_len = recv_vec_starts[i+1] - vec_start; ip = recv_procs[i]; hypre_MPI_Isend(&col_map_offd[vec_start], vec_len, HYPRE_MPI_INT, ip, 0, comm, &requests[j++]); } if (num_requests) { hypre_MPI_Waitall(num_requests, requests, status); hypre_TFree(requests); hypre_TFree(status); } if (num_sends) { for (i=0; i<send_map_starts[num_sends]; i++) send_map_elmts[i] -= first_col_diag; } hypre_TFree(proc_add); hypre_TFree(proc_mark); hypre_TFree(tmp); hypre_TFree(recv_buf); hypre_TFree(displs); hypre_TFree(info); /* finish up with the hand-coded call-by-reference... */ *p_num_recvs = num_recvs; *p_recv_procs = recv_procs; *p_recv_vec_starts = recv_vec_starts; *p_num_sends = num_sends; *p_send_procs = send_procs; *p_send_map_starts = send_map_starts; *p_send_map_elmts = send_map_elmts; } /* ---------------------------------------------------------------------- * hypre_MatvecCommPkgCreate * generates the comm_pkg for A * if no row and/or column partitioning is given, the routine determines * them with MPE_Decomp1d * ---------------------------------------------------------------------*/ HYPRE_Int hypre_MatvecCommPkgCreate ( hypre_ParCSRMatrix *A ) { HYPRE_Int num_sends = 0; HYPRE_Int *send_procs = NULL; HYPRE_Int *send_map_starts = NULL; HYPRE_Int *send_map_elmts = NULL; HYPRE_Int num_recvs = 0; HYPRE_Int *recv_procs = NULL; HYPRE_Int *recv_vec_starts = NULL; MPI_Comm comm = hypre_ParCSRMatrixComm(A); hypre_ParCSRCommPkg *comm_pkg; HYPRE_Int first_col_diag = hypre_ParCSRMatrixFirstColDiag(A); HYPRE_Int *col_map_offd = hypre_ParCSRMatrixColMapOffd(A); HYPRE_Int num_cols_offd = hypre_CSRMatrixNumCols(hypre_ParCSRMatrixOffd(A)); HYPRE_Int num_procs; hypre_MPI_Comm_size(comm,&num_procs); if (num_procs > 1) { #ifdef HYPRE_NO_GLOBAL_PARTITION HYPRE_Int row_start=0, row_end=0, col_start = 0, col_end = 0; HYPRE_Int global_num_cols; hypre_IJAssumedPart *apart; /*----------------------------------------------------------- * get parcsr_A information *----------------------------------------------------------*/ hypre_ParCSRMatrixGetLocalRange(A, &row_start, &row_end, &col_start, &col_end); global_num_cols = hypre_ParCSRMatrixGlobalNumCols(A); /* Create the assumed partition */ if (hypre_ParCSRMatrixAssumedPartition(A) == NULL) { hypre_ParCSRMatrixCreateAssumedPartition(A); } apart = hypre_ParCSRMatrixAssumedPartition(A); /*----------------------------------------------------------- * get commpkg info information *----------------------------------------------------------*/ hypre_NewCommPkgCreate_core( comm, col_map_offd, first_col_diag, col_start, col_end, num_cols_offd, global_num_cols, &num_recvs, &recv_procs, &recv_vec_starts, &num_sends, &send_procs, &send_map_starts, &send_map_elmts, apart); #else HYPRE_Int *col_starts = hypre_ParCSRMatrixColStarts(A); HYPRE_Int num_cols_diag = hypre_CSRMatrixNumCols(hypre_ParCSRMatrixDiag(A)); hypre_MatvecCommPkgCreate_core ( comm, col_map_offd, first_col_diag, col_starts, num_cols_diag, num_cols_offd, first_col_diag, col_map_offd, 1, &num_recvs, &recv_procs, &recv_vec_starts, &num_sends, &send_procs, &send_map_starts, &send_map_elmts ); #endif /*----------------------------------------------------------- * setup commpkg *----------------------------------------------------------*/ } else { send_map_starts = hypre_CTAlloc(HYPRE_Int,1); recv_vec_starts = hypre_CTAlloc(HYPRE_Int,1); } comm_pkg = hypre_CTAlloc(hypre_ParCSRCommPkg, 1); hypre_ParCSRCommPkgComm(comm_pkg) = comm; hypre_ParCSRCommPkgNumRecvs(comm_pkg) = num_recvs; hypre_ParCSRCommPkgRecvProcs(comm_pkg) = recv_procs; hypre_ParCSRCommPkgRecvVecStarts(comm_pkg) = recv_vec_starts; hypre_ParCSRCommPkgNumSends(comm_pkg) = num_sends; hypre_ParCSRCommPkgSendProcs(comm_pkg) = send_procs; hypre_ParCSRCommPkgSendMapStarts(comm_pkg) = send_map_starts; hypre_ParCSRCommPkgSendMapElmts(comm_pkg) = send_map_elmts; hypre_ParCSRMatrixCommPkg(A) = comm_pkg; return hypre_error_flag; } HYPRE_Int hypre_MatvecCommPkgDestroy( hypre_ParCSRCommPkg *comm_pkg ) { #ifdef HYPRE_USING_PERSISTENT_COMM HYPRE_Int i; for (i = HYPRE_COMM_PKG_JOB_COMPLEX; i < NUM_OF_COMM_PKG_JOB_TYPE; ++i) { if (comm_pkg->persistent_comm_handles[i]) { hypre_ParCSRPersistentCommHandleDestroy(comm_pkg->persistent_comm_handles[i]); } } #endif if (hypre_ParCSRCommPkgNumSends(comm_pkg)) { hypre_TFree(hypre_ParCSRCommPkgSendProcs(comm_pkg)); hypre_TFree(hypre_ParCSRCommPkgSendMapElmts(comm_pkg)); } hypre_TFree(hypre_ParCSRCommPkgSendMapStarts(comm_pkg)); /* if (hypre_ParCSRCommPkgSendMPITypes(comm_pkg)) hypre_TFree(hypre_ParCSRCommPkgSendMPITypes(comm_pkg)); */ if (hypre_ParCSRCommPkgNumRecvs(comm_pkg)) { hypre_TFree(hypre_ParCSRCommPkgRecvProcs(comm_pkg)); } hypre_TFree(hypre_ParCSRCommPkgRecvVecStarts(comm_pkg)); /* if (hypre_ParCSRCommPkgRecvMPITypes(comm_pkg)) hypre_TFree(hypre_ParCSRCommPkgRecvMPITypes(comm_pkg)); */ hypre_TFree(comm_pkg); return hypre_error_flag; } HYPRE_Int hypre_BuildCSRMatrixMPIDataType( HYPRE_Int num_nonzeros, HYPRE_Int num_rows, HYPRE_Complex *a_data, HYPRE_Int *a_i, HYPRE_Int *a_j, hypre_MPI_Datatype *csr_matrix_datatype ) { HYPRE_Int block_lens[3]; hypre_MPI_Aint displ[3]; hypre_MPI_Datatype types[3]; block_lens[0] = num_nonzeros; block_lens[1] = num_rows+1; block_lens[2] = num_nonzeros; types[0] = HYPRE_MPI_COMPLEX; types[1] = HYPRE_MPI_INT; types[2] = HYPRE_MPI_INT; hypre_MPI_Address(a_data, &displ[0]); hypre_MPI_Address(a_i, &displ[1]); hypre_MPI_Address(a_j, &displ[2]); hypre_MPI_Type_struct(3,block_lens,displ,types,csr_matrix_datatype); hypre_MPI_Type_commit(csr_matrix_datatype); return hypre_error_flag; } HYPRE_Int hypre_BuildCSRJDataType( HYPRE_Int num_nonzeros, HYPRE_Complex *a_data, HYPRE_Int *a_j, hypre_MPI_Datatype *csr_jdata_datatype ) { HYPRE_Int block_lens[2]; hypre_MPI_Aint displs[2]; hypre_MPI_Datatype types[2]; block_lens[0] = num_nonzeros; block_lens[1] = num_nonzeros; types[0] = HYPRE_MPI_COMPLEX; types[1] = HYPRE_MPI_INT; hypre_MPI_Address(a_data, &displs[0]); hypre_MPI_Address(a_j, &displs[1]); hypre_MPI_Type_struct(2,block_lens,displs,types,csr_jdata_datatype); hypre_MPI_Type_commit(csr_jdata_datatype); return hypre_error_flag; }
31,643
35.709977
108
c
AMG
AMG-master/parcsr_mv/par_csr_communication.h
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ #ifndef HYPRE_PAR_CSR_COMMUNICATION_HEADER #define HYPRE_PAR_CSR_COMMUNICATION_HEADER /*-------------------------------------------------------------------------- * hypre_ParCSRCommPkg: * Structure containing information for doing communications *--------------------------------------------------------------------------*/ #define HYPRE_USING_PERSISTENT_COMM // JSP: can be defined by configure #ifdef HYPRE_USING_PERSISTENT_COMM typedef enum CommPkgJobType { HYPRE_COMM_PKG_JOB_COMPLEX = 0, HYPRE_COMM_PKG_JOB_COMPLEX_TRANSPOSE, HYPRE_COMM_PKG_JOB_INT, HYPRE_COMM_PKG_JOB_INT_TRANSPOSE, NUM_OF_COMM_PKG_JOB_TYPE, } CommPkgJobType; typedef struct { void *send_data; void *recv_data; HYPRE_Int num_requests; hypre_MPI_Request *requests; HYPRE_Int own_send_data, own_recv_data; } hypre_ParCSRPersistentCommHandle; #endif typedef struct { MPI_Comm comm; HYPRE_Int num_sends; HYPRE_Int *send_procs; HYPRE_Int *send_map_starts; HYPRE_Int *send_map_elmts; HYPRE_Int num_recvs; HYPRE_Int *recv_procs; HYPRE_Int *recv_vec_starts; /* remote communication information */ hypre_MPI_Datatype *send_mpi_types; hypre_MPI_Datatype *recv_mpi_types; #ifdef HYPRE_USING_PERSISTENT_COMM hypre_ParCSRPersistentCommHandle *persistent_comm_handles[NUM_OF_COMM_PKG_JOB_TYPE]; #endif } hypre_ParCSRCommPkg; /*-------------------------------------------------------------------------- * hypre_ParCSRCommHandle: *--------------------------------------------------------------------------*/ typedef struct { hypre_ParCSRCommPkg *comm_pkg; void *send_data; void *recv_data; HYPRE_Int num_requests; hypre_MPI_Request *requests; } hypre_ParCSRCommHandle; /*-------------------------------------------------------------------------- * Accessor macros: hypre_ParCSRCommPkg *--------------------------------------------------------------------------*/ #define hypre_ParCSRCommPkgComm(comm_pkg) (comm_pkg -> comm) #define hypre_ParCSRCommPkgNumSends(comm_pkg) (comm_pkg -> num_sends) #define hypre_ParCSRCommPkgSendProcs(comm_pkg) (comm_pkg -> send_procs) #define hypre_ParCSRCommPkgSendProc(comm_pkg, i) (comm_pkg -> send_procs[i]) #define hypre_ParCSRCommPkgSendMapStarts(comm_pkg) (comm_pkg -> send_map_starts) #define hypre_ParCSRCommPkgSendMapStart(comm_pkg,i)(comm_pkg -> send_map_starts[i]) #define hypre_ParCSRCommPkgSendMapElmts(comm_pkg) (comm_pkg -> send_map_elmts) #define hypre_ParCSRCommPkgSendMapElmt(comm_pkg,i) (comm_pkg -> send_map_elmts[i]) #define hypre_ParCSRCommPkgNumRecvs(comm_pkg) (comm_pkg -> num_recvs) #define hypre_ParCSRCommPkgRecvProcs(comm_pkg) (comm_pkg -> recv_procs) #define hypre_ParCSRCommPkgRecvProc(comm_pkg, i) (comm_pkg -> recv_procs[i]) #define hypre_ParCSRCommPkgRecvVecStarts(comm_pkg) (comm_pkg -> recv_vec_starts) #define hypre_ParCSRCommPkgRecvVecStart(comm_pkg,i)(comm_pkg -> recv_vec_starts[i]) #define hypre_ParCSRCommPkgSendMPITypes(comm_pkg) (comm_pkg -> send_mpi_types) #define hypre_ParCSRCommPkgSendMPIType(comm_pkg,i) (comm_pkg -> send_mpi_types[i]) #define hypre_ParCSRCommPkgRecvMPITypes(comm_pkg) (comm_pkg -> recv_mpi_types) #define hypre_ParCSRCommPkgRecvMPIType(comm_pkg,i) (comm_pkg -> recv_mpi_types[i]) /*-------------------------------------------------------------------------- * Accessor macros: hypre_ParCSRCommHandle *--------------------------------------------------------------------------*/ #define hypre_ParCSRCommHandleCommPkg(comm_handle) (comm_handle -> comm_pkg) #define hypre_ParCSRCommHandleSendData(comm_handle) (comm_handle -> send_data) #define hypre_ParCSRCommHandleRecvData(comm_handle) (comm_handle -> recv_data) #define hypre_ParCSRCommHandleNumRequests(comm_handle) (comm_handle -> num_requests) #define hypre_ParCSRCommHandleRequests(comm_handle) (comm_handle -> requests) #define hypre_ParCSRCommHandleRequest(comm_handle, i) (comm_handle -> requests[i]) #endif /* HYPRE_PAR_CSR_COMMUNICATION_HEADER */
5,177
39.453125
87
h
AMG
AMG-master/parcsr_mv/par_csr_matop.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ #include "_hypre_parcsr_mv.h" #include "_hypre_utilities.h" #include "hypre_hopscotch_hash.h" #include "_hypre_parcsr_mv.h" /* RDF: The following prototype already exists in _hypre_parcsr_ls.h, so * something needs to be reorganized here.*/ #ifdef __cplusplus extern "C" { #endif hypre_CSRMatrix * hypre_ExchangeRAPData( hypre_CSRMatrix *RAP_int, hypre_ParCSRCommPkg *comm_pkg_RT); /* reference seems necessary to prevent a problem with the "headers" script... */ #ifdef __cplusplus } #endif /* The following function was formerly part of hypre_ParMatmul but was removed so it can also be used for multiplication of Boolean matrices */ void hypre_ParMatmul_RowSizes( HYPRE_Int ** C_diag_i, HYPRE_Int ** C_offd_i, /*HYPRE_Int ** B_marker,*/ HYPRE_Int * A_diag_i, HYPRE_Int * A_diag_j, HYPRE_Int * A_offd_i, HYPRE_Int * A_offd_j, HYPRE_Int * B_diag_i, HYPRE_Int * B_diag_j, HYPRE_Int * B_offd_i, HYPRE_Int * B_offd_j, HYPRE_Int * B_ext_diag_i, HYPRE_Int * B_ext_diag_j, HYPRE_Int * B_ext_offd_i, HYPRE_Int * B_ext_offd_j, HYPRE_Int * map_B_to_C, HYPRE_Int *C_diag_size, HYPRE_Int *C_offd_size, HYPRE_Int num_rows_diag_A, HYPRE_Int num_cols_offd_A, HYPRE_Int allsquare, HYPRE_Int num_cols_diag_B, HYPRE_Int num_cols_offd_B, HYPRE_Int num_cols_offd_C ) { HYPRE_Int i1, i2, i3, jj2, jj3; HYPRE_Int jj_count_diag, jj_count_offd, jj_row_begin_diag, jj_row_begin_offd; HYPRE_Int start_indexing = 0; /* start indexing for C_data at 0 */ HYPRE_Int num_threads = hypre_NumThreads(); HYPRE_Int *jj_count_diag_array; HYPRE_Int *jj_count_offd_array; HYPRE_Int ii, size, rest; /* First pass begins here. Computes sizes of C rows. Arrays computed: C_diag_i, C_offd_i, B_marker Arrays needed: (11, all HYPRE_Int*) A_diag_i, A_diag_j, A_offd_i, A_offd_j, B_diag_i, B_diag_j, B_offd_i, B_offd_j, B_ext_i, B_ext_j, col_map_offd_B, col_map_offd_B, B_offd_i, B_offd_j, B_ext_i, B_ext_j, Scalars computed: C_diag_size, C_offd_size Scalars needed: num_rows_diag_A, num_rows_diag_A, num_cols_offd_A, allsquare, first_col_diag_B, n_cols_B, num_cols_offd_B, num_cols_diag_B */ *C_diag_i = hypre_CTAlloc(HYPRE_Int, num_rows_diag_A+1); *C_offd_i = hypre_CTAlloc(HYPRE_Int, num_rows_diag_A+1); jj_count_diag_array = hypre_CTAlloc(HYPRE_Int, num_threads); jj_count_offd_array = hypre_CTAlloc(HYPRE_Int, num_threads); /*----------------------------------------------------------------------- * Loop over rows of A *-----------------------------------------------------------------------*/ size = num_rows_diag_A/num_threads; rest = num_rows_diag_A - size*num_threads; #ifdef HYPRE_USING_OPENMP #pragma omp parallel private(ii, i1, jj_row_begin_diag, jj_row_begin_offd, jj_count_diag, jj_count_offd, jj2, i2, jj3, i3) #endif /*for (ii=0; ii < num_threads; ii++)*/ { HYPRE_Int *B_marker = NULL; HYPRE_Int ns, ne; ii = hypre_GetThreadNum(); if (ii < rest) { ns = ii*size+ii; ne = (ii+1)*size+ii+1; } else { ns = ii*size+rest; ne = (ii+1)*size+rest; } jj_count_diag = start_indexing; jj_count_offd = start_indexing; if (num_cols_diag_B || num_cols_offd_C) B_marker = hypre_CTAlloc(HYPRE_Int, num_cols_diag_B+num_cols_offd_C); for (i1 = 0; i1 < num_cols_diag_B+num_cols_offd_C; i1++) B_marker[i1] = -1; for (i1 = ns; i1 < ne; i1++) { /*-------------------------------------------------------------------- * Set marker for diagonal entry, C_{i1,i1} (for square matrices). *--------------------------------------------------------------------*/ jj_row_begin_diag = jj_count_diag; jj_row_begin_offd = jj_count_offd; if ( allsquare ) { B_marker[i1] = jj_count_diag; jj_count_diag++; } /*----------------------------------------------------------------- * Loop over entries in row i1 of A_offd. *-----------------------------------------------------------------*/ if (num_cols_offd_A) { for (jj2 = A_offd_i[i1]; jj2 < A_offd_i[i1+1]; jj2++) { i2 = A_offd_j[jj2]; /*----------------------------------------------------------- * Loop over entries in row i2 of B_ext. *-----------------------------------------------------------*/ for (jj3 = B_ext_offd_i[i2]; jj3 < B_ext_offd_i[i2+1]; jj3++) { i3 = num_cols_diag_B+B_ext_offd_j[jj3]; /*-------------------------------------------------------- * Check B_marker to see that C_{i1,i3} has not already * been accounted for. If it has not, mark it and increment * counter. *--------------------------------------------------------*/ if (B_marker[i3] < jj_row_begin_offd) { B_marker[i3] = jj_count_offd; jj_count_offd++; } } for (jj3 = B_ext_diag_i[i2]; jj3 < B_ext_diag_i[i2+1]; jj3++) { i3 = B_ext_diag_j[jj3]; if (B_marker[i3] < jj_row_begin_diag) { B_marker[i3] = jj_count_diag; jj_count_diag++; } } } } /*----------------------------------------------------------------- * Loop over entries in row i1 of A_diag. *-----------------------------------------------------------------*/ for (jj2 = A_diag_i[i1]; jj2 < A_diag_i[i1+1]; jj2++) { i2 = A_diag_j[jj2]; /*----------------------------------------------------------- * Loop over entries in row i2 of B_diag. *-----------------------------------------------------------*/ for (jj3 = B_diag_i[i2]; jj3 < B_diag_i[i2+1]; jj3++) { i3 = B_diag_j[jj3]; /*-------------------------------------------------------- * Check B_marker to see that C_{i1,i3} has not already * been accounted for. If it has not, mark it and increment * counter. *--------------------------------------------------------*/ if (B_marker[i3] < jj_row_begin_diag) { B_marker[i3] = jj_count_diag; jj_count_diag++; } } /*----------------------------------------------------------- * Loop over entries in row i2 of B_offd. *-----------------------------------------------------------*/ if (num_cols_offd_B) { for (jj3 = B_offd_i[i2]; jj3 < B_offd_i[i2+1]; jj3++) { i3 = num_cols_diag_B+map_B_to_C[B_offd_j[jj3]]; /*-------------------------------------------------------- * Check B_marker to see that C_{i1,i3} has not already * been accounted for. If it has not, mark it and increment * counter. *--------------------------------------------------------*/ if (B_marker[i3] < jj_row_begin_offd) { B_marker[i3] = jj_count_offd; jj_count_offd++; } } } } /*-------------------------------------------------------------------- * Set C_diag_i and C_offd_i for this row. *--------------------------------------------------------------------*/ (*C_diag_i)[i1] = jj_row_begin_diag; (*C_offd_i)[i1] = jj_row_begin_offd; } jj_count_diag_array[ii] = jj_count_diag; jj_count_offd_array[ii] = jj_count_offd; hypre_TFree(B_marker); #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif if (ii) { jj_count_diag = jj_count_diag_array[0]; jj_count_offd = jj_count_offd_array[0]; for (i1 = 1; i1 < ii; i1++) { jj_count_diag += jj_count_diag_array[i1]; jj_count_offd += jj_count_offd_array[i1]; } for (i1 = ns; i1 < ne; i1++) { (*C_diag_i)[i1] += jj_count_diag; (*C_offd_i)[i1] += jj_count_offd; } } else { (*C_diag_i)[num_rows_diag_A] = 0; (*C_offd_i)[num_rows_diag_A] = 0; for (i1 = 0; i1 < num_threads; i1++) { (*C_diag_i)[num_rows_diag_A] += jj_count_diag_array[i1]; (*C_offd_i)[num_rows_diag_A] += jj_count_offd_array[i1]; } } } /* end parallel loop */ /*----------------------------------------------------------------------- * Allocate C_diag_data and C_diag_j arrays. * Allocate C_offd_data and C_offd_j arrays. *-----------------------------------------------------------------------*/ *C_diag_size = (*C_diag_i)[num_rows_diag_A]; *C_offd_size = (*C_offd_i)[num_rows_diag_A]; hypre_TFree(jj_count_diag_array); hypre_TFree(jj_count_offd_array); /* End of First Pass */ } /*-------------------------------------------------------------------------- * hypre_ParMatmul : multiplies two ParCSRMatrices A and B and returns * the product in ParCSRMatrix C * Note that C does not own the partitionings since its row_starts * is owned by A and col_starts by B. *--------------------------------------------------------------------------*/ hypre_ParCSRMatrix *hypre_ParMatmul( hypre_ParCSRMatrix *A, hypre_ParCSRMatrix *B ) { #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_MATMUL] -= hypre_MPI_Wtime(); #endif MPI_Comm comm = hypre_ParCSRMatrixComm(A); hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); HYPRE_Complex *A_diag_data = hypre_CSRMatrixData(A_diag); HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag); HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag); hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); HYPRE_Complex *A_offd_data = hypre_CSRMatrixData(A_offd); HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd); HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd); HYPRE_Int *row_starts_A = hypre_ParCSRMatrixRowStarts(A); HYPRE_Int num_rows_diag_A = hypre_CSRMatrixNumRows(A_diag); HYPRE_Int num_cols_diag_A = hypre_CSRMatrixNumCols(A_diag); HYPRE_Int num_cols_offd_A = hypre_CSRMatrixNumCols(A_offd); hypre_CSRMatrix *B_diag = hypre_ParCSRMatrixDiag(B); HYPRE_Complex *B_diag_data = hypre_CSRMatrixData(B_diag); HYPRE_Int *B_diag_i = hypre_CSRMatrixI(B_diag); HYPRE_Int *B_diag_j = hypre_CSRMatrixJ(B_diag); hypre_CSRMatrix *B_offd = hypre_ParCSRMatrixOffd(B); HYPRE_Int *col_map_offd_B = hypre_ParCSRMatrixColMapOffd(B); HYPRE_Complex *B_offd_data = hypre_CSRMatrixData(B_offd); HYPRE_Int *B_offd_i = hypre_CSRMatrixI(B_offd); HYPRE_Int *B_offd_j = hypre_CSRMatrixJ(B_offd); HYPRE_Int first_col_diag_B = hypre_ParCSRMatrixFirstColDiag(B); HYPRE_Int last_col_diag_B; HYPRE_Int *col_starts_B = hypre_ParCSRMatrixColStarts(B); HYPRE_Int num_rows_diag_B = hypre_CSRMatrixNumRows(B_diag); HYPRE_Int num_cols_diag_B = hypre_CSRMatrixNumCols(B_diag); HYPRE_Int num_cols_offd_B = hypre_CSRMatrixNumCols(B_offd); hypre_ParCSRMatrix *C; HYPRE_Int *col_map_offd_C; HYPRE_Int *map_B_to_C=NULL; hypre_CSRMatrix *C_diag; HYPRE_Complex *C_diag_data; HYPRE_Int *C_diag_i; HYPRE_Int *C_diag_j; hypre_CSRMatrix *C_offd; HYPRE_Complex *C_offd_data=NULL; HYPRE_Int *C_offd_i=NULL; HYPRE_Int *C_offd_j=NULL; HYPRE_Int C_diag_size; HYPRE_Int C_offd_size; HYPRE_Int num_cols_offd_C = 0; hypre_CSRMatrix *Bs_ext; HYPRE_Complex *Bs_ext_data; HYPRE_Int *Bs_ext_i; HYPRE_Int *Bs_ext_j; HYPRE_Complex *B_ext_diag_data; HYPRE_Int *B_ext_diag_i; HYPRE_Int *B_ext_diag_j; HYPRE_Int B_ext_diag_size; HYPRE_Complex *B_ext_offd_data; HYPRE_Int *B_ext_offd_i; HYPRE_Int *B_ext_offd_j; HYPRE_Int B_ext_offd_size; HYPRE_Int n_rows_A, n_cols_A; HYPRE_Int n_rows_B, n_cols_B; HYPRE_Int allsquare = 0; HYPRE_Int num_procs; HYPRE_Int *my_diag_array; HYPRE_Int *my_offd_array; HYPRE_Int max_num_threads; HYPRE_Complex zero = 0.0; n_rows_A = hypre_ParCSRMatrixGlobalNumRows(A); n_cols_A = hypre_ParCSRMatrixGlobalNumCols(A); n_rows_B = hypre_ParCSRMatrixGlobalNumRows(B); n_cols_B = hypre_ParCSRMatrixGlobalNumCols(B); max_num_threads = hypre_NumThreads(); my_diag_array = hypre_CTAlloc(HYPRE_Int, max_num_threads); my_offd_array = hypre_CTAlloc(HYPRE_Int, max_num_threads); if (n_cols_A != n_rows_B || num_cols_diag_A != num_rows_diag_B) { hypre_error_w_msg(HYPRE_ERROR_GENERIC," Error! Incompatible matrix dimensions!\n"); return NULL; } if ( num_rows_diag_A==num_cols_diag_B) allsquare = 1; /*----------------------------------------------------------------------- * Extract B_ext, i.e. portion of B that is stored on neighbor procs * and needed locally for matrix matrix product *-----------------------------------------------------------------------*/ hypre_MPI_Comm_size(comm, &num_procs); #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_RENUMBER_COLIDX] -= hypre_MPI_Wtime(); #endif if (num_procs > 1) { /*--------------------------------------------------------------------- * If there exists no CommPkg for A, a CommPkg is generated using * equally load balanced partitionings within * hypre_ParCSRMatrixExtractBExt *--------------------------------------------------------------------*/ Bs_ext = hypre_ParCSRMatrixExtractBExt(B,A,1); Bs_ext_data = hypre_CSRMatrixData(Bs_ext); Bs_ext_i = hypre_CSRMatrixI(Bs_ext); Bs_ext_j = hypre_CSRMatrixJ(Bs_ext); } B_ext_diag_i = hypre_CTAlloc(HYPRE_Int, num_cols_offd_A+1); B_ext_offd_i = hypre_CTAlloc(HYPRE_Int, num_cols_offd_A+1); B_ext_diag_size = 0; B_ext_offd_size = 0; last_col_diag_B = first_col_diag_B + num_cols_diag_B -1; #ifdef HYPRE_CONCURRENT_HOPSCOTCH hypre_UnorderedIntSet set; #pragma omp parallel { HYPRE_Int size, rest, ii; HYPRE_Int ns, ne; HYPRE_Int i1, i, j; HYPRE_Int my_offd_size, my_diag_size; HYPRE_Int cnt_offd, cnt_diag; HYPRE_Int num_threads = hypre_NumActiveThreads(); size = num_cols_offd_A/num_threads; rest = num_cols_offd_A - size*num_threads; ii = hypre_GetThreadNum(); if (ii < rest) { ns = ii*size+ii; ne = (ii+1)*size+ii+1; } else { ns = ii*size+rest; ne = (ii+1)*size+rest; } my_diag_size = 0; my_offd_size = 0; for (i=ns; i < ne; i++) { B_ext_diag_i[i] = my_diag_size; B_ext_offd_i[i] = my_offd_size; for (j=Bs_ext_i[i]; j < Bs_ext_i[i+1]; j++) if (Bs_ext_j[j] < first_col_diag_B || Bs_ext_j[j] > last_col_diag_B) my_offd_size++; else my_diag_size++; } my_diag_array[ii] = my_diag_size; my_offd_array[ii] = my_offd_size; #pragma omp barrier if (ii) { my_diag_size = my_diag_array[0]; my_offd_size = my_offd_array[0]; for (i1 = 1; i1 < ii; i1++) { my_diag_size += my_diag_array[i1]; my_offd_size += my_offd_array[i1]; } for (i1 = ns; i1 < ne; i1++) { B_ext_diag_i[i1] += my_diag_size; B_ext_offd_i[i1] += my_offd_size; } } else { B_ext_diag_size = 0; B_ext_offd_size = 0; for (i1 = 0; i1 < num_threads; i1++) { B_ext_diag_size += my_diag_array[i1]; B_ext_offd_size += my_offd_array[i1]; } B_ext_diag_i[num_cols_offd_A] = B_ext_diag_size; B_ext_offd_i[num_cols_offd_A] = B_ext_offd_size; if (B_ext_diag_size) { B_ext_diag_j = hypre_CTAlloc(HYPRE_Int, B_ext_diag_size); B_ext_diag_data = hypre_CTAlloc(HYPRE_Complex, B_ext_diag_size); } if (B_ext_offd_size) { B_ext_offd_j = hypre_CTAlloc(HYPRE_Int, B_ext_offd_size); B_ext_offd_data = hypre_CTAlloc(HYPRE_Complex, B_ext_offd_size); } hypre_UnorderedIntSetCreate(&set, B_ext_offd_size + num_cols_offd_B, 16*hypre_NumThreads()); } #pragma omp barrier cnt_offd = B_ext_offd_i[ns]; cnt_diag = B_ext_diag_i[ns]; for (i=ns; i < ne; i++) { for (j=Bs_ext_i[i]; j < Bs_ext_i[i+1]; j++) if (Bs_ext_j[j] < first_col_diag_B || Bs_ext_j[j] > last_col_diag_B) { hypre_UnorderedIntSetPut(&set, Bs_ext_j[j]); B_ext_offd_j[cnt_offd] = Bs_ext_j[j]; B_ext_offd_data[cnt_offd++] = Bs_ext_data[j]; } else { B_ext_diag_j[cnt_diag] = Bs_ext_j[j] - first_col_diag_B; B_ext_diag_data[cnt_diag++] = Bs_ext_data[j]; } } HYPRE_Int i_begin, i_end; hypre_GetSimpleThreadPartition(&i_begin, &i_end, num_cols_offd_B); for (i = i_begin; i < i_end; i++) { hypre_UnorderedIntSetPut(&set, col_map_offd_B[i]); } } /* omp parallel */ if (num_procs > 1) { hypre_CSRMatrixDestroy(Bs_ext); Bs_ext = NULL; } col_map_offd_C = hypre_UnorderedIntSetCopyToArray(&set, &num_cols_offd_C); hypre_UnorderedIntSetDestroy(&set); hypre_UnorderedIntMap col_map_offd_C_inverse; hypre_sort_and_create_inverse_map(col_map_offd_C, num_cols_offd_C, &col_map_offd_C, &col_map_offd_C_inverse); HYPRE_Int i, j; #pragma omp parallel for private(j) HYPRE_SMP_SCHEDULE for (i = 0; i < num_cols_offd_A; i++) for (j=B_ext_offd_i[i]; j < B_ext_offd_i[i+1]; j++) B_ext_offd_j[j] = hypre_UnorderedIntMapGet(&col_map_offd_C_inverse, B_ext_offd_j[j]); if (num_cols_offd_C) { hypre_UnorderedIntMapDestroy(&col_map_offd_C_inverse); } hypre_TFree(my_diag_array); hypre_TFree(my_offd_array); if (num_cols_offd_B) { HYPRE_Int i; map_B_to_C = hypre_CTAlloc(HYPRE_Int,num_cols_offd_B); #pragma omp parallel private(i) { HYPRE_Int i_begin, i_end; hypre_GetSimpleThreadPartition(&i_begin, &i_end, num_cols_offd_C); HYPRE_Int cnt; if (i_end > i_begin) { cnt = hypre_LowerBound(col_map_offd_B, col_map_offd_B + num_cols_offd_B, col_map_offd_C[i_begin]) - col_map_offd_B; } for (i = i_begin; i < i_end && cnt < num_cols_offd_B; i++) { if (col_map_offd_C[i] == col_map_offd_B[cnt]) { map_B_to_C[cnt++] = i; } } } } #else /* !HYPRE_CONCURRENT_HOPSCOTCH */ HYPRE_Int *temp; #ifdef HYPRE_USING_OPENMP #pragma omp parallel #endif { HYPRE_Int size, rest, ii; HYPRE_Int ns, ne; HYPRE_Int i1, i, j; HYPRE_Int my_offd_size, my_diag_size; HYPRE_Int cnt_offd, cnt_diag; HYPRE_Int num_threads = hypre_NumActiveThreads(); size = num_cols_offd_A/num_threads; rest = num_cols_offd_A - size*num_threads; ii = hypre_GetThreadNum(); if (ii < rest) { ns = ii*size+ii; ne = (ii+1)*size+ii+1; } else { ns = ii*size+rest; ne = (ii+1)*size+rest; } my_diag_size = 0; my_offd_size = 0; for (i=ns; i < ne; i++) { B_ext_diag_i[i] = my_diag_size; B_ext_offd_i[i] = my_offd_size; for (j=Bs_ext_i[i]; j < Bs_ext_i[i+1]; j++) if (Bs_ext_j[j] < first_col_diag_B || Bs_ext_j[j] > last_col_diag_B) my_offd_size++; else my_diag_size++; } my_diag_array[ii] = my_diag_size; my_offd_array[ii] = my_offd_size; #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif if (ii) { my_diag_size = my_diag_array[0]; my_offd_size = my_offd_array[0]; for (i1 = 1; i1 < ii; i1++) { my_diag_size += my_diag_array[i1]; my_offd_size += my_offd_array[i1]; } for (i1 = ns; i1 < ne; i1++) { B_ext_diag_i[i1] += my_diag_size; B_ext_offd_i[i1] += my_offd_size; } } else { B_ext_diag_size = 0; B_ext_offd_size = 0; for (i1 = 0; i1 < num_threads; i1++) { B_ext_diag_size += my_diag_array[i1]; B_ext_offd_size += my_offd_array[i1]; } B_ext_diag_i[num_cols_offd_A] = B_ext_diag_size; B_ext_offd_i[num_cols_offd_A] = B_ext_offd_size; if (B_ext_diag_size) { B_ext_diag_j = hypre_CTAlloc(HYPRE_Int, B_ext_diag_size); B_ext_diag_data = hypre_CTAlloc(HYPRE_Complex, B_ext_diag_size); } if (B_ext_offd_size) { B_ext_offd_j = hypre_CTAlloc(HYPRE_Int, B_ext_offd_size); B_ext_offd_data = hypre_CTAlloc(HYPRE_Complex, B_ext_offd_size); } if (B_ext_offd_size || num_cols_offd_B) temp = hypre_CTAlloc(HYPRE_Int, B_ext_offd_size+num_cols_offd_B); } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif cnt_offd = B_ext_offd_i[ns]; cnt_diag = B_ext_diag_i[ns]; for (i=ns; i < ne; i++) { for (j=Bs_ext_i[i]; j < Bs_ext_i[i+1]; j++) if (Bs_ext_j[j] < first_col_diag_B || Bs_ext_j[j] > last_col_diag_B) { temp[cnt_offd] = Bs_ext_j[j]; B_ext_offd_j[cnt_offd] = Bs_ext_j[j]; B_ext_offd_data[cnt_offd++] = Bs_ext_data[j]; } else { B_ext_diag_j[cnt_diag] = Bs_ext_j[j] - first_col_diag_B; B_ext_diag_data[cnt_diag++] = Bs_ext_data[j]; } } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif if (ii == 0) { HYPRE_Int cnt; if (num_procs > 1) { hypre_CSRMatrixDestroy(Bs_ext); Bs_ext = NULL; } cnt = 0; if (B_ext_offd_size || num_cols_offd_B) { cnt = B_ext_offd_size; for (i=0; i < num_cols_offd_B; i++) temp[cnt++] = col_map_offd_B[i]; if (cnt) { HYPRE_Int value; hypre_qsort0(temp, 0, cnt-1); num_cols_offd_C = 1; value = temp[0]; for (i=1; i < cnt; i++) { if (temp[i] > value) { value = temp[i]; temp[num_cols_offd_C++] = value; } } } if (num_cols_offd_C) col_map_offd_C = hypre_CTAlloc(HYPRE_Int,num_cols_offd_C); for (i=0; i < num_cols_offd_C; i++) col_map_offd_C[i] = temp[i]; hypre_TFree(temp); } } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif for (i=ns; i < ne; i++) for (j=B_ext_offd_i[i]; j < B_ext_offd_i[i+1]; j++) B_ext_offd_j[j] = hypre_BinarySearch(col_map_offd_C, B_ext_offd_j[j], num_cols_offd_C); } /* end parallel region */ hypre_TFree(my_diag_array); hypre_TFree(my_offd_array); if (num_cols_offd_B) { HYPRE_Int i, cnt; map_B_to_C = hypre_CTAlloc(HYPRE_Int,num_cols_offd_B); cnt = 0; for (i=0; i < num_cols_offd_C; i++) if (col_map_offd_C[i] == col_map_offd_B[cnt]) { map_B_to_C[cnt++] = i; if (cnt == num_cols_offd_B) break; } } #endif /* !HYPRE_CONCURRENT_HOPSCOTCH */ #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_RENUMBER_COLIDX] += hypre_MPI_Wtime(); #endif hypre_ParMatmul_RowSizes( /*&C_diag_i, &C_offd_i, &B_marker,*/ &C_diag_i, &C_offd_i, A_diag_i, A_diag_j, A_offd_i, A_offd_j, B_diag_i, B_diag_j, B_offd_i, B_offd_j, B_ext_diag_i, B_ext_diag_j, B_ext_offd_i, B_ext_offd_j, map_B_to_C, &C_diag_size, &C_offd_size, num_rows_diag_A, num_cols_offd_A, allsquare, num_cols_diag_B, num_cols_offd_B, num_cols_offd_C ); /*----------------------------------------------------------------------- * Allocate C_diag_data and C_diag_j arrays. * Allocate C_offd_data and C_offd_j arrays. *-----------------------------------------------------------------------*/ last_col_diag_B = first_col_diag_B + num_cols_diag_B - 1; C_diag_data = hypre_CTAlloc(HYPRE_Complex, C_diag_size); C_diag_j = hypre_CTAlloc(HYPRE_Int, C_diag_size); if (C_offd_size) { C_offd_data = hypre_CTAlloc(HYPRE_Complex, C_offd_size); C_offd_j = hypre_CTAlloc(HYPRE_Int, C_offd_size); } /*----------------------------------------------------------------------- * Second Pass: Fill in C_diag_data and C_diag_j. * Second Pass: Fill in C_offd_data and C_offd_j. *-----------------------------------------------------------------------*/ /*----------------------------------------------------------------------- * Initialize some stuff. *-----------------------------------------------------------------------*/ #ifdef HYPRE_USING_OPENMP #pragma omp parallel #endif { HYPRE_Int *B_marker = NULL; HYPRE_Int ns, ne, size, rest, ii; HYPRE_Int i1, i2, i3, jj2, jj3; HYPRE_Int jj_row_begin_diag, jj_count_diag; HYPRE_Int jj_row_begin_offd, jj_count_offd; HYPRE_Int num_threads; HYPRE_Complex a_entry; /*, a_b_product;*/ ii = hypre_GetThreadNum(); num_threads = hypre_NumActiveThreads(); size = num_rows_diag_A/num_threads; rest = num_rows_diag_A - size*num_threads; if (ii < rest) { ns = ii*size+ii; ne = (ii+1)*size+ii+1; } else { ns = ii*size+rest; ne = (ii+1)*size+rest; } jj_count_diag = C_diag_i[ns]; jj_count_offd = C_offd_i[ns]; if (num_cols_diag_B || num_cols_offd_C) B_marker = hypre_CTAlloc(HYPRE_Int, num_cols_diag_B+num_cols_offd_C); for (i1 = 0; i1 < num_cols_diag_B+num_cols_offd_C; i1++) B_marker[i1] = -1; /*----------------------------------------------------------------------- * Loop over interior c-points. *-----------------------------------------------------------------------*/ for (i1 = ns; i1 < ne; i1++) { /*-------------------------------------------------------------------- * Create diagonal entry, C_{i1,i1} *--------------------------------------------------------------------*/ jj_row_begin_diag = jj_count_diag; jj_row_begin_offd = jj_count_offd; if ( allsquare ) { B_marker[i1] = jj_count_diag; C_diag_data[jj_count_diag] = zero; C_diag_j[jj_count_diag] = i1; jj_count_diag++; } /*----------------------------------------------------------------- * Loop over entries in row i1 of A_offd. *-----------------------------------------------------------------*/ if (num_cols_offd_A) { for (jj2 = A_offd_i[i1]; jj2 < A_offd_i[i1+1]; jj2++) { i2 = A_offd_j[jj2]; a_entry = A_offd_data[jj2]; /*----------------------------------------------------------- * Loop over entries in row i2 of B_ext. *-----------------------------------------------------------*/ for (jj3 = B_ext_offd_i[i2]; jj3 < B_ext_offd_i[i2+1]; jj3++) { i3 = num_cols_diag_B+B_ext_offd_j[jj3]; /*-------------------------------------------------------- * Check B_marker to see that C_{i1,i3} has not already * been accounted for. If it has not, create a new entry. * If it has, add new contribution. *--------------------------------------------------------*/ if (B_marker[i3] < jj_row_begin_offd) { B_marker[i3] = jj_count_offd; C_offd_data[jj_count_offd] = a_entry*B_ext_offd_data[jj3]; C_offd_j[jj_count_offd] = i3-num_cols_diag_B; jj_count_offd++; } else C_offd_data[B_marker[i3]] += a_entry*B_ext_offd_data[jj3]; } for (jj3 = B_ext_diag_i[i2]; jj3 < B_ext_diag_i[i2+1]; jj3++) { i3 = B_ext_diag_j[jj3]; if (B_marker[i3] < jj_row_begin_diag) { B_marker[i3] = jj_count_diag; C_diag_data[jj_count_diag] = a_entry*B_ext_diag_data[jj3]; C_diag_j[jj_count_diag] = i3; jj_count_diag++; } else C_diag_data[B_marker[i3]] += a_entry*B_ext_diag_data[jj3]; } } } /*----------------------------------------------------------------- * Loop over entries in row i1 of A_diag. *-----------------------------------------------------------------*/ for (jj2 = A_diag_i[i1]; jj2 < A_diag_i[i1+1]; jj2++) { i2 = A_diag_j[jj2]; a_entry = A_diag_data[jj2]; /*----------------------------------------------------------- * Loop over entries in row i2 of B_diag. *-----------------------------------------------------------*/ for (jj3 = B_diag_i[i2]; jj3 < B_diag_i[i2+1]; jj3++) { i3 = B_diag_j[jj3]; /*-------------------------------------------------------- * Check B_marker to see that C_{i1,i3} has not already * been accounted for. If it has not, create a new entry. * If it has, add new contribution. *--------------------------------------------------------*/ if (B_marker[i3] < jj_row_begin_diag) { B_marker[i3] = jj_count_diag; C_diag_data[jj_count_diag] = a_entry*B_diag_data[jj3]; C_diag_j[jj_count_diag] = i3; jj_count_diag++; } else { C_diag_data[B_marker[i3]] += a_entry*B_diag_data[jj3]; } } if (num_cols_offd_B) { for (jj3 = B_offd_i[i2]; jj3 < B_offd_i[i2+1]; jj3++) { i3 = num_cols_diag_B+map_B_to_C[B_offd_j[jj3]]; /*-------------------------------------------------------- * Check B_marker to see that C_{i1,i3} has not already * been accounted for. If it has not, create a new entry. * If it has, add new contribution. *--------------------------------------------------------*/ if (B_marker[i3] < jj_row_begin_offd) { B_marker[i3] = jj_count_offd; C_offd_data[jj_count_offd] = a_entry*B_offd_data[jj3]; C_offd_j[jj_count_offd] = i3-num_cols_diag_B; jj_count_offd++; } else { C_offd_data[B_marker[i3]] += a_entry*B_offd_data[jj3]; } } } } } hypre_TFree(B_marker); } /*end parallel region */ C = hypre_ParCSRMatrixCreate(comm, n_rows_A, n_cols_B, row_starts_A, col_starts_B, num_cols_offd_C, C_diag_size, C_offd_size); /* Note that C does not own the partitionings */ hypre_ParCSRMatrixSetRowStartsOwner(C,0); hypre_ParCSRMatrixSetColStartsOwner(C,0); C_diag = hypre_ParCSRMatrixDiag(C); hypre_CSRMatrixData(C_diag) = C_diag_data; hypre_CSRMatrixI(C_diag) = C_diag_i; hypre_CSRMatrixJ(C_diag) = C_diag_j; C_offd = hypre_ParCSRMatrixOffd(C); hypre_CSRMatrixI(C_offd) = C_offd_i; hypre_ParCSRMatrixOffd(C) = C_offd; if (num_cols_offd_C) { hypre_CSRMatrixData(C_offd) = C_offd_data; hypre_CSRMatrixJ(C_offd) = C_offd_j; hypre_ParCSRMatrixColMapOffd(C) = col_map_offd_C; } /*----------------------------------------------------------------------- * Free various arrays *-----------------------------------------------------------------------*/ hypre_TFree(B_ext_diag_i); if (B_ext_diag_size) { hypre_TFree(B_ext_diag_j); hypre_TFree(B_ext_diag_data); } hypre_TFree(B_ext_offd_i); if (B_ext_offd_size) { hypre_TFree(B_ext_offd_j); hypre_TFree(B_ext_offd_data); } if (num_cols_offd_B) hypre_TFree(map_B_to_C); #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_MATMUL] += hypre_MPI_Wtime(); #endif return C; } /* The following function was formerly part of hypre_ParCSRMatrixExtractBExt but the code was removed so it can be used for a corresponding function for Boolean matrices JSP: to allow communication overlapping, it returns comm_handle_idx and comm_handle_data. Before accessing B, they should be destroyed (including send_data contained in the comm_handle). */ void hypre_ParCSRMatrixExtractBExt_Arrays_Overlap( HYPRE_Int ** pB_ext_i, HYPRE_Int ** pB_ext_j, HYPRE_Complex ** pB_ext_data, HYPRE_Int ** pB_ext_row_map, HYPRE_Int * num_nonzeros, HYPRE_Int data, HYPRE_Int find_row_map, MPI_Comm comm, hypre_ParCSRCommPkg * comm_pkg, HYPRE_Int num_cols_B, HYPRE_Int num_recvs, HYPRE_Int num_sends, HYPRE_Int first_col_diag, HYPRE_Int * row_starts, HYPRE_Int * recv_vec_starts, HYPRE_Int * send_map_starts, HYPRE_Int * send_map_elmts, HYPRE_Int * diag_i, HYPRE_Int * diag_j, HYPRE_Int * offd_i, HYPRE_Int * offd_j, HYPRE_Int * col_map_offd, HYPRE_Real * diag_data, HYPRE_Real * offd_data, hypre_ParCSRCommHandle **comm_handle_idx, hypre_ParCSRCommHandle **comm_handle_data, HYPRE_Int *CF_marker, HYPRE_Int *CF_marker_offd, HYPRE_Int skip_fine, /* 1 if only coarse points are needed */ HYPRE_Int skip_same_sign /* 1 if only points that have the same sign are needed */ // extended based long range interpolation: skip_fine = 1, skip_same_sign = 0 for S matrix, skip_fine = 1, skip_same_sign = 1 for A matrix // other interpolation: skip_fine = 0, skip_same_sign = 0 ) { hypre_ParCSRCommHandle *comm_handle, *row_map_comm_handle = NULL; hypre_ParCSRCommPkg *tmp_comm_pkg; HYPRE_Int *B_int_i; HYPRE_Int *B_int_j; HYPRE_Int *B_ext_i; HYPRE_Int * B_ext_j; HYPRE_Complex * B_ext_data; HYPRE_Complex * B_int_data; HYPRE_Int * B_int_row_map; HYPRE_Int * B_ext_row_map; HYPRE_Int num_procs, my_id; HYPRE_Int *jdata_recv_vec_starts; HYPRE_Int *jdata_send_map_starts; HYPRE_Int i, j, k; HYPRE_Int start_index; /*HYPRE_Int jrow;*/ HYPRE_Int num_rows_B_ext; HYPRE_Int *prefix_sum_workspace; hypre_MPI_Comm_size(comm,&num_procs); hypre_MPI_Comm_rank(comm,&my_id); #ifdef HYPRE_NO_GLOBAL_PARTITION HYPRE_Int first_row_index = row_starts[0]; #else HYPRE_Int first_row_index = row_starts[my_id]; HYPRE_Int *send_procs = hypre_ParCSRCommPkgSendProcs(comm_pkg); #endif num_rows_B_ext = recv_vec_starts[num_recvs]; if ( num_rows_B_ext < 0 ) { /* no B_ext, no communication */ *pB_ext_i = NULL; *pB_ext_j = NULL; if ( data ) *pB_ext_data = NULL; if ( find_row_map ) *pB_ext_row_map = NULL; *num_nonzeros = 0; return; }; B_int_i = hypre_CTAlloc(HYPRE_Int, send_map_starts[num_sends]+1); B_ext_i = hypre_CTAlloc(HYPRE_Int, num_rows_B_ext+1); *pB_ext_i = B_ext_i; if ( find_row_map ) { B_int_row_map = hypre_CTAlloc( HYPRE_Int, send_map_starts[num_sends]+1 ); B_ext_row_map = hypre_CTAlloc( HYPRE_Int, num_rows_B_ext+1 ); *pB_ext_row_map = B_ext_row_map; }; /*-------------------------------------------------------------------------- * generate B_int_i through adding number of row-elements of offd and diag * for corresponding rows. B_int_i[j+1] contains the number of elements of * a row j (which is determined through send_map_elmts) *--------------------------------------------------------------------------*/ jdata_send_map_starts = hypre_CTAlloc(HYPRE_Int, num_sends+1); jdata_recv_vec_starts = hypre_CTAlloc(HYPRE_Int, num_recvs+1); jdata_send_map_starts[0] = B_int_i[0] = 0; /*HYPRE_Int prefix_sum_workspace[(hypre_NumThreads() + 1)*num_sends];*/ prefix_sum_workspace = hypre_TAlloc(HYPRE_Int, (hypre_NumThreads() + 1)*num_sends); #ifdef HYPRE_USING_OPENMP #pragma omp parallel private(i,j,k) #endif { /*HYPRE_Int counts[num_sends];*/ HYPRE_Int *counts; counts = hypre_TAlloc(HYPRE_Int, num_sends); for (i=0; i < num_sends; i++) { HYPRE_Int j_begin, j_end; hypre_GetSimpleThreadPartition(&j_begin, &j_end, send_map_starts[i + 1] - send_map_starts[i]); j_begin += send_map_starts[i]; j_end += send_map_starts[i]; HYPRE_Int count = 0; if (skip_fine && skip_same_sign) { #ifndef HYPRE_NO_GLOBAL_PARTITION HYPRE_Int send_proc = send_procs[i]; HYPRE_Int send_proc_first_row = row_starts[send_proc]; HYPRE_Int send_proc_last_row = row_starts[send_proc + 1]; #endif for (j = j_begin; j < j_end; j++) { HYPRE_Int jrow = send_map_elmts[j]; HYPRE_Int len = 0; if (diag_data[diag_i[jrow]] >= 0) { for (k = diag_i[jrow] + 1; k < diag_i[jrow + 1]; k++) { if (diag_data[k] < 0 && CF_marker[diag_j[k]] >= 0) len++; } for (k = offd_i[jrow]; k < offd_i[jrow + 1]; k++) { #ifdef HYPRE_NO_GLOBAL_PARTITION if (offd_data[k] < 0) len++; #else HYPRE_Int c = offd_j[k]; HYPRE_Int c_global = col_map_offd[c]; if (offd_data[k] < 0 && (CF_marker_offd[c] >= 0 || (c_global >= send_proc_first_row && c_global < send_proc_last_row))) len++; #endif } } else { for (k = diag_i[jrow] + 1; k < diag_i[jrow + 1]; k++) { if (diag_data[k] > 0 && CF_marker[diag_j[k]] >= 0) len++; } for (k = offd_i[jrow]; k < offd_i[jrow + 1]; k++) { #ifdef HYPRE_NO_GLOBAL_PARTITION if (offd_data[k] > 0) len++; #else HYPRE_Int c = offd_j[k]; HYPRE_Int c_global = col_map_offd[c]; if (offd_data[k] > 0 && (CF_marker_offd[c] >= 0 || (c_global >= send_proc_first_row && c_global < send_proc_last_row))) len++; #endif } } B_int_i[j + 1] = len; count += len; } } else if (skip_fine) { for (j = j_begin; j < j_end; j++) { HYPRE_Int jrow = send_map_elmts[j]; HYPRE_Int len = 0; for (k = diag_i[jrow]; k < diag_i[jrow + 1]; k++) { if (CF_marker[diag_j[k]] >= 0) len++; } for (k = offd_i[jrow]; k < offd_i[jrow + 1]; k++) { if (CF_marker_offd[offd_j[k]] >= 0) len++; } B_int_i[j + 1] = len; count += len; } } else { for (j = j_begin; j < j_end; j++) { HYPRE_Int jrow = send_map_elmts[j]; HYPRE_Int len = diag_i[jrow + 1] - diag_i[jrow]; len += offd_i[jrow + 1] - offd_i[jrow]; B_int_i[j + 1] = len; count += len; } } if (find_row_map) { for (j = j_begin; j < j_end; j++) { HYPRE_Int jrow = send_map_elmts[j]; B_int_row_map[j] = jrow + first_row_index; } } counts[i] = count; } hypre_prefix_sum_multiple(counts, jdata_send_map_starts + 1, num_sends, prefix_sum_workspace); #ifdef HYPRE_USING_OPENMP #pragma omp master #endif { for (i = 1; i < num_sends; i++) { jdata_send_map_starts[i + 1] += jdata_send_map_starts[i]; } /*-------------------------------------------------------------------------- * initialize communication *--------------------------------------------------------------------------*/ comm_handle = hypre_ParCSRCommHandleCreate(11,comm_pkg, &B_int_i[1],&(B_ext_i[1]) ); if ( find_row_map ) { /* scatter/gather B_int row numbers to form array of B_ext row numbers */ row_map_comm_handle = hypre_ParCSRCommHandleCreate (11,comm_pkg, B_int_row_map, B_ext_row_map ); } B_int_j = hypre_TAlloc(HYPRE_Int, jdata_send_map_starts[num_sends]); if (data) B_int_data = hypre_TAlloc(HYPRE_Complex, jdata_send_map_starts[num_sends]); } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif for (i=0; i < num_sends; i++) { HYPRE_Int j_begin, j_end; hypre_GetSimpleThreadPartition(&j_begin, &j_end, send_map_starts[i + 1] - send_map_starts[i]); j_begin += send_map_starts[i]; j_end += send_map_starts[i]; HYPRE_Int count = counts[i] + jdata_send_map_starts[i]; if (data) { if (skip_same_sign && skip_fine) { #ifndef HYPRE_NO_GLOBAL_PARTITION HYPRE_Int send_proc = send_procs[i]; HYPRE_Int send_proc_first_row = row_starts[send_proc]; HYPRE_Int send_proc_last_row = row_starts[send_proc + 1]; #endif for (j = j_begin; j < j_end; j++) { HYPRE_Int jrow = send_map_elmts[j]; /*HYPRE_Int count_begin = count;*/ if (diag_data[diag_i[jrow]] >= 0) { for (k = diag_i[jrow] + 1; k < diag_i[jrow + 1]; k++) { if (diag_data[k] < 0 && CF_marker[diag_j[k]] >= 0) { B_int_j[count] = diag_j[k]+first_col_diag; B_int_data[count] = diag_data[k]; count++; } } for (k = offd_i[jrow]; k < offd_i[jrow + 1]; k++) { HYPRE_Int c = offd_j[k]; HYPRE_Int c_global = col_map_offd[c]; #ifdef HYPRE_NO_GLOBAL_PARTITION if (offd_data[k] < 0) #else if (offd_data[k] < 0 && (CF_marker_offd[c] >= 0 || (c_global >= send_proc_first_row && c_global < send_proc_last_row))) #endif { B_int_j[count] = c_global; B_int_data[count] = offd_data[k]; count++; } } } else { for (k = diag_i[jrow] + 1; k < diag_i[jrow + 1]; k++) { if (diag_data[k] > 0 && CF_marker[diag_j[k]] >= 0) { B_int_j[count] = diag_j[k]+first_col_diag; B_int_data[count] = diag_data[k]; count++; } } for (k = offd_i[jrow]; k < offd_i[jrow + 1]; k++) { HYPRE_Int c = offd_j[k]; HYPRE_Int c_global = col_map_offd[c]; #ifdef HYPRE_NO_GLOBAL_PARTITION if (offd_data[k] > 0) #else if (offd_data[k] > 0 && (CF_marker_offd[c] >= 0 || (c_global >= send_proc_first_row && c_global < send_proc_last_row))) #endif { B_int_j[count] = c_global; B_int_data[count] = offd_data[k]; count++; } } } } } else { for (j = j_begin; j < j_end; ++j) { HYPRE_Int jrow = send_map_elmts[j]; for (k=diag_i[jrow]; k < diag_i[jrow+1]; k++) { B_int_j[count] = diag_j[k]+first_col_diag; B_int_data[count] = diag_data[k]; count++; } for (k=offd_i[jrow]; k < offd_i[jrow+1]; k++) { B_int_j[count] = col_map_offd[offd_j[k]]; B_int_data[count] = offd_data[k]; count++; } } } } // data else { if (skip_fine) { for (j = j_begin; j < j_end; j++) { HYPRE_Int jrow = send_map_elmts[j]; for (k = diag_i[jrow]; k < diag_i[jrow + 1]; k++) { if (CF_marker[diag_j[k]] >= 0) { B_int_j[count] = diag_j[k] + first_col_diag; count++; } } for (k = offd_i[jrow]; k < offd_i[jrow + 1]; k++) { if (CF_marker_offd[offd_j[k]] >= 0) { B_int_j[count] = col_map_offd[offd_j[k]]; count++; } } } } else { for (j = j_begin; j < j_end; ++j) { HYPRE_Int jrow = send_map_elmts[j]; for (k=diag_i[jrow]; k < diag_i[jrow+1]; k++) { B_int_j[count] = diag_j[k]+first_col_diag; count++; } for (k=offd_i[jrow]; k < offd_i[jrow+1]; k++) { B_int_j[count] = col_map_offd[offd_j[k]]; count++; } } } } // !data } /* for each send target */ hypre_TFree(counts); } /* omp parallel. JSP: this takes most of time in this function */ hypre_TFree(prefix_sum_workspace); tmp_comm_pkg = hypre_CTAlloc(hypre_ParCSRCommPkg,1); hypre_ParCSRCommPkgComm(tmp_comm_pkg) = comm; hypre_ParCSRCommPkgNumSends(tmp_comm_pkg) = num_sends; hypre_ParCSRCommPkgNumRecvs(tmp_comm_pkg) = num_recvs; hypre_ParCSRCommPkgSendProcs(tmp_comm_pkg) = hypre_ParCSRCommPkgSendProcs(comm_pkg); hypre_ParCSRCommPkgRecvProcs(tmp_comm_pkg) = hypre_ParCSRCommPkgRecvProcs(comm_pkg); hypre_ParCSRCommPkgSendMapStarts(tmp_comm_pkg) = jdata_send_map_starts; hypre_ParCSRCommHandleDestroy(comm_handle); comm_handle = NULL; /*-------------------------------------------------------------------------- * after communication exchange B_ext_i[j+1] contains the number of elements * of a row j ! * evaluate B_ext_i and compute *num_nonzeros for B_ext *--------------------------------------------------------------------------*/ for (i=0; i < num_recvs; i++) for (j = recv_vec_starts[i]; j < recv_vec_starts[i+1]; j++) B_ext_i[j+1] += B_ext_i[j]; *num_nonzeros = B_ext_i[num_rows_B_ext]; *pB_ext_j = hypre_TAlloc(HYPRE_Int, *num_nonzeros); B_ext_j = *pB_ext_j; if (data) { *pB_ext_data = hypre_TAlloc(HYPRE_Complex, *num_nonzeros); B_ext_data = *pB_ext_data; }; for (i=0; i < num_recvs; i++) { start_index = B_ext_i[recv_vec_starts[i]]; *num_nonzeros = B_ext_i[recv_vec_starts[i+1]]-start_index; jdata_recv_vec_starts[i+1] = B_ext_i[recv_vec_starts[i+1]]; } hypre_ParCSRCommPkgRecvVecStarts(tmp_comm_pkg) = jdata_recv_vec_starts; *comm_handle_idx = hypre_ParCSRCommHandleCreate(11,tmp_comm_pkg,B_int_j,B_ext_j); if (data) { *comm_handle_data = hypre_ParCSRCommHandleCreate(1,tmp_comm_pkg,B_int_data, B_ext_data); } if (row_map_comm_handle) { hypre_ParCSRCommHandleDestroy(row_map_comm_handle); row_map_comm_handle = NULL; } hypre_TFree(jdata_send_map_starts); hypre_TFree(jdata_recv_vec_starts); hypre_TFree(tmp_comm_pkg); hypre_TFree(B_int_i); if ( find_row_map ) hypre_TFree(B_int_row_map); /* end generic part */ } void hypre_ParCSRMatrixExtractBExt_Arrays( HYPRE_Int ** pB_ext_i, HYPRE_Int ** pB_ext_j, HYPRE_Complex ** pB_ext_data, HYPRE_Int ** pB_ext_row_map, HYPRE_Int * num_nonzeros, HYPRE_Int data, HYPRE_Int find_row_map, MPI_Comm comm, hypre_ParCSRCommPkg * comm_pkg, HYPRE_Int num_cols_B, HYPRE_Int num_recvs, HYPRE_Int num_sends, HYPRE_Int first_col_diag, HYPRE_Int * row_starts, HYPRE_Int * recv_vec_starts, HYPRE_Int * send_map_starts, HYPRE_Int * send_map_elmts, HYPRE_Int * diag_i, HYPRE_Int * diag_j, HYPRE_Int * offd_i, HYPRE_Int * offd_j, HYPRE_Int * col_map_offd, HYPRE_Real * diag_data, HYPRE_Real * offd_data ) { hypre_ParCSRCommHandle *comm_handle_idx, *comm_handle_data; hypre_ParCSRMatrixExtractBExt_Arrays_Overlap( pB_ext_i, pB_ext_j, pB_ext_data, pB_ext_row_map, num_nonzeros, data, find_row_map, comm, comm_pkg, num_cols_B, num_recvs, num_sends, first_col_diag, row_starts, recv_vec_starts, send_map_starts, send_map_elmts, diag_i, diag_j, offd_i, offd_j, col_map_offd, diag_data, offd_data, &comm_handle_idx, &comm_handle_data, NULL, NULL, 0, 0); HYPRE_Int *send_idx = (HYPRE_Int *)comm_handle_idx->send_data; hypre_ParCSRCommHandleDestroy(comm_handle_idx); hypre_TFree(send_idx); if (data) { HYPRE_Real *send_data = (HYPRE_Real *)comm_handle_data->send_data; hypre_ParCSRCommHandleDestroy(comm_handle_data); hypre_TFree(send_data); } } /*-------------------------------------------------------------------------- * hypre_ParCSRMatrixExtractBExt : extracts rows from B which are located on * other processors and needed for multiplication with A locally. The rows * are returned as CSRMatrix. *--------------------------------------------------------------------------*/ hypre_CSRMatrix * hypre_ParCSRMatrixExtractBExt_Overlap( hypre_ParCSRMatrix *B, hypre_ParCSRMatrix *A, HYPRE_Int data, hypre_ParCSRCommHandle **comm_handle_idx, hypre_ParCSRCommHandle **comm_handle_data, HYPRE_Int *CF_marker, HYPRE_Int *CF_marker_offd, HYPRE_Int skip_fine, HYPRE_Int skip_same_sign ) { MPI_Comm comm = hypre_ParCSRMatrixComm(B); HYPRE_Int first_col_diag = hypre_ParCSRMatrixFirstColDiag(B); /*HYPRE_Int first_row_index = hypre_ParCSRMatrixFirstRowIndex(B);*/ HYPRE_Int *col_map_offd = hypre_ParCSRMatrixColMapOffd(B); hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A); HYPRE_Int num_recvs; HYPRE_Int *recv_vec_starts; HYPRE_Int num_sends; HYPRE_Int *send_map_starts; HYPRE_Int *send_map_elmts; hypre_CSRMatrix *diag = hypre_ParCSRMatrixDiag(B); HYPRE_Int *diag_i = hypre_CSRMatrixI(diag); HYPRE_Int *diag_j = hypre_CSRMatrixJ(diag); HYPRE_Real *diag_data = hypre_CSRMatrixData(diag); hypre_CSRMatrix *offd = hypre_ParCSRMatrixOffd(B); HYPRE_Int *offd_i = hypre_CSRMatrixI(offd); HYPRE_Int *offd_j = hypre_CSRMatrixJ(offd); HYPRE_Real *offd_data = hypre_CSRMatrixData(offd); HYPRE_Int num_cols_B, num_nonzeros; HYPRE_Int num_rows_B_ext; hypre_CSRMatrix *B_ext; HYPRE_Int *B_ext_i; HYPRE_Int *B_ext_j; HYPRE_Complex *B_ext_data; HYPRE_Int *idummy; /*--------------------------------------------------------------------- * If there exists no CommPkg for A, a CommPkg is generated using * equally load balanced partitionings *--------------------------------------------------------------------*/ if (!hypre_ParCSRMatrixCommPkg(A)) { hypre_MatvecCommPkgCreate(A); } comm_pkg = hypre_ParCSRMatrixCommPkg(A); num_recvs = hypre_ParCSRCommPkgNumRecvs(comm_pkg); recv_vec_starts = hypre_ParCSRCommPkgRecvVecStarts(comm_pkg); num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); send_map_starts = hypre_ParCSRCommPkgSendMapStarts(comm_pkg); send_map_elmts = hypre_ParCSRCommPkgSendMapElmts(comm_pkg); num_cols_B = hypre_ParCSRMatrixGlobalNumCols(B); num_rows_B_ext = recv_vec_starts[num_recvs]; hypre_ParCSRMatrixExtractBExt_Arrays_Overlap ( &B_ext_i, &B_ext_j, &B_ext_data, &idummy, &num_nonzeros, data, 0, comm, comm_pkg, num_cols_B, num_recvs, num_sends, first_col_diag, B->row_starts, recv_vec_starts, send_map_starts, send_map_elmts, diag_i, diag_j, offd_i, offd_j, col_map_offd, diag_data, offd_data, comm_handle_idx, comm_handle_data, CF_marker, CF_marker_offd, skip_fine, skip_same_sign ); B_ext = hypre_CSRMatrixCreate(num_rows_B_ext,num_cols_B,num_nonzeros); hypre_CSRMatrixI(B_ext) = B_ext_i; hypre_CSRMatrixJ(B_ext) = B_ext_j; if (data) hypre_CSRMatrixData(B_ext) = B_ext_data; return B_ext; } hypre_CSRMatrix * hypre_ParCSRMatrixExtractBExt( hypre_ParCSRMatrix *B, hypre_ParCSRMatrix *A, HYPRE_Int data ) { hypre_ParCSRCommHandle *comm_handle_idx, *comm_handle_data; hypre_CSRMatrix *B_ext = hypre_ParCSRMatrixExtractBExt_Overlap(B, A, data, &comm_handle_idx, &comm_handle_data, NULL, NULL, 0, 0); HYPRE_Int *send_idx = (HYPRE_Int *)comm_handle_idx->send_data; hypre_ParCSRCommHandleDestroy(comm_handle_idx); hypre_TFree(send_idx); if (data) { HYPRE_Real *send_data = (HYPRE_Real *)comm_handle_data->send_data; hypre_ParCSRCommHandleDestroy(comm_handle_data); hypre_TFree(send_data); } return B_ext; } /*-------------------------------------------------------------------------- * hypre_ParCSRMatrixTranspose *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParCSRMatrixTranspose( hypre_ParCSRMatrix *A, hypre_ParCSRMatrix **AT_ptr, HYPRE_Int data ) { hypre_ParCSRCommHandle *comm_handle; MPI_Comm comm = hypre_ParCSRMatrixComm(A); hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A); hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); HYPRE_Int num_cols = hypre_ParCSRMatrixNumCols(A); HYPRE_Int first_row_index = hypre_ParCSRMatrixFirstRowIndex(A); HYPRE_Int *row_starts = hypre_ParCSRMatrixRowStarts(A); HYPRE_Int *col_starts = hypre_ParCSRMatrixColStarts(A); HYPRE_Int num_cols_offd = hypre_CSRMatrixNumCols(A_offd); HYPRE_Int ierr = 0; HYPRE_Int num_sends, num_recvs, num_cols_offd_AT; HYPRE_Int i, j, k, index, counter, j_row; HYPRE_Int value; hypre_ParCSRMatrix *AT; hypre_CSRMatrix *AT_diag; hypre_CSRMatrix *AT_offd; hypre_CSRMatrix *AT_tmp; HYPRE_Int first_row_index_AT, first_col_diag_AT; HYPRE_Int local_num_rows_AT, local_num_cols_AT; HYPRE_Int *AT_tmp_i; HYPRE_Int *AT_tmp_j; HYPRE_Complex *AT_tmp_data; HYPRE_Int *AT_buf_i; HYPRE_Int *AT_buf_j; HYPRE_Complex *AT_buf_data; HYPRE_Int *AT_offd_i; HYPRE_Int *AT_offd_j; HYPRE_Complex *AT_offd_data; HYPRE_Int *col_map_offd_AT; HYPRE_Int *row_starts_AT; HYPRE_Int *col_starts_AT; HYPRE_Int num_procs, my_id; HYPRE_Int *recv_procs; HYPRE_Int *send_procs; HYPRE_Int *recv_vec_starts; HYPRE_Int *send_map_starts; HYPRE_Int *send_map_elmts; HYPRE_Int *tmp_recv_vec_starts; HYPRE_Int *tmp_send_map_starts; hypre_ParCSRCommPkg *tmp_comm_pkg; hypre_MPI_Comm_size(comm,&num_procs); hypre_MPI_Comm_rank(comm,&my_id); num_cols_offd_AT = 0; counter = 0; AT_offd_j = NULL; AT_offd_data = NULL; col_map_offd_AT = NULL; /*--------------------------------------------------------------------- * If there exists no CommPkg for A, a CommPkg is generated using * equally load balanced partitionings *--------------------------------------------------------------------*/ if (!comm_pkg) { hypre_MatvecCommPkgCreate(A); comm_pkg = hypre_ParCSRMatrixCommPkg(A); } if (num_procs > 1) { hypre_CSRMatrixTranspose (A_offd, &AT_tmp, data); AT_tmp_i = hypre_CSRMatrixI(AT_tmp); AT_tmp_j = hypre_CSRMatrixJ(AT_tmp); if (data) AT_tmp_data = hypre_CSRMatrixData(AT_tmp); num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); num_recvs = hypre_ParCSRCommPkgNumRecvs(comm_pkg); recv_procs = hypre_ParCSRCommPkgRecvProcs(comm_pkg); send_procs = hypre_ParCSRCommPkgSendProcs(comm_pkg); recv_vec_starts = hypre_ParCSRCommPkgRecvVecStarts(comm_pkg); send_map_starts = hypre_ParCSRCommPkgSendMapStarts(comm_pkg); send_map_elmts = hypre_ParCSRCommPkgSendMapElmts(comm_pkg); AT_buf_i = hypre_CTAlloc(HYPRE_Int,send_map_starts[num_sends]); for (i=0; i < AT_tmp_i[num_cols_offd]; i++) AT_tmp_j[i] += first_row_index; for (i=0; i < num_cols_offd; i++) AT_tmp_i[i] = AT_tmp_i[i+1]-AT_tmp_i[i]; comm_handle = hypre_ParCSRCommHandleCreate(12, comm_pkg, AT_tmp_i, AT_buf_i); } hypre_CSRMatrixTranspose( A_diag, &AT_diag, data); AT_offd_i = hypre_CTAlloc(HYPRE_Int, num_cols+1); if (num_procs > 1) { hypre_ParCSRCommHandleDestroy(comm_handle); comm_handle = NULL; tmp_send_map_starts = hypre_CTAlloc(HYPRE_Int,num_sends+1); tmp_recv_vec_starts = hypre_CTAlloc(HYPRE_Int,num_recvs+1); tmp_send_map_starts[0] = send_map_starts[0]; for (i=0; i < num_sends; i++) { tmp_send_map_starts[i+1] = tmp_send_map_starts[i]; for (j=send_map_starts[i]; j < send_map_starts[i+1]; j++) { tmp_send_map_starts[i+1] += AT_buf_i[j]; AT_offd_i[send_map_elmts[j]+1] += AT_buf_i[j]; } } for (i=0; i < num_cols; i++) AT_offd_i[i+1] += AT_offd_i[i]; tmp_recv_vec_starts[0] = recv_vec_starts[0]; for (i=0; i < num_recvs; i++) { tmp_recv_vec_starts[i+1] = tmp_recv_vec_starts[i]; for (j=recv_vec_starts[i]; j < recv_vec_starts[i+1]; j++) { tmp_recv_vec_starts[i+1] += AT_tmp_i[j]; } } tmp_comm_pkg = hypre_CTAlloc(hypre_ParCSRCommPkg,1); hypre_ParCSRCommPkgComm(tmp_comm_pkg) = comm; hypre_ParCSRCommPkgNumSends(tmp_comm_pkg) = num_sends; hypre_ParCSRCommPkgNumRecvs(tmp_comm_pkg) = num_recvs; hypre_ParCSRCommPkgRecvProcs(tmp_comm_pkg) = recv_procs; hypre_ParCSRCommPkgSendProcs(tmp_comm_pkg) = send_procs; hypre_ParCSRCommPkgRecvVecStarts(tmp_comm_pkg) = tmp_recv_vec_starts; hypre_ParCSRCommPkgSendMapStarts(tmp_comm_pkg) = tmp_send_map_starts; AT_buf_j = hypre_CTAlloc(HYPRE_Int,tmp_send_map_starts[num_sends]); comm_handle = hypre_ParCSRCommHandleCreate(12, tmp_comm_pkg, AT_tmp_j, AT_buf_j); hypre_ParCSRCommHandleDestroy(comm_handle); comm_handle = NULL; if (data) { AT_buf_data = hypre_CTAlloc(HYPRE_Complex,tmp_send_map_starts[num_sends]); comm_handle = hypre_ParCSRCommHandleCreate(2,tmp_comm_pkg,AT_tmp_data, AT_buf_data); hypre_ParCSRCommHandleDestroy(comm_handle); comm_handle = NULL; } hypre_TFree(tmp_recv_vec_starts); hypre_TFree(tmp_send_map_starts); hypre_TFree(tmp_comm_pkg); hypre_CSRMatrixDestroy(AT_tmp); if (AT_offd_i[num_cols]) { AT_offd_j = hypre_CTAlloc(HYPRE_Int, AT_offd_i[num_cols]); if (data) AT_offd_data = hypre_CTAlloc(HYPRE_Complex, AT_offd_i[num_cols]); } else { AT_offd_j = NULL; AT_offd_data = NULL; } counter = 0; for (i=0; i < num_sends; i++) { for (j=send_map_starts[i]; j < send_map_starts[i+1]; j++) { j_row = send_map_elmts[j]; index = AT_offd_i[j_row]; for (k=0; k < AT_buf_i[j]; k++) { if (data) AT_offd_data[index] = AT_buf_data[counter]; AT_offd_j[index++] = AT_buf_j[counter++]; } AT_offd_i[j_row] = index; } } for (i=num_cols; i > 0; i--) AT_offd_i[i] = AT_offd_i[i-1]; AT_offd_i[0] = 0; if (counter) { hypre_qsort0(AT_buf_j,0,counter-1); num_cols_offd_AT = 1; value = AT_buf_j[0]; for (i=1; i < counter; i++) { if (value < AT_buf_j[i]) { AT_buf_j[num_cols_offd_AT++] = AT_buf_j[i]; value = AT_buf_j[i]; } } } if (num_cols_offd_AT) col_map_offd_AT = hypre_CTAlloc(HYPRE_Int, num_cols_offd_AT); else col_map_offd_AT = NULL; for (i=0; i < num_cols_offd_AT; i++) col_map_offd_AT[i] = AT_buf_j[i]; hypre_TFree(AT_buf_i); hypre_TFree(AT_buf_j); if (data) hypre_TFree(AT_buf_data); for (i=0; i < counter; i++) AT_offd_j[i] = hypre_BinarySearch(col_map_offd_AT,AT_offd_j[i], num_cols_offd_AT); } AT_offd = hypre_CSRMatrixCreate(num_cols,num_cols_offd_AT,counter); hypre_CSRMatrixI(AT_offd) = AT_offd_i; hypre_CSRMatrixJ(AT_offd) = AT_offd_j; hypre_CSRMatrixData(AT_offd) = AT_offd_data; #ifdef HYPRE_NO_GLOBAL_PARTITION row_starts_AT = hypre_CTAlloc(HYPRE_Int, 2); for (i=0; i < 2; i++) row_starts_AT[i] = col_starts[i]; if (row_starts != col_starts) { col_starts_AT = hypre_CTAlloc(HYPRE_Int,2); for (i=0; i < 2; i++) col_starts_AT[i] = row_starts[i]; } else { col_starts_AT = row_starts_AT; } first_row_index_AT = row_starts_AT[0]; first_col_diag_AT = col_starts_AT[0]; local_num_rows_AT = row_starts_AT[1]-first_row_index_AT ; local_num_cols_AT = col_starts_AT[1]-first_col_diag_AT; #else row_starts_AT = hypre_CTAlloc(HYPRE_Int,num_procs+1); for (i=0; i < num_procs+1; i++) row_starts_AT[i] = col_starts[i]; if (row_starts != col_starts) { col_starts_AT = hypre_CTAlloc(HYPRE_Int,num_procs+1); for (i=0; i < num_procs+1; i++) col_starts_AT[i] = row_starts[i]; } else { col_starts_AT = row_starts_AT; } first_row_index_AT = row_starts_AT[my_id]; first_col_diag_AT = col_starts_AT[my_id]; local_num_rows_AT = row_starts_AT[my_id+1]-first_row_index_AT ; local_num_cols_AT = col_starts_AT[my_id+1]-first_col_diag_AT; #endif AT = hypre_CTAlloc(hypre_ParCSRMatrix,1); hypre_ParCSRMatrixComm(AT) = comm; hypre_ParCSRMatrixDiag(AT) = AT_diag; hypre_ParCSRMatrixOffd(AT) = AT_offd; hypre_ParCSRMatrixGlobalNumRows(AT) = hypre_ParCSRMatrixGlobalNumCols(A); hypre_ParCSRMatrixGlobalNumCols(AT) = hypre_ParCSRMatrixGlobalNumRows(A); hypre_ParCSRMatrixRowStarts(AT) = row_starts_AT; hypre_ParCSRMatrixColStarts(AT) = col_starts_AT; hypre_ParCSRMatrixColMapOffd(AT) = col_map_offd_AT; hypre_ParCSRMatrixFirstRowIndex(AT) = first_row_index_AT; hypre_ParCSRMatrixFirstColDiag(AT) = first_col_diag_AT; hypre_ParCSRMatrixLastRowIndex(AT) = first_row_index_AT + local_num_rows_AT - 1; hypre_ParCSRMatrixLastColDiag(AT) = first_col_diag_AT + local_num_cols_AT - 1; hypre_ParCSRMatrixOwnsData(AT) = 1; hypre_ParCSRMatrixOwnsRowStarts(AT) = 1; hypre_ParCSRMatrixOwnsColStarts(AT) = 1; if (row_starts_AT == col_starts_AT) hypre_ParCSRMatrixOwnsColStarts(AT) = 0; hypre_ParCSRMatrixCommPkg(AT) = NULL; hypre_ParCSRMatrixCommPkgT(AT) = NULL; hypre_ParCSRMatrixRowindices(AT) = NULL; hypre_ParCSRMatrixRowvalues(AT) = NULL; hypre_ParCSRMatrixGetrowactive(AT) = 0; *AT_ptr = AT; return ierr; } /* ----------------------------------------------------------------------------- * generate a parallel spanning tree (for Maxwell Equation) * G_csr is the node to edge connectivity matrix * ----------------------------------------------------------------------------- */ void hypre_ParCSRMatrixGenSpanningTree( hypre_ParCSRMatrix *G_csr, HYPRE_Int **indices, HYPRE_Int G_type ) { HYPRE_Int nrows_G, ncols_G, *G_diag_i, *G_diag_j, *GT_diag_mat, i, j, k, edge; HYPRE_Int *nodes_marked, *edges_marked, *queue, queue_tail, queue_head, node; HYPRE_Int mypid, nprocs, n_children, *children, nsends, *send_procs, *recv_cnts; HYPRE_Int nrecvs, *recv_procs, n_proc_array, *proc_array, *pgraph_i, *pgraph_j; HYPRE_Int parent, proc, proc2, node2, found, *t_indices, tree_size, *T_diag_i; HYPRE_Int *T_diag_j, *counts, offset; MPI_Comm comm; hypre_ParCSRCommPkg *comm_pkg; hypre_CSRMatrix *G_diag; /* fetch G matrix (G_type = 0 ==> node to edge) */ if (G_type == 0) { nrows_G = hypre_ParCSRMatrixGlobalNumRows(G_csr); ncols_G = hypre_ParCSRMatrixGlobalNumCols(G_csr); G_diag = hypre_ParCSRMatrixDiag(G_csr); G_diag_i = hypre_CSRMatrixI(G_diag); G_diag_j = hypre_CSRMatrixJ(G_diag); } else { nrows_G = hypre_ParCSRMatrixGlobalNumCols(G_csr); ncols_G = hypre_ParCSRMatrixGlobalNumRows(G_csr); G_diag = hypre_ParCSRMatrixDiag(G_csr); T_diag_i = hypre_CSRMatrixI(G_diag); T_diag_j = hypre_CSRMatrixJ(G_diag); counts = (HYPRE_Int *) malloc(nrows_G * sizeof(HYPRE_Int)); for (i = 0; i < nrows_G; i++) counts[i] = 0; for (i = 0; i < T_diag_i[ncols_G]; i++) counts[T_diag_j[i]]++; G_diag_i = (HYPRE_Int *) malloc((nrows_G+1) * sizeof(HYPRE_Int)); G_diag_j = (HYPRE_Int *) malloc(T_diag_i[ncols_G] * sizeof(HYPRE_Int)); G_diag_i[0] = 0; for (i = 1; i <= nrows_G; i++) G_diag_i[i] = G_diag_i[i-1] + counts[i-1]; for (i = 0; i < ncols_G; i++) { for (j = T_diag_i[i]; j < T_diag_i[i+1]; j++) { k = T_diag_j[j]; offset = G_diag_i[k]++; G_diag_j[offset] = i; } } G_diag_i[0] = 0; for (i = 1; i <= nrows_G; i++) G_diag_i[i] = G_diag_i[i-1] + counts[i-1]; free(counts); } /* form G transpose in special form (2 nodes per edge max) */ GT_diag_mat = (HYPRE_Int *) malloc(2 * ncols_G * sizeof(HYPRE_Int)); for (i = 0; i < 2 * ncols_G; i++) GT_diag_mat[i] = -1; for (i = 0; i < nrows_G; i++) { for (j = G_diag_i[i]; j < G_diag_i[i+1]; j++) { edge = G_diag_j[j]; if (GT_diag_mat[edge*2] == -1) GT_diag_mat[edge*2] = i; else GT_diag_mat[edge*2+1] = i; } } /* BFS on the local matrix graph to find tree */ nodes_marked = (HYPRE_Int *) malloc(nrows_G * sizeof(HYPRE_Int)); edges_marked = (HYPRE_Int *) malloc(ncols_G * sizeof(HYPRE_Int)); for (i = 0; i < nrows_G; i++) nodes_marked[i] = 0; for (i = 0; i < ncols_G; i++) edges_marked[i] = 0; queue = (HYPRE_Int *) malloc(nrows_G * sizeof(HYPRE_Int)); queue_head = 0; queue_tail = 1; queue[0] = 0; nodes_marked[0] = 1; while ((queue_tail-queue_head) > 0) { node = queue[queue_tail-1]; queue_tail--; for (i = G_diag_i[node]; i < G_diag_i[node+1]; i++) { edge = G_diag_j[i]; if (edges_marked[edge] == 0) { if (GT_diag_mat[2*edge+1] != -1) { node2 = GT_diag_mat[2*edge]; if (node2 == node) node2 = GT_diag_mat[2*edge+1]; if (nodes_marked[node2] == 0) { nodes_marked[node2] = 1; edges_marked[edge] = 1; queue[queue_tail] = node2; queue_tail++; } } } } } free(nodes_marked); free(queue); free(GT_diag_mat); /* fetch the communication information from */ comm = hypre_ParCSRMatrixComm(G_csr); hypre_MPI_Comm_rank(comm, &mypid); hypre_MPI_Comm_size(comm, &nprocs); comm_pkg = hypre_ParCSRMatrixCommPkg(G_csr); if (nprocs == 1 && comm_pkg == NULL) { hypre_MatvecCommPkgCreate((hypre_ParCSRMatrix *) G_csr); comm_pkg = hypre_ParCSRMatrixCommPkg(G_csr); } /* construct processor graph based on node-edge connection */ /* (local edges connected to neighbor processor nodes) */ n_children = 0; nrecvs = nsends = 0; if (nprocs > 1) { nsends = hypre_ParCSRCommPkgNumSends(comm_pkg); send_procs = hypre_ParCSRCommPkgSendProcs(comm_pkg); nrecvs = hypre_ParCSRCommPkgNumRecvs(comm_pkg); recv_procs = hypre_ParCSRCommPkgRecvProcs(comm_pkg); proc_array = NULL; if ((nsends+nrecvs) > 0) { n_proc_array = 0; proc_array = (HYPRE_Int *) malloc((nsends+nrecvs) * sizeof(HYPRE_Int)); for (i = 0; i < nsends; i++) proc_array[i] = send_procs[i]; for (i = 0; i < nrecvs; i++) proc_array[nsends+i] = recv_procs[i]; hypre_qsort0(proc_array, 0, nsends+nrecvs-1); n_proc_array = 1; for (i = 1; i < nrecvs+nsends; i++) if (proc_array[i] != proc_array[n_proc_array]) proc_array[n_proc_array++] = proc_array[i]; } pgraph_i = (HYPRE_Int *) malloc((nprocs+1) * sizeof(HYPRE_Int)); recv_cnts = (HYPRE_Int *) malloc(nprocs * sizeof(HYPRE_Int)); hypre_MPI_Allgather(&n_proc_array, 1, HYPRE_MPI_INT, recv_cnts, 1, HYPRE_MPI_INT, comm); pgraph_i[0] = 0; for (i = 1; i <= nprocs; i++) pgraph_i[i] = pgraph_i[i-1] + recv_cnts[i-1]; pgraph_j = (HYPRE_Int *) malloc(pgraph_i[nprocs] * sizeof(HYPRE_Int)); hypre_MPI_Allgatherv(proc_array, n_proc_array, HYPRE_MPI_INT, pgraph_j, recv_cnts, pgraph_i, HYPRE_MPI_INT, comm); free(recv_cnts); /* BFS on the processor graph to determine parent and children */ nodes_marked = (HYPRE_Int *) malloc(nprocs * sizeof(HYPRE_Int)); for (i = 0; i < nprocs; i++) nodes_marked[i] = -1; queue = (HYPRE_Int *) malloc(nprocs * sizeof(HYPRE_Int)); queue_head = 0; queue_tail = 1; node = 0; queue[0] = node; while ((queue_tail-queue_head) > 0) { proc = queue[queue_tail-1]; queue_tail--; for (i = pgraph_i[proc]; i < pgraph_i[proc+1]; i++) { proc2 = pgraph_j[i]; if (nodes_marked[proc2] < 0) { nodes_marked[proc2] = proc; queue[queue_tail] = proc2; queue_tail++; } } } parent = nodes_marked[mypid]; n_children = 0; for (i = 0; i < nprocs; i++) if (nodes_marked[i] == mypid) n_children++; if (n_children == 0) {n_children = 0; children = NULL;} else { children = (HYPRE_Int *) malloc(n_children * sizeof(HYPRE_Int)); n_children = 0; for (i = 0; i < nprocs; i++) if (nodes_marked[i] == mypid) children[n_children++] = i; } free(nodes_marked); free(queue); free(pgraph_i); free(pgraph_j); } /* first, connection with my parent : if the edge in my parent * * is incident to one of my nodes, then my parent will mark it */ found = 0; for (i = 0; i < nrecvs; i++) { proc = hypre_ParCSRCommPkgRecvProc(comm_pkg, i); if (proc == parent) { found = 1; break; } } /* but if all the edges connected to my parent are on my side, * * then I will just pick one of them as tree edge */ if (found == 0) { for (i = 0; i < nsends; i++) { proc = hypre_ParCSRCommPkgSendProc(comm_pkg, i); if (proc == parent) { k = hypre_ParCSRCommPkgSendMapStart(comm_pkg,i); edge = hypre_ParCSRCommPkgSendMapElmt(comm_pkg,k); edges_marked[edge] = 1; break; } } } /* next, if my processor has an edge incident on one node in my * * child, put this edge on the tree. But if there is no such * * edge, then I will assume my child will pick up an edge */ for (j = 0; j < n_children; j++) { proc = children[j]; for (i = 0; i < nsends; i++) { proc2 = hypre_ParCSRCommPkgSendProc(comm_pkg, i); if (proc == proc2) { k = hypre_ParCSRCommPkgSendMapStart(comm_pkg,i); edge = hypre_ParCSRCommPkgSendMapElmt(comm_pkg,k); edges_marked[edge] = 1; break; } } } if (n_children > 0) free(children); /* count the size of the tree */ tree_size = 0; for (i = 0; i < ncols_G; i++) if (edges_marked[i] == 1) tree_size++; t_indices = (HYPRE_Int *) malloc((tree_size+1) * sizeof(HYPRE_Int)); t_indices[0] = tree_size; tree_size = 1; for (i = 0; i < ncols_G; i++) if (edges_marked[i] == 1) t_indices[tree_size++] = i; (*indices) = t_indices; free(edges_marked); if (G_type != 0) { free(G_diag_i); free(G_diag_j); } } /* ----------------------------------------------------------------------------- * extract submatrices based on given indices * ----------------------------------------------------------------------------- */ void hypre_ParCSRMatrixExtractSubmatrices( hypre_ParCSRMatrix *A_csr, HYPRE_Int *indices2, hypre_ParCSRMatrix ***submatrices ) { HYPRE_Int nindices, *indices, nrows_A, *A_diag_i, *A_diag_j, mypid, nprocs; HYPRE_Int i, j, k, *proc_offsets1, *proc_offsets2, *itmp_array, *exp_indices; HYPRE_Int nnz11, nnz12, nnz21, nnz22, col, ncols_offd, nnz_offd, nnz_diag; HYPRE_Int global_nrows, global_ncols, *row_starts, *col_starts, nrows, nnz; HYPRE_Int *diag_i, *diag_j, row, *offd_i; HYPRE_Complex *A_diag_a, *diag_a; hypre_ParCSRMatrix *A11_csr, *A12_csr, *A21_csr, *A22_csr; hypre_CSRMatrix *A_diag, *diag, *offd; MPI_Comm comm; /* ----------------------------------------------------- * first make sure the incoming indices are in order * ----------------------------------------------------- */ nindices = indices2[0]; indices = &(indices2[1]); hypre_qsort0(indices, 0, nindices-1); /* ----------------------------------------------------- * fetch matrix information * ----------------------------------------------------- */ nrows_A = hypre_ParCSRMatrixGlobalNumRows(A_csr); A_diag = hypre_ParCSRMatrixDiag(A_csr); A_diag_i = hypre_CSRMatrixI(A_diag); A_diag_j = hypre_CSRMatrixJ(A_diag); A_diag_a = hypre_CSRMatrixData(A_diag); comm = hypre_ParCSRMatrixComm(A_csr); hypre_MPI_Comm_rank(comm, &mypid); hypre_MPI_Comm_size(comm, &nprocs); if (nprocs > 1) { hypre_error_w_msg(HYPRE_ERROR_GENERIC,"ExtractSubmatrices: cannot handle nprocs > 1 yet.\n"); exit(1); } /* ----------------------------------------------------- * compute new matrix dimensions * ----------------------------------------------------- */ proc_offsets1 = (HYPRE_Int *) malloc((nprocs+1) * sizeof(HYPRE_Int)); proc_offsets2 = (HYPRE_Int *) malloc((nprocs+1) * sizeof(HYPRE_Int)); hypre_MPI_Allgather(&nindices, 1, HYPRE_MPI_INT, proc_offsets1, 1, HYPRE_MPI_INT, comm); k = 0; for (i = 0; i < nprocs; i++) { j = proc_offsets1[i]; proc_offsets1[i] = k; k += j; } proc_offsets1[nprocs] = k; itmp_array = hypre_ParCSRMatrixRowStarts(A_csr); for (i = 0; i <= nprocs; i++) proc_offsets2[i] = itmp_array[i] - proc_offsets1[i]; /* ----------------------------------------------------- * assign id's to row and col for later processing * ----------------------------------------------------- */ exp_indices = (HYPRE_Int *) malloc(nrows_A * sizeof(HYPRE_Int)); for (i = 0; i < nrows_A; i++) exp_indices[i] = -1; for (i = 0; i < nindices; i++) { if (exp_indices[indices[i]] == -1) exp_indices[indices[i]] = i; else { hypre_error_w_msg(HYPRE_ERROR_GENERIC,"ExtractSubmatrices: wrong index %d %d\n"); exit(1); } } k = 0; for (i = 0; i < nrows_A; i++) { if (exp_indices[i] < 0) { exp_indices[i] = - k - 1; k++; } } /* ----------------------------------------------------- * compute number of nonzeros for each block * ----------------------------------------------------- */ nnz11 = nnz12 = nnz21 = nnz22 = 0; for (i = 0; i < nrows_A; i++) { if (exp_indices[i] >= 0) { for (j = A_diag_i[i]; j < A_diag_i[i+1]; j++) { col = A_diag_j[j]; if (exp_indices[col] >= 0) nnz11++; else nnz12++; } } else { for (j = A_diag_i[i]; j < A_diag_i[i+1]; j++) { col = A_diag_j[j]; if (exp_indices[col] >= 0) nnz21++; else nnz22++; } } } /* ----------------------------------------------------- * create A11 matrix (assume sequential for the moment) * ----------------------------------------------------- */ ncols_offd = 0; nnz_offd = 0; nnz_diag = nnz11; #ifdef HYPRE_NO_GLOBAL_PARTITION /* This case is not yet implemented! */ global_nrows = 0; global_ncols = 0; row_starts = NULL; col_starts = NULL; #else global_nrows = proc_offsets1[nprocs]; global_ncols = proc_offsets1[nprocs]; row_starts = hypre_CTAlloc(HYPRE_Int, nprocs+1); col_starts = hypre_CTAlloc(HYPRE_Int, nprocs+1); for (i = 0; i <= nprocs; i++) { row_starts[i] = proc_offsets1[i]; col_starts[i] = proc_offsets1[i]; } #endif A11_csr = hypre_ParCSRMatrixCreate(comm, global_nrows, global_ncols, row_starts, col_starts, ncols_offd, nnz_diag, nnz_offd); nrows = nindices; diag_i = hypre_CTAlloc(HYPRE_Int, nrows+1); diag_j = hypre_CTAlloc(HYPRE_Int, nnz_diag); diag_a = hypre_CTAlloc(HYPRE_Complex, nnz_diag); nnz = 0; row = 0; diag_i[0] = 0; for (i = 0; i < nrows_A; i++) { if (exp_indices[i] >= 0) { for (j = A_diag_i[i]; j < A_diag_i[i+1]; j++) { col = A_diag_j[j]; if (exp_indices[col] >= 0) { diag_j[nnz] = exp_indices[col]; diag_a[nnz++] = A_diag_a[j]; } } row++; diag_i[row] = nnz; } } diag = hypre_ParCSRMatrixDiag(A11_csr); hypre_CSRMatrixI(diag) = diag_i; hypre_CSRMatrixJ(diag) = diag_j; hypre_CSRMatrixData(diag) = diag_a; offd_i = hypre_CTAlloc(HYPRE_Int, nrows+1); for (i = 0; i <= nrows; i++) offd_i[i] = 0; offd = hypre_ParCSRMatrixOffd(A11_csr); hypre_CSRMatrixI(offd) = offd_i; hypre_CSRMatrixJ(offd) = NULL; hypre_CSRMatrixData(offd) = NULL; /* ----------------------------------------------------- * create A12 matrix (assume sequential for the moment) * ----------------------------------------------------- */ ncols_offd = 0; nnz_offd = 0; nnz_diag = nnz12; global_nrows = proc_offsets1[nprocs]; global_ncols = proc_offsets2[nprocs]; row_starts = hypre_CTAlloc(HYPRE_Int, nprocs+1); col_starts = hypre_CTAlloc(HYPRE_Int, nprocs+1); for (i = 0; i <= nprocs; i++) { row_starts[i] = proc_offsets1[i]; col_starts[i] = proc_offsets2[i]; } A12_csr = hypre_ParCSRMatrixCreate(comm, global_nrows, global_ncols, row_starts, col_starts, ncols_offd, nnz_diag, nnz_offd); nrows = nindices; diag_i = hypre_CTAlloc(HYPRE_Int, nrows+1); diag_j = hypre_CTAlloc(HYPRE_Int, nnz_diag); diag_a = hypre_CTAlloc(HYPRE_Complex, nnz_diag); nnz = 0; row = 0; diag_i[0] = 0; for (i = 0; i < nrows_A; i++) { if (exp_indices[i] >= 0) { for (j = A_diag_i[i]; j < A_diag_i[i+1]; j++) { col = A_diag_j[j]; if (exp_indices[col] < 0) { diag_j[nnz] = - exp_indices[col] - 1; diag_a[nnz++] = A_diag_a[j]; } } row++; diag_i[row] = nnz; } } if (nnz > nnz_diag) hypre_error(HYPRE_ERROR_GENERIC); /*hypre_printf("WARNING WARNING WARNING\n");*/ diag = hypre_ParCSRMatrixDiag(A12_csr); hypre_CSRMatrixI(diag) = diag_i; hypre_CSRMatrixJ(diag) = diag_j; hypre_CSRMatrixData(diag) = diag_a; offd_i = hypre_CTAlloc(HYPRE_Int, nrows+1); for (i = 0; i <= nrows; i++) offd_i[i] = 0; offd = hypre_ParCSRMatrixOffd(A12_csr); hypre_CSRMatrixI(offd) = offd_i; hypre_CSRMatrixJ(offd) = NULL; hypre_CSRMatrixData(offd) = NULL; /* ----------------------------------------------------- * create A21 matrix (assume sequential for the moment) * ----------------------------------------------------- */ ncols_offd = 0; nnz_offd = 0; nnz_diag = nnz21; global_nrows = proc_offsets2[nprocs]; global_ncols = proc_offsets1[nprocs]; row_starts = hypre_CTAlloc(HYPRE_Int, nprocs+1); col_starts = hypre_CTAlloc(HYPRE_Int, nprocs+1); for (i = 0; i <= nprocs; i++) { row_starts[i] = proc_offsets2[i]; col_starts[i] = proc_offsets1[i]; } A21_csr = hypre_ParCSRMatrixCreate(comm, global_nrows, global_ncols, row_starts, col_starts, ncols_offd, nnz_diag, nnz_offd); nrows = nrows_A - nindices; diag_i = hypre_CTAlloc(HYPRE_Int, nrows+1); diag_j = hypre_CTAlloc(HYPRE_Int, nnz_diag); diag_a = hypre_CTAlloc(HYPRE_Complex, nnz_diag); nnz = 0; row = 0; diag_i[0] = 0; for (i = 0; i < nrows_A; i++) { if (exp_indices[i] < 0) { for (j = A_diag_i[i]; j < A_diag_i[i+1]; j++) { col = A_diag_j[j]; if (exp_indices[col] >= 0) { diag_j[nnz] = exp_indices[col]; diag_a[nnz++] = A_diag_a[j]; } } row++; diag_i[row] = nnz; } } diag = hypre_ParCSRMatrixDiag(A21_csr); hypre_CSRMatrixI(diag) = diag_i; hypre_CSRMatrixJ(diag) = diag_j; hypre_CSRMatrixData(diag) = diag_a; offd_i = hypre_CTAlloc(HYPRE_Int, nrows+1); for (i = 0; i <= nrows; i++) offd_i[i] = 0; offd = hypre_ParCSRMatrixOffd(A21_csr); hypre_CSRMatrixI(offd) = offd_i; hypre_CSRMatrixJ(offd) = NULL; hypre_CSRMatrixData(offd) = NULL; /* ----------------------------------------------------- * create A22 matrix (assume sequential for the moment) * ----------------------------------------------------- */ ncols_offd = 0; nnz_offd = 0; nnz_diag = nnz22; global_nrows = proc_offsets2[nprocs]; global_ncols = proc_offsets2[nprocs]; row_starts = hypre_CTAlloc(HYPRE_Int, nprocs+1); col_starts = hypre_CTAlloc(HYPRE_Int, nprocs+1); for (i = 0; i <= nprocs; i++) { row_starts[i] = proc_offsets2[i]; col_starts[i] = proc_offsets2[i]; } A22_csr = hypre_ParCSRMatrixCreate(comm, global_nrows, global_ncols, row_starts, col_starts, ncols_offd, nnz_diag, nnz_offd); nrows = nrows_A - nindices; diag_i = hypre_CTAlloc(HYPRE_Int, nrows+1); diag_j = hypre_CTAlloc(HYPRE_Int, nnz_diag); diag_a = hypre_CTAlloc(HYPRE_Complex, nnz_diag); nnz = 0; row = 0; diag_i[0] = 0; for (i = 0; i < nrows_A; i++) { if (exp_indices[i] < 0) { for (j = A_diag_i[i]; j < A_diag_i[i+1]; j++) { col = A_diag_j[j]; if (exp_indices[col] < 0) { diag_j[nnz] = - exp_indices[col] - 1; diag_a[nnz++] = A_diag_a[j]; } } row++; diag_i[row] = nnz; } } diag = hypre_ParCSRMatrixDiag(A22_csr); hypre_CSRMatrixI(diag) = diag_i; hypre_CSRMatrixJ(diag) = diag_j; hypre_CSRMatrixData(diag) = diag_a; offd_i = hypre_CTAlloc(HYPRE_Int, nrows+1); for (i = 0; i <= nrows; i++) offd_i[i] = 0; offd = hypre_ParCSRMatrixOffd(A22_csr); hypre_CSRMatrixI(offd) = offd_i; hypre_CSRMatrixJ(offd) = NULL; hypre_CSRMatrixData(offd) = NULL; /* ----------------------------------------------------- * hand the matrices back to the caller and clean up * ----------------------------------------------------- */ (*submatrices)[0] = A11_csr; (*submatrices)[1] = A12_csr; (*submatrices)[2] = A21_csr; (*submatrices)[3] = A22_csr; free(proc_offsets1); free(proc_offsets2); free(exp_indices); } /* ----------------------------------------------------------------------------- * extract submatrices of a rectangular matrix * ----------------------------------------------------------------------------- */ void hypre_ParCSRMatrixExtractRowSubmatrices( hypre_ParCSRMatrix *A_csr, HYPRE_Int *indices2, hypre_ParCSRMatrix ***submatrices ) { HYPRE_Int nindices, *indices, nrows_A, *A_diag_i, *A_diag_j, mypid, nprocs; HYPRE_Int i, j, k, *proc_offsets1, *proc_offsets2, *itmp_array, *exp_indices; HYPRE_Int nnz11, nnz21, col, ncols_offd, nnz_offd, nnz_diag; HYPRE_Int *A_offd_i, *A_offd_j; HYPRE_Int global_nrows, global_ncols, *row_starts, *col_starts, nrows, nnz; HYPRE_Int *diag_i, *diag_j, row, *offd_i, *offd_j, nnz11_offd, nnz21_offd; HYPRE_Complex *A_diag_a, *diag_a, *offd_a; hypre_ParCSRMatrix *A11_csr, *A21_csr; hypre_CSRMatrix *A_diag, *diag, *A_offd, *offd; MPI_Comm comm; /* ----------------------------------------------------- * first make sure the incoming indices are in order * ----------------------------------------------------- */ nindices = indices2[0]; indices = &(indices2[1]); hypre_qsort0(indices, 0, nindices-1); /* ----------------------------------------------------- * fetch matrix information * ----------------------------------------------------- */ nrows_A = hypre_ParCSRMatrixGlobalNumRows(A_csr); A_diag = hypre_ParCSRMatrixDiag(A_csr); A_diag_i = hypre_CSRMatrixI(A_diag); A_diag_j = hypre_CSRMatrixJ(A_diag); A_diag_a = hypre_CSRMatrixData(A_diag); A_offd = hypre_ParCSRMatrixOffd(A_csr); A_offd_i = hypre_CSRMatrixI(A_offd); A_offd_j = hypre_CSRMatrixJ(A_offd); comm = hypre_ParCSRMatrixComm(A_csr); hypre_MPI_Comm_rank(comm, &mypid); hypre_MPI_Comm_size(comm, &nprocs); /* ----------------------------------------------------- * compute new matrix dimensions * ----------------------------------------------------- */ proc_offsets1 = (HYPRE_Int *) malloc((nprocs+1) * sizeof(HYPRE_Int)); proc_offsets2 = (HYPRE_Int *) malloc((nprocs+1) * sizeof(HYPRE_Int)); hypre_MPI_Allgather(&nindices, 1, HYPRE_MPI_INT, proc_offsets1, 1, HYPRE_MPI_INT, comm); k = 0; for (i = 0; i < nprocs; i++) { j = proc_offsets1[i]; proc_offsets1[i] = k; k += j; } proc_offsets1[nprocs] = k; itmp_array = hypre_ParCSRMatrixRowStarts(A_csr); for (i = 0; i <= nprocs; i++) proc_offsets2[i] = itmp_array[i] - proc_offsets1[i]; /* ----------------------------------------------------- * assign id's to row and col for later processing * ----------------------------------------------------- */ exp_indices = (HYPRE_Int *) malloc(nrows_A * sizeof(HYPRE_Int)); for (i = 0; i < nrows_A; i++) exp_indices[i] = -1; for (i = 0; i < nindices; i++) { if (exp_indices[indices[i]] == -1) exp_indices[indices[i]] = i; else { hypre_error_w_msg(HYPRE_ERROR_GENERIC,"ExtractRowSubmatrices: wrong index %d %d\n"); exit(1); } } k = 0; for (i = 0; i < nrows_A; i++) { if (exp_indices[i] < 0) { exp_indices[i] = - k - 1; k++; } } /* ----------------------------------------------------- * compute number of nonzeros for each block * ----------------------------------------------------- */ nnz11 = nnz21 = nnz11_offd = nnz21_offd = 0; for (i = 0; i < nrows_A; i++) { if (exp_indices[i] >= 0) { for (j = A_diag_i[i]; j < A_diag_i[i+1]; j++) { col = A_diag_j[j]; if (exp_indices[col] >= 0) nnz11++; } nnz11_offd += A_offd_i[i+1] - A_offd_i[i]; } else { for (j = A_diag_i[i]; j < A_diag_i[i+1]; j++) { col = A_diag_j[j]; if (exp_indices[col] < 0) nnz21++; } nnz21_offd += A_offd_i[i+1] - A_offd_i[i]; } } /* ----------------------------------------------------- * create A11 matrix (assume sequential for the moment) * ----------------------------------------------------- */ ncols_offd = hypre_CSRMatrixNumCols(hypre_ParCSRMatrixDiag(A_csr)); nnz_diag = nnz11; nnz_offd = nnz11_offd; global_nrows = proc_offsets1[nprocs]; itmp_array = hypre_ParCSRMatrixColStarts(A_csr); global_ncols = itmp_array[nprocs]; row_starts = hypre_CTAlloc(HYPRE_Int, nprocs+1); col_starts = hypre_CTAlloc(HYPRE_Int, nprocs+1); for (i = 0; i <= nprocs; i++) { row_starts[i] = proc_offsets1[i]; col_starts[i] = itmp_array[i]; } A11_csr = hypre_ParCSRMatrixCreate(comm, global_nrows, global_ncols, row_starts, col_starts, ncols_offd, nnz_diag, nnz_offd); nrows = nindices; diag_i = hypre_CTAlloc(HYPRE_Int, nrows+1); diag_j = hypre_CTAlloc(HYPRE_Int, nnz_diag); diag_a = hypre_CTAlloc(HYPRE_Complex, nnz_diag); nnz = 0; row = 0; diag_i[0] = 0; for (i = 0; i < nrows_A; i++) { if (exp_indices[i] >= 0) { for (j = A_diag_i[i]; j < A_diag_i[i+1]; j++) { col = A_diag_j[j]; if (exp_indices[col] >= 0) { diag_j[nnz] = exp_indices[col]; diag_a[nnz++] = A_diag_a[j]; } } row++; diag_i[row] = nnz; } } diag = hypre_ParCSRMatrixDiag(A11_csr); hypre_CSRMatrixI(diag) = diag_i; hypre_CSRMatrixJ(diag) = diag_j; hypre_CSRMatrixData(diag) = diag_a; offd_i = hypre_CTAlloc(HYPRE_Int, nrows+1); offd_j = hypre_CTAlloc(HYPRE_Int, nnz_offd); offd_a = hypre_CTAlloc(HYPRE_Complex, nnz_offd); nnz = 0; row = 0; offd_i[0] = 0; for (i = 0; i < nrows_A; i++) { if (exp_indices[i] >= 0) { for (j = A_offd_i[i]; j < A_offd_i[i+1]; j++) { offd_j[nnz] = A_offd_j[j]; offd_a[nnz++] = A_diag_a[j]; } row++; offd_i[row] = nnz; } } offd = hypre_ParCSRMatrixOffd(A11_csr); hypre_CSRMatrixI(offd) = offd_i; hypre_CSRMatrixJ(offd) = offd_j; hypre_CSRMatrixData(offd) = offd_a; /* ----------------------------------------------------- * create A21 matrix * ----------------------------------------------------- */ ncols_offd = hypre_CSRMatrixNumCols(hypre_ParCSRMatrixDiag(A_csr)); nnz_offd = nnz21_offd; nnz_diag = nnz21; global_nrows = proc_offsets2[nprocs]; itmp_array = hypre_ParCSRMatrixColStarts(A_csr); global_ncols = itmp_array[nprocs]; row_starts = hypre_CTAlloc(HYPRE_Int, nprocs+1); col_starts = hypre_CTAlloc(HYPRE_Int, nprocs+1); for (i = 0; i <= nprocs; i++) { row_starts[i] = proc_offsets2[i]; col_starts[i] = itmp_array[i]; } A21_csr = hypre_ParCSRMatrixCreate(comm, global_nrows, global_ncols, row_starts, col_starts, ncols_offd, nnz_diag, nnz_offd); nrows = nrows_A - nindices; diag_i = hypre_CTAlloc(HYPRE_Int, nrows+1); diag_j = hypre_CTAlloc(HYPRE_Int, nnz_diag); diag_a = hypre_CTAlloc(HYPRE_Complex, nnz_diag); nnz = 0; row = 0; diag_i[0] = 0; for (i = 0; i < nrows_A; i++) { if (exp_indices[i] < 0) { for (j = A_diag_i[i]; j < A_diag_i[i+1]; j++) { diag_j[nnz] = A_diag_j[j]; diag_a[nnz++] = A_diag_a[j]; } row++; diag_i[row] = nnz; } } diag = hypre_ParCSRMatrixDiag(A21_csr); hypre_CSRMatrixI(diag) = diag_i; hypre_CSRMatrixJ(diag) = diag_j; hypre_CSRMatrixData(diag) = diag_a; offd_i = hypre_CTAlloc(HYPRE_Int, nrows+1); offd_j = hypre_CTAlloc(HYPRE_Int, nnz_offd); offd_a = hypre_CTAlloc(HYPRE_Complex, nnz_offd); nnz = 0; row = 0; offd_i[0] = 0; for (i = 0; i < nrows_A; i++) { if (exp_indices[i] < 0) { for (j = A_offd_i[i]; j < A_offd_i[i+1]; j++) { offd_j[nnz] = A_offd_j[j]; offd_a[nnz++] = A_diag_a[j]; } row++; offd_i[row] = nnz; } } offd = hypre_ParCSRMatrixOffd(A21_csr); hypre_CSRMatrixI(offd) = offd_i; hypre_CSRMatrixJ(offd) = offd_j; hypre_CSRMatrixData(offd) = offd_a; /* ----------------------------------------------------- * hand the matrices back to the caller and clean up * ----------------------------------------------------- */ (*submatrices)[0] = A11_csr; (*submatrices)[1] = A21_csr; free(proc_offsets1); free(proc_offsets2); free(exp_indices); } /* ----------------------------------------------------------------------------- * return the sum of all local elements of the matrix * ----------------------------------------------------------------------------- */ HYPRE_Complex hypre_ParCSRMatrixLocalSumElts( hypre_ParCSRMatrix * A ) { hypre_CSRMatrix * A_diag = hypre_ParCSRMatrixDiag( A ); hypre_CSRMatrix * A_offd = hypre_ParCSRMatrixOffd( A ); return hypre_CSRMatrixSumElts(A_diag) + hypre_CSRMatrixSumElts(A_offd); } /*-------------------------------------------------------------------------- * hypre_ParCSRMatrixMatAminvDB * computes C = (A - inv(D)B) where D is a diagonal matrix * Note: Data structure of A is expected to be a subset of data structure of B! *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParCSRMatrixAminvDB( hypre_ParCSRMatrix *A, hypre_ParCSRMatrix *B, HYPRE_Complex *d, hypre_ParCSRMatrix **C_ptr) { MPI_Comm comm = hypre_ParCSRMatrixComm(B); hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); hypre_ParCSRMatrix *C = NULL; HYPRE_Int num_cols_offd_A = hypre_CSRMatrixNumCols(A_offd); hypre_ParCSRCommPkg *comm_pkg_B = hypre_ParCSRMatrixCommPkg(B); hypre_CSRMatrix *B_diag = hypre_ParCSRMatrixDiag(B); hypre_CSRMatrix *B_offd = hypre_ParCSRMatrixOffd(B); HYPRE_Int num_cols_offd_B = hypre_CSRMatrixNumCols(B_offd); HYPRE_Int num_sends_B, num_recvs_B; HYPRE_Int i, j, cnt; HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag); HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag); HYPRE_Complex *A_diag_data = hypre_CSRMatrixData(A_diag); HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd); HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd); HYPRE_Complex *A_offd_data = hypre_CSRMatrixData(A_offd); HYPRE_Int *col_map_offd_A = hypre_ParCSRMatrixColMapOffd(A); HYPRE_Int num_rows = hypre_CSRMatrixNumRows(B_diag); HYPRE_Int *B_diag_i = hypre_CSRMatrixI(B_diag); HYPRE_Int *B_diag_j = hypre_CSRMatrixJ(B_diag); HYPRE_Complex *B_diag_data = hypre_CSRMatrixData(B_diag); HYPRE_Int *B_offd_i = hypre_CSRMatrixI(B_offd); HYPRE_Int *B_offd_j = hypre_CSRMatrixJ(B_offd); HYPRE_Complex *B_offd_data = hypre_CSRMatrixData(B_offd); HYPRE_Int *col_map_offd_B = hypre_ParCSRMatrixColMapOffd(B); hypre_CSRMatrix *C_diag = NULL; hypre_CSRMatrix *C_offd = NULL; HYPRE_Int *C_diag_i = NULL; HYPRE_Int *C_diag_j = NULL; HYPRE_Complex *C_diag_data = NULL; HYPRE_Int *C_offd_i = NULL; HYPRE_Int *C_offd_j = NULL; HYPRE_Complex *C_offd_data = NULL; HYPRE_Int num_procs, my_id; HYPRE_Int *recv_procs_B; HYPRE_Int *send_procs_B; HYPRE_Int *recv_vec_starts_B; HYPRE_Int *send_map_starts_B; HYPRE_Int *send_map_elmts_B; hypre_ParCSRCommPkg *comm_pkg_C; HYPRE_Int *recv_procs_C; HYPRE_Int *send_procs_C; HYPRE_Int *recv_vec_starts_C; HYPRE_Int *send_map_starts_C; HYPRE_Int *send_map_elmts_C; HYPRE_Int *map_to_B; /*HYPRE_Int *C_diag_array; HYPRE_Int *C_offd_array;*/ HYPRE_Complex *D_tmp; HYPRE_Int size, rest, num_threads, ii; hypre_MPI_Comm_size(comm,&num_procs); hypre_MPI_Comm_rank(comm,&my_id); num_threads = hypre_NumThreads(); /*C_diag_array = hypre_CTAlloc(HYPRE_Int, num_threads); C_offd_array = hypre_CTAlloc(HYPRE_Int, num_threads);*/ /*--------------------------------------------------------------------- * If there exists no CommPkg for B, a CommPkg is generated *--------------------------------------------------------------------*/ if (!comm_pkg_B) { hypre_MatvecCommPkgCreate(B); comm_pkg_B = hypre_ParCSRMatrixCommPkg(B); } C = hypre_ParCSRMatrixCompleteClone(B); /*hypre_ParCSRMatrixInitialize(C);*/ C_diag = hypre_ParCSRMatrixDiag(C); C_diag_i = hypre_CSRMatrixI(C_diag); C_diag_j = hypre_CSRMatrixJ(C_diag); C_diag_data = hypre_CSRMatrixData(C_diag); C_offd = hypre_ParCSRMatrixOffd(C); C_offd_i = hypre_CSRMatrixI(C_offd); C_offd_j = hypre_CSRMatrixJ(C_offd); C_offd_data = hypre_CSRMatrixData(C_offd); size = num_rows/num_threads; rest = num_rows - size*num_threads; D_tmp = hypre_CTAlloc(HYPRE_Complex, num_rows); if (num_cols_offd_A) { map_to_B = hypre_CTAlloc(HYPRE_Int, num_cols_offd_A); cnt = 0; for (i=0; i < num_cols_offd_A; i++) { while (col_map_offd_B[cnt] < col_map_offd_A[i]) { cnt++; } map_to_B[i] = cnt; cnt++; } } #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(ii, i, j) #endif for (ii=0; ii < num_threads; ii++) { HYPRE_Int *A_marker = NULL; HYPRE_Int ns, ne, A_col, num_cols, nmax; if (ii < rest) { ns = ii*size+ii; ne = (ii+1)*size+ii+1; } else { ns = ii*size+rest; ne = (ii+1)*size+rest; } nmax = hypre_max(num_rows, num_cols_offd_B); A_marker = hypre_CTAlloc(HYPRE_Int, nmax); for (i=0; i < num_rows; i++) A_marker[i] = -1; for (i=ns; i < ne; i++) D_tmp[i] = 1.0/d[i]; num_cols = C_diag_i[ns]; for (i=ns; i < ne; i++) { for (j = A_diag_i[i]; j < A_diag_i[i+1]; j++) { A_col = A_diag_j[j]; if (A_marker[A_col] < C_diag_i[i]) { A_marker[A_col] = num_cols; C_diag_j[num_cols] = A_col; C_diag_data[num_cols] = A_diag_data[j]; num_cols++; } else { C_diag_data[A_marker[A_col]] += A_diag_data[j]; } } for (j = B_diag_i[i]; j < B_diag_i[i+1]; j++) { A_col = B_diag_j[j]; if (A_marker[A_col] < C_diag_i[i]) { A_marker[A_col] = num_cols; C_diag_j[num_cols] = A_col; C_diag_data[num_cols] = -D_tmp[i]*B_diag_data[j]; num_cols++; } else { C_diag_data[A_marker[A_col]] -= D_tmp[i]*B_diag_data[j]; } } } for (i=0; i < num_cols_offd_B; i++) A_marker[i] = -1; num_cols = C_offd_i[ns]; for (i=ns; i < ne; i++) { for (j = A_offd_i[i]; j < A_offd_i[i+1]; j++) { A_col = map_to_B[A_offd_j[j]]; if (A_marker[A_col] < B_offd_i[i]) { A_marker[A_col] = num_cols; C_offd_j[num_cols] = A_col; C_offd_data[num_cols] = A_offd_data[j]; num_cols++; } else { C_offd_data[A_marker[A_col]] += A_offd_data[j]; } } for (j = B_offd_i[i]; j < B_offd_i[i+1]; j++) { A_col = B_offd_j[j]; if (A_marker[A_col] < B_offd_i[i]) { A_marker[A_col] = num_cols; C_offd_j[num_cols] = A_col; C_offd_data[num_cols] = -D_tmp[i]*B_offd_data[j]; num_cols++; } else { C_offd_data[A_marker[A_col]] -= D_tmp[i]*B_offd_data[j]; } } } hypre_TFree(A_marker); } /* end parallel region */ /*for (i=0; i < num_cols_offd_B; i++) col_map_offd_C[i] = col_map_offd_B[i]; */ num_sends_B = hypre_ParCSRCommPkgNumSends(comm_pkg_B); num_recvs_B = hypre_ParCSRCommPkgNumRecvs(comm_pkg_B); recv_procs_B = hypre_ParCSRCommPkgRecvProcs(comm_pkg_B); recv_vec_starts_B = hypre_ParCSRCommPkgRecvVecStarts(comm_pkg_B); send_procs_B = hypre_ParCSRCommPkgSendProcs(comm_pkg_B); send_map_starts_B = hypre_ParCSRCommPkgSendMapStarts(comm_pkg_B); send_map_elmts_B = hypre_ParCSRCommPkgSendMapElmts(comm_pkg_B); recv_procs_C = hypre_CTAlloc(HYPRE_Int, num_recvs_B); recv_vec_starts_C = hypre_CTAlloc(HYPRE_Int, num_recvs_B+1); send_procs_C = hypre_CTAlloc(HYPRE_Int, num_sends_B); send_map_starts_C = hypre_CTAlloc(HYPRE_Int, num_sends_B+1); send_map_elmts_C = hypre_CTAlloc(HYPRE_Int, send_map_starts_B[num_sends_B]); for (i=0; i < num_recvs_B; i++) recv_procs_C[i] = recv_procs_B[i]; for (i=0; i < num_recvs_B+1; i++) recv_vec_starts_C[i] = recv_vec_starts_B[i]; for (i=0; i < num_sends_B; i++) send_procs_C[i] = send_procs_B[i]; for (i=0; i < num_sends_B+1; i++) send_map_starts_C[i] = send_map_starts_B[i]; for (i=0; i < send_map_starts_B[num_sends_B]; i++) send_map_elmts_C[i] = send_map_elmts_B[i]; comm_pkg_C = hypre_CTAlloc(hypre_ParCSRCommPkg,1); hypre_ParCSRCommPkgComm(comm_pkg_C) = comm; hypre_ParCSRCommPkgNumRecvs(comm_pkg_C) = num_recvs_B; hypre_ParCSRCommPkgRecvProcs(comm_pkg_C) = recv_procs_C; hypre_ParCSRCommPkgRecvVecStarts(comm_pkg_C) = recv_vec_starts_C; hypre_ParCSRCommPkgNumSends(comm_pkg_C) = num_sends_B; hypre_ParCSRCommPkgSendProcs(comm_pkg_C) = send_procs_C; hypre_ParCSRCommPkgSendMapStarts(comm_pkg_C) = send_map_starts_C; hypre_ParCSRCommPkgSendMapElmts(comm_pkg_C) = send_map_elmts_C; hypre_ParCSRMatrixCommPkg(C) = comm_pkg_C; hypre_TFree(D_tmp); if (num_cols_offd_A) hypre_TFree(map_to_B); *C_ptr = C; return (hypre_error_flag); } /*-------------------------------------------------------------------------- * hypre_ParTMatmul : multiplies two ParCSRMatrices transpose(A) and B and returns * the product in ParCSRMatrix C * Note that C does not own the partitionings since its row_starts * is owned by A and col_starts by B. *--------------------------------------------------------------------------*/ hypre_ParCSRMatrix *hypre_ParTMatmul( hypre_ParCSRMatrix *A, hypre_ParCSRMatrix *B) { MPI_Comm comm = hypre_ParCSRMatrixComm(A); hypre_ParCSRCommPkg *comm_pkg_A = hypre_ParCSRMatrixCommPkg(A); hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); hypre_CSRMatrix *AT_diag = NULL; hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); hypre_CSRMatrix *AT_offd = NULL; HYPRE_Int num_rows_diag_A = hypre_CSRMatrixNumRows(A_diag); HYPRE_Int num_cols_diag_A = hypre_CSRMatrixNumCols(A_diag); hypre_CSRMatrix *B_diag = hypre_ParCSRMatrixDiag(B); hypre_CSRMatrix *B_offd = hypre_ParCSRMatrixOffd(B); HYPRE_Int *col_map_offd_B = hypre_ParCSRMatrixColMapOffd(B); HYPRE_Int first_col_diag_B = hypre_ParCSRMatrixFirstColDiag(B); HYPRE_Int *col_starts_A = hypre_ParCSRMatrixColStarts(A); HYPRE_Int *col_starts_B = hypre_ParCSRMatrixColStarts(B); HYPRE_Int num_rows_diag_B = hypre_CSRMatrixNumRows(B_diag); HYPRE_Int num_cols_diag_B = hypre_CSRMatrixNumCols(B_diag); HYPRE_Int num_cols_offd_B = hypre_CSRMatrixNumCols(B_offd); hypre_ParCSRMatrix *C; HYPRE_Int *col_map_offd_C = NULL; HYPRE_Int *map_B_to_C; hypre_CSRMatrix *C_diag = NULL; hypre_CSRMatrix *C_tmp_diag = NULL; HYPRE_Complex *C_diag_data = NULL; HYPRE_Int *C_diag_i = NULL; HYPRE_Int *C_diag_j = NULL; HYPRE_Int first_col_diag_C; HYPRE_Int last_col_diag_C; hypre_CSRMatrix *C_offd = NULL; hypre_CSRMatrix *C_tmp_offd = NULL; hypre_CSRMatrix *C_int = NULL; hypre_CSRMatrix *C_ext = NULL; HYPRE_Int *C_ext_i; HYPRE_Int *C_ext_j; HYPRE_Complex *C_ext_data; HYPRE_Int *C_ext_diag_i; HYPRE_Int *C_ext_diag_j; HYPRE_Complex *C_ext_diag_data; HYPRE_Int *C_ext_offd_i; HYPRE_Int *C_ext_offd_j; HYPRE_Complex *C_ext_offd_data; HYPRE_Int C_ext_size = 0; HYPRE_Int C_ext_diag_size = 0; HYPRE_Int C_ext_offd_size = 0; HYPRE_Int *C_tmp_diag_i; HYPRE_Int *C_tmp_diag_j; HYPRE_Complex *C_tmp_diag_data; HYPRE_Int *C_tmp_offd_i; HYPRE_Int *C_tmp_offd_j; HYPRE_Complex *C_tmp_offd_data; HYPRE_Complex *C_offd_data=NULL; HYPRE_Int *C_offd_i=NULL; HYPRE_Int *C_offd_j=NULL; HYPRE_Int *temp; HYPRE_Int *send_map_starts_A; HYPRE_Int *send_map_elmts_A; HYPRE_Int num_sends_A; HYPRE_Int num_cols_offd_C = 0; HYPRE_Int *P_marker; HYPRE_Int i, j; HYPRE_Int i1, j_indx; HYPRE_Int n_rows_A, n_cols_A; HYPRE_Int n_rows_B, n_cols_B; /*HYPRE_Int allsquare = 0;*/ HYPRE_Int cnt, cnt_offd, cnt_diag; HYPRE_Int value; HYPRE_Int num_procs, my_id; HYPRE_Int max_num_threads; HYPRE_Int *C_diag_array = NULL; HYPRE_Int *C_offd_array = NULL; HYPRE_Int first_row_index, first_col_diag; HYPRE_Int local_num_rows, local_num_cols; n_rows_A = hypre_ParCSRMatrixGlobalNumRows(A); n_cols_A = hypre_ParCSRMatrixGlobalNumCols(A); n_rows_B = hypre_ParCSRMatrixGlobalNumRows(B); n_cols_B = hypre_ParCSRMatrixGlobalNumCols(B); hypre_MPI_Comm_size(comm,&num_procs); hypre_MPI_Comm_rank(comm, &my_id); max_num_threads = hypre_NumThreads(); if (n_rows_A != n_rows_B || num_rows_diag_A != num_rows_diag_B) { hypre_error_w_msg(HYPRE_ERROR_GENERIC," Error! Incompatible matrix dimensions!\n"); return NULL; } /*if (num_cols_diag_A == num_cols_diag_B) allsquare = 1;*/ hypre_CSRMatrixTranspose(A_diag, &AT_diag, 1); hypre_CSRMatrixTranspose(A_offd, &AT_offd, 1); C_tmp_diag = hypre_CSRMatrixMultiply(AT_diag, B_diag); C_ext_size = 0; if (num_procs > 1) { hypre_CSRMatrix *C_int_diag; hypre_CSRMatrix *C_int_offd; C_tmp_offd = hypre_CSRMatrixMultiply(AT_diag, B_offd); C_int_diag = hypre_CSRMatrixMultiply(AT_offd, B_diag); C_int_offd = hypre_CSRMatrixMultiply(AT_offd, B_offd); hypre_ParCSRMatrixDiag(B) = C_int_diag; hypre_ParCSRMatrixOffd(B) = C_int_offd; C_int = hypre_MergeDiagAndOffd(B); hypre_ParCSRMatrixDiag(B) = B_diag; hypre_ParCSRMatrixOffd(B) = B_offd; C_ext = hypre_ExchangeRAPData(C_int, comm_pkg_A); C_ext_i = hypre_CSRMatrixI(C_ext); C_ext_j = hypre_CSRMatrixJ(C_ext); C_ext_data = hypre_CSRMatrixData(C_ext); C_ext_size = C_ext_i[hypre_CSRMatrixNumRows(C_ext)]; hypre_CSRMatrixDestroy(C_int); hypre_CSRMatrixDestroy(C_int_diag); hypre_CSRMatrixDestroy(C_int_offd); } else { C_tmp_offd = hypre_CSRMatrixCreate(num_cols_diag_A, 0, 0); hypre_CSRMatrixInitialize(C_tmp_offd); } hypre_CSRMatrixDestroy(AT_diag); hypre_CSRMatrixDestroy(AT_offd); /*----------------------------------------------------------------------- * Add contents of C_ext to C_tmp_diag and C_tmp_offd * to obtain C_diag and C_offd *-----------------------------------------------------------------------*/ /* check for new nonzero columns in C_offd generated through C_ext */ first_col_diag_C = first_col_diag_B; last_col_diag_C = first_col_diag_B + num_cols_diag_B - 1; C_tmp_diag_i = hypre_CSRMatrixI(C_tmp_diag); if (C_ext_size || num_cols_offd_B) { HYPRE_Int C_ext_num_rows; num_sends_A = hypre_ParCSRCommPkgNumSends(comm_pkg_A); send_map_starts_A = hypre_ParCSRCommPkgSendMapStarts(comm_pkg_A); send_map_elmts_A = hypre_ParCSRCommPkgSendMapElmts(comm_pkg_A); C_ext_num_rows = send_map_starts_A[num_sends_A]; C_ext_diag_i = hypre_CTAlloc(HYPRE_Int, C_ext_num_rows+1); C_ext_offd_i = hypre_CTAlloc(HYPRE_Int, C_ext_num_rows+1); temp = hypre_CTAlloc(HYPRE_Int, C_ext_size+num_cols_offd_B); C_ext_diag_size = 0; C_ext_offd_size = 0; for (i=0; i < C_ext_num_rows; i++) { for (j=C_ext_i[i]; j < C_ext_i[i+1]; j++) if (C_ext_j[j] < first_col_diag_C || C_ext_j[j] > last_col_diag_C) temp[C_ext_offd_size++] = C_ext_j[j]; else C_ext_diag_size++; C_ext_diag_i[i+1] = C_ext_diag_size; C_ext_offd_i[i+1] = C_ext_offd_size; } cnt = C_ext_offd_size; for (i=0; i < num_cols_offd_B; i++) temp[cnt++] = col_map_offd_B[i]; if (cnt) { hypre_qsort0(temp,0,cnt-1); value = temp[0]; num_cols_offd_C = 1; for (i=1; i < cnt; i++) { if (temp[i] > value) { value = temp[i]; temp[num_cols_offd_C++] = value; } } } if (num_cols_offd_C) col_map_offd_C = hypre_CTAlloc(HYPRE_Int, num_cols_offd_C); for (i=0; i < num_cols_offd_C; i++) col_map_offd_C[i] = temp[i]; hypre_TFree(temp); if (C_ext_diag_size) { C_ext_diag_j = hypre_CTAlloc(HYPRE_Int, C_ext_diag_size); C_ext_diag_data = hypre_CTAlloc(HYPRE_Complex, C_ext_diag_size); } if (C_ext_offd_size) { C_ext_offd_j = hypre_CTAlloc(HYPRE_Int, C_ext_offd_size); C_ext_offd_data = hypre_CTAlloc(HYPRE_Complex, C_ext_offd_size); } C_tmp_diag_j = hypre_CSRMatrixJ(C_tmp_diag); C_tmp_diag_data = hypre_CSRMatrixData(C_tmp_diag); C_tmp_offd_i = hypre_CSRMatrixI(C_tmp_offd); C_tmp_offd_j = hypre_CSRMatrixJ(C_tmp_offd); C_tmp_offd_data = hypre_CSRMatrixData(C_tmp_offd); cnt_offd = 0; cnt_diag = 0; for (i=0; i < C_ext_num_rows; i++) { for (j=C_ext_i[i]; j < C_ext_i[i+1]; j++) if (C_ext_j[j] < first_col_diag_C || C_ext_j[j] > last_col_diag_C) { C_ext_offd_j[cnt_offd] = hypre_BinarySearch(col_map_offd_C, C_ext_j[j], num_cols_offd_C); C_ext_offd_data[cnt_offd++] = C_ext_data[j]; } else { C_ext_diag_j[cnt_diag] = C_ext_j[j] - first_col_diag_C; C_ext_diag_data[cnt_diag++] = C_ext_data[j]; } } } if (C_ext) { hypre_CSRMatrixDestroy(C_ext); C_ext = NULL; } if (num_cols_offd_B) { map_B_to_C = hypre_CTAlloc(HYPRE_Int,num_cols_offd_B); cnt = 0; for (i=0; i < num_cols_offd_C; i++) if (col_map_offd_C[i] == col_map_offd_B[cnt]) { map_B_to_C[cnt++] = i; if (cnt == num_cols_offd_B) break; } for (i=0; i < hypre_CSRMatrixI(C_tmp_offd)[hypre_CSRMatrixNumRows(C_tmp_offd)]; i++) { j_indx = C_tmp_offd_j[i]; C_tmp_offd_j[i] = map_B_to_C[j_indx]; } } /*----------------------------------------------------------------------- * Need to compute C_diag = C_tmp_diag + C_ext_diag * and C_offd = C_tmp_offd + C_ext_offd !!!! * First generate structure *-----------------------------------------------------------------------*/ if (C_ext_size || num_cols_offd_B) { C_diag_i = hypre_CTAlloc(HYPRE_Int, num_cols_diag_A+1); C_offd_i = hypre_CTAlloc(HYPRE_Int, num_cols_diag_A+1); C_diag_array = hypre_CTAlloc(HYPRE_Int, max_num_threads); C_offd_array = hypre_CTAlloc(HYPRE_Int, max_num_threads); #ifdef HYPRE_USING_OPENMP #pragma omp parallel #endif { HYPRE_Int *B_marker = NULL; HYPRE_Int *B_marker_offd = NULL; HYPRE_Int ik, jk, j1, j2, jcol; HYPRE_Int ns, ne, ii, nnz_d, nnz_o; HYPRE_Int rest, size; HYPRE_Int num_threads = hypre_NumActiveThreads(); size = num_cols_diag_A/num_threads; rest = num_cols_diag_A - size*num_threads; ii = hypre_GetThreadNum(); if (ii < rest) { ns = ii*size+ii; ne = (ii+1)*size+ii+1; } else { ns = ii*size+rest; ne = (ii+1)*size+rest; } B_marker = hypre_CTAlloc(HYPRE_Int, num_cols_diag_B); B_marker_offd = hypre_CTAlloc(HYPRE_Int, num_cols_offd_C); for (ik = 0; ik < num_cols_diag_B; ik++) B_marker[ik] = -1; for (ik = 0; ik < num_cols_offd_C; ik++) B_marker_offd[ik] = -1; nnz_d = 0; nnz_o = 0; for (ik = ns; ik < ne; ik++) { for (jk = C_tmp_diag_i[ik]; jk < C_tmp_diag_i[ik+1]; jk++) { jcol = C_tmp_diag_j[jk]; B_marker[jcol] = ik; nnz_d++; } for (jk = C_tmp_offd_i[ik]; jk < C_tmp_offd_i[ik+1]; jk++) { jcol = C_tmp_offd_j[jk]; B_marker_offd[jcol] = ik; nnz_o++; } for (jk = 0; jk < num_sends_A; jk++) for (j1 = send_map_starts_A[jk]; j1 < send_map_starts_A[jk+1]; j1++) if (send_map_elmts_A[j1] == ik) { for (j2 = C_ext_diag_i[j1]; j2 < C_ext_diag_i[j1+1]; j2++) { jcol = C_ext_diag_j[j2]; if (B_marker[jcol] < ik) { B_marker[jcol] = ik; nnz_d++; } } for (j2 = C_ext_offd_i[j1]; j2 < C_ext_offd_i[j1+1]; j2++) { jcol = C_ext_offd_j[j2]; if (B_marker_offd[jcol] < ik) { B_marker_offd[jcol] = ik; nnz_o++; } } break; } C_diag_array[ii] = nnz_d; C_offd_array[ii] = nnz_o; } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif if (ii == 0) { nnz_d = 0; nnz_o = 0; for (ik = 0; ik < num_threads-1; ik++) { C_diag_array[ik+1] += C_diag_array[ik]; C_offd_array[ik+1] += C_offd_array[ik]; } nnz_d = C_diag_array[num_threads-1]; nnz_o = C_offd_array[num_threads-1]; C_diag_i[num_cols_diag_A] = nnz_d; C_offd_i[num_cols_diag_A] = nnz_o; C_diag = hypre_CSRMatrixCreate(num_cols_diag_A, num_cols_diag_A, nnz_d); C_offd = hypre_CSRMatrixCreate(num_cols_diag_A, num_cols_offd_C, nnz_o); hypre_CSRMatrixI(C_diag) = C_diag_i; hypre_CSRMatrixInitialize(C_diag); C_diag_j = hypre_CSRMatrixJ(C_diag); C_diag_data = hypre_CSRMatrixData(C_diag); hypre_CSRMatrixI(C_offd) = C_offd_i; hypre_CSRMatrixInitialize(C_offd); C_offd_j = hypre_CSRMatrixJ(C_offd); C_offd_data = hypre_CSRMatrixData(C_offd); } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif /*----------------------------------------------------------------------- * Need to compute C_diag = C_tmp_diag + C_ext_diag * and C_offd = C_tmp_offd + C_ext_offd !!!! * Now fill in values *-----------------------------------------------------------------------*/ for (ik = 0; ik < num_cols_diag_B; ik++) B_marker[ik] = -1; for (ik = 0; ik < num_cols_offd_C; ik++) B_marker_offd[ik] = -1; /*----------------------------------------------------------------------- * Populate matrices *-----------------------------------------------------------------------*/ nnz_d = 0; nnz_o = 0; nnz_o = 0; if (ii) { nnz_d = C_diag_array[ii-1]; nnz_o = C_offd_array[ii-1]; } for (ik = ns; ik < ne; ik++) { C_diag_i[ik] = nnz_d; C_offd_i[ik] = nnz_o; for (jk = C_tmp_diag_i[ik]; jk < C_tmp_diag_i[ik+1]; jk++) { jcol = C_tmp_diag_j[jk]; C_diag_j[nnz_d] = jcol; C_diag_data[nnz_d] = C_tmp_diag_data[jk]; B_marker[jcol] = nnz_d; nnz_d++; } for (jk = C_tmp_offd_i[ik]; jk < C_tmp_offd_i[ik+1]; jk++) { jcol = C_tmp_offd_j[jk]; C_offd_j[nnz_o] = jcol; C_offd_data[nnz_o] = C_tmp_offd_data[jk]; B_marker_offd[jcol] = nnz_o; nnz_o++; } for (jk = 0; jk < num_sends_A; jk++) for (j1 = send_map_starts_A[jk]; j1 < send_map_starts_A[jk+1]; j1++) if (send_map_elmts_A[j1] == ik) { for (j2 = C_ext_diag_i[j1]; j2 < C_ext_diag_i[j1+1]; j2++) { jcol = C_ext_diag_j[j2]; if (B_marker[jcol] < C_diag_i[ik]) { C_diag_j[nnz_d] = jcol; C_diag_data[nnz_d] = C_ext_diag_data[j2]; B_marker[jcol] = nnz_d; nnz_d++; } else C_diag_data[B_marker[jcol]] += C_ext_diag_data[j2]; } for (j2 = C_ext_offd_i[j1]; j2 < C_ext_offd_i[j1+1]; j2++) { jcol = C_ext_offd_j[j2]; if (B_marker_offd[jcol] < C_offd_i[ik]) { C_offd_j[nnz_o] = jcol; C_offd_data[nnz_o] = C_ext_offd_data[j2]; B_marker_offd[jcol] = nnz_o; nnz_o++; } else C_offd_data[B_marker_offd[jcol]] += C_ext_offd_data[j2]; } break; } } hypre_TFree(B_marker); hypre_TFree(B_marker_offd); } /*end parallel region */ hypre_TFree(C_diag_array); hypre_TFree(C_offd_array); } /*C = hypre_ParCSRMatrixCreate(comm, n_cols_A, n_cols_B, col_starts_A, col_starts_B, num_cols_offd_C, nnz_diag, nnz_offd); hypre_CSRMatrixDestroy(hypre_ParCSRMatrixDiag(C)); hypre_CSRMatrixDestroy(hypre_ParCSRMatrixOffd(C)); */ #ifdef HYPRE_NO_GLOBAL_PARTITION /* row_starts[0] is start of local rows. row_starts[1] is start of next processor's rows */ first_row_index = col_starts_A[0]; local_num_rows = col_starts_A[1]-first_row_index ; first_col_diag = col_starts_B[0]; local_num_cols = col_starts_B[1]-first_col_diag; #else first_row_index = col_starts_A[my_id]; local_num_rows = col_starts_A[my_id+1]-first_row_index; first_col_diag = col_starts_B[my_id]; local_num_cols = col_starts_B[my_id+1]-first_col_diag; #endif C = hypre_CTAlloc(hypre_ParCSRMatrix, 1); hypre_ParCSRMatrixComm(C) = comm; hypre_ParCSRMatrixGlobalNumRows(C) = n_cols_A; hypre_ParCSRMatrixGlobalNumCols(C) = n_cols_B; hypre_ParCSRMatrixFirstRowIndex(C) = first_row_index; hypre_ParCSRMatrixFirstColDiag(C) = first_col_diag; hypre_ParCSRMatrixLastRowIndex(C) = first_row_index + local_num_rows - 1; hypre_ParCSRMatrixLastColDiag(C) = first_col_diag + local_num_cols - 1; hypre_ParCSRMatrixColMapOffd(C) = NULL; hypre_ParCSRMatrixAssumedPartition(C) = NULL; hypre_ParCSRMatrixRowStarts(C) = col_starts_A; hypre_ParCSRMatrixColStarts(C) = col_starts_B; hypre_ParCSRMatrixCommPkg(C) = NULL; hypre_ParCSRMatrixCommPkgT(C) = NULL; /* set defaults */ hypre_ParCSRMatrixOwnsData(C) = 1; hypre_ParCSRMatrixRowindices(C) = NULL; hypre_ParCSRMatrixRowvalues(C) = NULL; hypre_ParCSRMatrixGetrowactive(C) = 0; /* Note that C does not own the partitionings */ hypre_ParCSRMatrixSetRowStartsOwner(C,0); hypre_ParCSRMatrixSetColStartsOwner(C,0); if (C_diag) hypre_ParCSRMatrixDiag(C) = C_diag; else hypre_ParCSRMatrixDiag(C) = C_tmp_diag; if (C_offd) hypre_ParCSRMatrixOffd(C) = C_offd; else hypre_ParCSRMatrixOffd(C) = C_tmp_offd; if (num_cols_offd_C) { HYPRE_Int jj_count_offd, nnz_offd; HYPRE_Int *new_col_map_offd_C = NULL; P_marker = hypre_CTAlloc(HYPRE_Int,num_cols_offd_C); for (i=0; i < num_cols_offd_C; i++) P_marker[i] = -1; jj_count_offd = 0; nnz_offd = C_offd_i[num_cols_diag_A]; for (i=0; i < nnz_offd; i++) { i1 = C_offd_j[i]; if (P_marker[i1]) { P_marker[i1] = 0; jj_count_offd++; } } if (jj_count_offd < num_cols_offd_C) { new_col_map_offd_C = hypre_CTAlloc(HYPRE_Int,jj_count_offd); jj_count_offd = 0; for (i=0; i < num_cols_offd_C; i++) if (!P_marker[i]) { P_marker[i] = jj_count_offd; new_col_map_offd_C[jj_count_offd++] = col_map_offd_C[i]; } for (i=0; i < nnz_offd; i++) { i1 = C_offd_j[i]; C_offd_j[i] = P_marker[i1]; } num_cols_offd_C = jj_count_offd; hypre_TFree(col_map_offd_C); col_map_offd_C = new_col_map_offd_C; hypre_CSRMatrixNumCols(hypre_ParCSRMatrixOffd(C)) = num_cols_offd_C; } hypre_TFree(P_marker); } hypre_ParCSRMatrixColMapOffd(C) = col_map_offd_C; /*----------------------------------------------------------------------- * Free various arrays *-----------------------------------------------------------------------*/ if (C_ext_size || num_cols_offd_B) { hypre_TFree(C_ext_diag_i); hypre_TFree(C_ext_offd_i); } if (C_ext_diag_size) { hypre_TFree(C_ext_diag_j); hypre_TFree(C_ext_diag_data); } if (C_ext_offd_size) { hypre_TFree(C_ext_offd_j); hypre_TFree(C_ext_offd_data); } if (num_cols_offd_B) hypre_TFree(map_B_to_C); if (C_diag) hypre_CSRMatrixDestroy(C_tmp_diag); if (C_offd) hypre_CSRMatrixDestroy(C_tmp_offd); return C; }
125,091
32.154519
194
c
AMG
AMG-master/parcsr_mv/par_csr_matop_marked.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ #include "_hypre_parcsr_mv.h" #include "assert.h" void hypre_ParCSRMatrixCopy_C( hypre_ParCSRMatrix * P, hypre_ParCSRMatrix * C, HYPRE_Int * CF_marker ); void hypre_ParCSRMatrixZero_F( hypre_ParCSRMatrix * P, HYPRE_Int * CF_marker ); void hypre_ParMatmul_RowSizes_Marked( HYPRE_Int ** C_diag_i, HYPRE_Int ** C_offd_i, HYPRE_Int ** B_marker, HYPRE_Int * A_diag_i, HYPRE_Int * A_diag_j, HYPRE_Int * A_offd_i, HYPRE_Int * A_offd_j, HYPRE_Int * B_diag_i, HYPRE_Int * B_diag_j, HYPRE_Int * B_offd_i, HYPRE_Int * B_offd_j, HYPRE_Int * B_ext_diag_i, HYPRE_Int * B_ext_diag_j, HYPRE_Int * B_ext_offd_i, HYPRE_Int * B_ext_offd_j, HYPRE_Int * map_B_to_C, HYPRE_Int *C_diag_size, HYPRE_Int *C_offd_size, HYPRE_Int num_rows_diag_A, HYPRE_Int num_cols_offd_A, HYPRE_Int allsquare, HYPRE_Int num_cols_diag_B, HYPRE_Int num_cols_offd_B, HYPRE_Int num_cols_offd_C, HYPRE_Int * CF_marker, HYPRE_Int * dof_func, HYPRE_Int * dof_func_offd ) /* Compute row sizes of result of a matrix multiplication A*B. But we only consider rows designated by CF_marker(i)<0 ("Fine" rows). This function is the same as hypre_ParMatmul_RowSizes,but with a little code added to use the marker array. Input arguments like num_rows_diag_A should refer to the full size matrix A, not just the "Fine" part. The principle here is that A and B have coarse+fine data, C only has fine data. But C is the full size of the product A*B. */ { HYPRE_Int i1, i2, i3, jj2, jj3; HYPRE_Int jj_count_diag, jj_count_offd, jj_row_begin_diag, jj_row_begin_offd; HYPRE_Int start_indexing = 0; /* start indexing for C_data at 0 */ /* First pass begins here. Computes sizes of marked C rows. Arrays computed: C_diag_i, C_offd_i, B_marker Arrays needed: (11, all HYPRE_Int*) A_diag_i, A_diag_j, A_offd_i, A_offd_j, B_diag_i, B_diag_j, B_offd_i, B_offd_j, B_ext_i, B_ext_j, col_map_offd_B, col_map_offd_B, B_offd_i, B_offd_j, B_ext_i, B_ext_j, Scalars computed: C_diag_size, C_offd_size Scalars needed: num_rows_diag_A, num_rows_diag_A, num_cols_offd_A, allsquare, first_col_diag_B, n_cols_B, num_cols_offd_B, num_cols_diag_B */ *C_diag_i = hypre_CTAlloc(HYPRE_Int, num_rows_diag_A+1); *C_offd_i = hypre_CTAlloc(HYPRE_Int, num_rows_diag_A+1); /* ... CTAlloc initializes to 0, so entries ignored due to CF_marker will be returned as 0 */ jj_count_diag = start_indexing; jj_count_offd = start_indexing; for (i1 = 0; i1 < num_cols_diag_B+num_cols_offd_C; i1++) { (*B_marker)[i1] = -1; } /*----------------------------------------------------------------------- * Loop over rows of A *-----------------------------------------------------------------------*/ for (i1 = 0; i1 < num_rows_diag_A; i1++) if ( CF_marker[i1] >= 0 ) /* Coarse row */ { /* To make an empty C row i1, its begin point should be the same as for * i1: */ /* (*C_diag_i)[i1] = jj_count_diag; (*C_offd_i)[i1] = jj_count_offd;*/ /* To make the C row i1 the same size as the B row i1: */ jj_row_begin_diag = jj_count_diag; jj_row_begin_offd = jj_count_offd; jj_count_diag += B_diag_i[i1+1] - B_diag_i[i1]; jj_count_offd += B_offd_i[i1+1] - B_offd_i[i1]; (*C_diag_i)[i1] = jj_row_begin_diag; (*C_offd_i)[i1] = jj_row_begin_offd; } else { /* This block, most of of this function, is unchanged from hypre_ParMatmul_Row_Sizes (except for the dof_func checks, which are effectively gone if you set dof_func=NULL); maybe it can be spun off into a separate shared function.*/ /*-------------------------------------------------------------------- * Set marker for diagonal entry, C_{i1,i1} (for square matrices). *--------------------------------------------------------------------*/ jj_row_begin_diag = jj_count_diag; jj_row_begin_offd = jj_count_offd; if ( allsquare ) { (*B_marker)[i1] = jj_count_diag; jj_count_diag++; } /*----------------------------------------------------------------- * Loop over entries in row i1 of A_offd. *-----------------------------------------------------------------*/ if (num_cols_offd_A) { for (jj2 = A_offd_i[i1]; jj2 < A_offd_i[i1+1]; jj2++) { i2 = A_offd_j[jj2]; if ( dof_func==NULL || dof_func[i1] == dof_func_offd[i2] ) {/* interpolate only like "functions" */ /*----------------------------------------------------------- * Loop over entries in row i2 of B_ext. *-----------------------------------------------------------*/ for (jj3 = B_ext_offd_i[i2]; jj3 < B_ext_offd_i[i2+1]; jj3++) { i3 = num_cols_diag_B+B_ext_offd_j[jj3]; /*-------------------------------------------------------- * Check B_marker to see that C_{i1,i3} has not already * been accounted for. If it has not, mark it and increment * counter. *--------------------------------------------------------*/ if ((*B_marker)[i3] < jj_row_begin_offd) { (*B_marker)[i3] = jj_count_offd; jj_count_offd++; } } for (jj3 = B_ext_diag_i[i2]; jj3 < B_ext_diag_i[i2+1]; jj3++) { i3 = B_ext_diag_j[jj3]; if ((*B_marker)[i3] < jj_row_begin_diag) { (*B_marker)[i3] = jj_count_diag; jj_count_diag++; } } } } } /*----------------------------------------------------------------- * Loop over entries in row i1 of A_diag. *-----------------------------------------------------------------*/ for (jj2 = A_diag_i[i1]; jj2 < A_diag_i[i1+1]; jj2++) { i2 = A_diag_j[jj2]; if( dof_func==NULL || dof_func[i1] == dof_func[i2] ) { /* interpolate only like "functions" */ /*----------------------------------------------------------- * Loop over entries in row i2 of B_diag. *-----------------------------------------------------------*/ for (jj3 = B_diag_i[i2]; jj3 < B_diag_i[i2+1]; jj3++) { i3 = B_diag_j[jj3]; /*-------------------------------------------------------- * Check B_marker to see that C_{i1,i3} has not already * been accounted for. If it has not, mark it and increment * counter. *--------------------------------------------------------*/ if ((*B_marker)[i3] < jj_row_begin_diag) { (*B_marker)[i3] = jj_count_diag; jj_count_diag++; } } /*----------------------------------------------------------- * Loop over entries in row i2 of B_offd. *-----------------------------------------------------------*/ if (num_cols_offd_B) { for (jj3 = B_offd_i[i2]; jj3 < B_offd_i[i2+1]; jj3++) { i3 = num_cols_diag_B+map_B_to_C[B_offd_j[jj3]]; /*-------------------------------------------------------- * Check B_marker to see that C_{i1,i3} has not already * been accounted for. If it has not, mark it and increment * counter. *--------------------------------------------------------*/ if ((*B_marker)[i3] < jj_row_begin_offd) { (*B_marker)[i3] = jj_count_offd; jj_count_offd++; } } } } } /*-------------------------------------------------------------------- * Set C_diag_i and C_offd_i for this row. *--------------------------------------------------------------------*/ (*C_diag_i)[i1] = jj_row_begin_diag; (*C_offd_i)[i1] = jj_row_begin_offd; } (*C_diag_i)[num_rows_diag_A] = jj_count_diag; (*C_offd_i)[num_rows_diag_A] = jj_count_offd; /*----------------------------------------------------------------------- * Allocate C_diag_data and C_diag_j arrays. * Allocate C_offd_data and C_offd_j arrays. *-----------------------------------------------------------------------*/ *C_diag_size = jj_count_diag; *C_offd_size = jj_count_offd; /* End of First Pass */ } hypre_ParCSRMatrix * hypre_ParMatmul_FC( hypre_ParCSRMatrix * A, hypre_ParCSRMatrix * P, HYPRE_Int * CF_marker, HYPRE_Int * dof_func, HYPRE_Int * dof_func_offd ) /* hypre_parMatmul_FC creates and returns the "Fine"-designated rows of the matrix product A*P. A's size is (nC+nF)*(nC+nF), P's size is (nC+nF)*nC where nC is the number of coarse rows/columns, nF the number of fine rows/columns. The size of C=A*P is (nC+nF)*nC, even though not all rows of C are actually computed. If we were to construct a matrix consisting only of the computed rows of C, its size would be nF*nC. "Fine" is defined solely by the marker array, and for example could be a proper subset of the fine points of a multigrid hierarchy. */ { /* To compute a submatrix of C containing only the computed data, i.e. only "Fine" rows, we would have to do a lot of computational work, with a lot of communication. The communication is because such a matrix would need global information that depends on which rows are "Fine". */ MPI_Comm comm = hypre_ParCSRMatrixComm(A); hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); HYPRE_Complex *A_diag_data = hypre_CSRMatrixData(A_diag); HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag); HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag); hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); HYPRE_Complex *A_offd_data = hypre_CSRMatrixData(A_offd); HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd); HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd); HYPRE_Int *row_starts_A = hypre_ParCSRMatrixRowStarts(A); HYPRE_Int num_rows_diag_A = hypre_CSRMatrixNumRows(A_diag); HYPRE_Int num_cols_diag_A = hypre_CSRMatrixNumCols(A_diag); HYPRE_Int num_cols_offd_A = hypre_CSRMatrixNumCols(A_offd); hypre_CSRMatrix *P_diag = hypre_ParCSRMatrixDiag(P); HYPRE_Complex *P_diag_data = hypre_CSRMatrixData(P_diag); HYPRE_Int *P_diag_i = hypre_CSRMatrixI(P_diag); HYPRE_Int *P_diag_j = hypre_CSRMatrixJ(P_diag); hypre_CSRMatrix *P_offd = hypre_ParCSRMatrixOffd(P); HYPRE_Int *col_map_offd_P = hypre_ParCSRMatrixColMapOffd(P); HYPRE_Complex *P_offd_data = hypre_CSRMatrixData(P_offd); HYPRE_Int *P_offd_i = hypre_CSRMatrixI(P_offd); HYPRE_Int *P_offd_j = hypre_CSRMatrixJ(P_offd); HYPRE_Int first_col_diag_P = hypre_ParCSRMatrixFirstColDiag(P); HYPRE_Int last_col_diag_P; HYPRE_Int *col_starts_P = hypre_ParCSRMatrixColStarts(P); HYPRE_Int num_rows_diag_P = hypre_CSRMatrixNumRows(P_diag); HYPRE_Int num_cols_diag_P = hypre_CSRMatrixNumCols(P_diag); HYPRE_Int num_cols_offd_P = hypre_CSRMatrixNumCols(P_offd); hypre_ParCSRMatrix *C; HYPRE_Int *col_map_offd_C; HYPRE_Int *map_P_to_C; hypre_CSRMatrix *C_diag; HYPRE_Complex *C_diag_data; HYPRE_Int *C_diag_i; HYPRE_Int *C_diag_j; hypre_CSRMatrix *C_offd; HYPRE_Complex *C_offd_data=NULL; HYPRE_Int *C_offd_i=NULL; HYPRE_Int *C_offd_j=NULL; HYPRE_Int C_diag_size; HYPRE_Int C_offd_size; HYPRE_Int num_cols_offd_C = 0; hypre_CSRMatrix *Ps_ext; HYPRE_Complex *Ps_ext_data; HYPRE_Int *Ps_ext_i; HYPRE_Int *Ps_ext_j; HYPRE_Complex *P_ext_diag_data; HYPRE_Int *P_ext_diag_i; HYPRE_Int *P_ext_diag_j; HYPRE_Int P_ext_diag_size; HYPRE_Complex *P_ext_offd_data; HYPRE_Int *P_ext_offd_i; HYPRE_Int *P_ext_offd_j; HYPRE_Int P_ext_offd_size; HYPRE_Int *P_marker; HYPRE_Int *temp; HYPRE_Int i, j; HYPRE_Int i1, i2, i3; HYPRE_Int jj2, jj3; HYPRE_Int jj_count_diag, jj_count_offd; HYPRE_Int jj_row_begin_diag, jj_row_begin_offd; HYPRE_Int start_indexing = 0; /* start indexing for C_data at 0 */ HYPRE_Int n_rows_A_global, n_cols_A_global; HYPRE_Int n_rows_P_global, n_cols_P_global; HYPRE_Int allsquare = 0; HYPRE_Int cnt, cnt_offd, cnt_diag; HYPRE_Int num_procs; HYPRE_Int value; HYPRE_Complex a_entry; HYPRE_Complex a_b_product; n_rows_A_global = hypre_ParCSRMatrixGlobalNumRows(A); n_cols_A_global = hypre_ParCSRMatrixGlobalNumCols(A); n_rows_P_global = hypre_ParCSRMatrixGlobalNumRows(P); n_cols_P_global = hypre_ParCSRMatrixGlobalNumCols(P); if (n_cols_A_global != n_rows_P_global || num_cols_diag_A != num_rows_diag_P) { hypre_printf(" Error! Incompatible matrix dimensions!\n"); return NULL; } /* if (num_rows_A==num_cols_P) allsquare = 1; */ /*----------------------------------------------------------------------- * Extract P_ext, i.e. portion of P that is stored on neighbor procs * and needed locally for matrix matrix product *-----------------------------------------------------------------------*/ hypre_MPI_Comm_size(comm, &num_procs); if (num_procs > 1) { /*--------------------------------------------------------------------- * If there exists no CommPkg for A, a CommPkg is generated using * equally load balanced partitionings within * hypre_ParCSRMatrixExtractBExt *--------------------------------------------------------------------*/ Ps_ext = hypre_ParCSRMatrixExtractBExt(P,A,1); Ps_ext_data = hypre_CSRMatrixData(Ps_ext); Ps_ext_i = hypre_CSRMatrixI(Ps_ext); Ps_ext_j = hypre_CSRMatrixJ(Ps_ext); } P_ext_diag_i = hypre_CTAlloc(HYPRE_Int, num_cols_offd_A+1); P_ext_offd_i = hypre_CTAlloc(HYPRE_Int, num_cols_offd_A+1); P_ext_diag_size = 0; P_ext_offd_size = 0; last_col_diag_P = first_col_diag_P + num_cols_diag_P -1; for (i=0; i < num_cols_offd_A; i++) { for (j=Ps_ext_i[i]; j < Ps_ext_i[i+1]; j++) if (Ps_ext_j[j] < first_col_diag_P || Ps_ext_j[j] > last_col_diag_P) P_ext_offd_size++; else P_ext_diag_size++; P_ext_diag_i[i+1] = P_ext_diag_size; P_ext_offd_i[i+1] = P_ext_offd_size; } if (P_ext_diag_size) { P_ext_diag_j = hypre_CTAlloc(HYPRE_Int, P_ext_diag_size); P_ext_diag_data = hypre_CTAlloc(HYPRE_Complex, P_ext_diag_size); } if (P_ext_offd_size) { P_ext_offd_j = hypre_CTAlloc(HYPRE_Int, P_ext_offd_size); P_ext_offd_data = hypre_CTAlloc(HYPRE_Complex, P_ext_offd_size); } cnt_offd = 0; cnt_diag = 0; for (i=0; i < num_cols_offd_A; i++) { for (j=Ps_ext_i[i]; j < Ps_ext_i[i+1]; j++) if (Ps_ext_j[j] < first_col_diag_P || Ps_ext_j[j] > last_col_diag_P) { P_ext_offd_j[cnt_offd] = Ps_ext_j[j]; P_ext_offd_data[cnt_offd++] = Ps_ext_data[j]; } else { P_ext_diag_j[cnt_diag] = Ps_ext_j[j] - first_col_diag_P; P_ext_diag_data[cnt_diag++] = Ps_ext_data[j]; } } if (num_procs > 1) { hypre_CSRMatrixDestroy(Ps_ext); Ps_ext = NULL; } cnt = 0; if (P_ext_offd_size || num_cols_offd_P) { temp = hypre_CTAlloc(HYPRE_Int, P_ext_offd_size+num_cols_offd_P); for (i=0; i < P_ext_offd_size; i++) temp[i] = P_ext_offd_j[i]; cnt = P_ext_offd_size; for (i=0; i < num_cols_offd_P; i++) temp[cnt++] = col_map_offd_P[i]; } if (cnt) { hypre_qsort0(temp, 0, cnt-1); num_cols_offd_C = 1; value = temp[0]; for (i=1; i < cnt; i++) { if (temp[i] > value) { value = temp[i]; temp[num_cols_offd_C++] = value; } } } if (num_cols_offd_C) col_map_offd_C = hypre_CTAlloc(HYPRE_Int,num_cols_offd_C); for (i=0; i < num_cols_offd_C; i++) col_map_offd_C[i] = temp[i]; if (P_ext_offd_size || num_cols_offd_P) hypre_TFree(temp); for (i=0 ; i < P_ext_offd_size; i++) P_ext_offd_j[i] = hypre_BinarySearch(col_map_offd_C, P_ext_offd_j[i], num_cols_offd_C); if (num_cols_offd_P) { map_P_to_C = hypre_CTAlloc(HYPRE_Int,num_cols_offd_P); cnt = 0; for (i=0; i < num_cols_offd_C; i++) if (col_map_offd_C[i] == col_map_offd_P[cnt]) { map_P_to_C[cnt++] = i; if (cnt == num_cols_offd_P) break; } } /*----------------------------------------------------------------------- * Allocate marker array. *-----------------------------------------------------------------------*/ P_marker = hypre_CTAlloc(HYPRE_Int, num_cols_diag_P+num_cols_offd_C); /*----------------------------------------------------------------------- * Initialize some stuff. *-----------------------------------------------------------------------*/ for (i1 = 0; i1 < num_cols_diag_P+num_cols_offd_C; i1++) { P_marker[i1] = -1; } /* no changes for the marked version above this point */ /* This function call is the first pass: */ hypre_ParMatmul_RowSizes_Marked( &C_diag_i, &C_offd_i, &P_marker, A_diag_i, A_diag_j, A_offd_i, A_offd_j, P_diag_i, P_diag_j, P_offd_i, P_offd_j, P_ext_diag_i, P_ext_diag_j, P_ext_offd_i, P_ext_offd_j, map_P_to_C, &C_diag_size, &C_offd_size, num_rows_diag_A, num_cols_offd_A, allsquare, num_cols_diag_P, num_cols_offd_P, num_cols_offd_C, CF_marker, dof_func, dof_func_offd ); /* The above call of hypre_ParMatmul_RowSizes_Marked computed two scalars: C_diag_size, C_offd_size, and two arrays: C_diag_i, C_offd_i ( P_marker is also computed, but only used internally ) */ /*----------------------------------------------------------------------- * Allocate C_diag_data and C_diag_j arrays. * Allocate C_offd_data and C_offd_j arrays. *-----------------------------------------------------------------------*/ last_col_diag_P = first_col_diag_P + num_cols_diag_P - 1; C_diag_data = hypre_CTAlloc(HYPRE_Complex, C_diag_size); C_diag_j = hypre_CTAlloc(HYPRE_Int, C_diag_size); if (C_offd_size) { C_offd_data = hypre_CTAlloc(HYPRE_Complex, C_offd_size); C_offd_j = hypre_CTAlloc(HYPRE_Int, C_offd_size); } /*----------------------------------------------------------------------- * Second Pass: Fill in C_diag_data and C_diag_j. * Second Pass: Fill in C_offd_data and C_offd_j. *-----------------------------------------------------------------------*/ /*----------------------------------------------------------------------- * Initialize some stuff. *-----------------------------------------------------------------------*/ jj_count_diag = start_indexing; jj_count_offd = start_indexing; for (i1 = 0; i1 < num_cols_diag_P+num_cols_offd_C; i1++) { P_marker[i1] = -1; } /*----------------------------------------------------------------------- * Loop over interior c-points. *-----------------------------------------------------------------------*/ for (i1 = 0; i1 < num_rows_diag_A; i1++) { if ( CF_marker[i1] < 0 ) /* i1 is a fine row */ /* ... This and the coarse row code are the only parts between first pass and near the end where hypre_ParMatmul_FC is different from the regular hypre_ParMatmul */ { /*-------------------------------------------------------------------- * Create diagonal entry, C_{i1,i1} *--------------------------------------------------------------------*/ jj_row_begin_diag = jj_count_diag; jj_row_begin_offd = jj_count_offd; /*----------------------------------------------------------------- * Loop over entries in row i1 of A_offd. *-----------------------------------------------------------------*/ if (num_cols_offd_A) { for (jj2 = A_offd_i[i1]; jj2 < A_offd_i[i1+1]; jj2++) { i2 = A_offd_j[jj2]; if( dof_func==NULL || dof_func[i1] == dof_func_offd[i2] ) { /* interpolate only like "functions" */ a_entry = A_offd_data[jj2]; /*----------------------------------------------------------- * Loop over entries in row i2 of P_ext. *-----------------------------------------------------------*/ for (jj3 = P_ext_offd_i[i2]; jj3 < P_ext_offd_i[i2+1]; jj3++) { i3 = num_cols_diag_P+P_ext_offd_j[jj3]; a_b_product = a_entry * P_ext_offd_data[jj3]; /*-------------------------------------------------------- * Check P_marker to see that C_{i1,i3} has not already * been accounted for. If it has not, create a new entry. * If it has, add new contribution. *--------------------------------------------------------*/ if (P_marker[i3] < jj_row_begin_offd) { P_marker[i3] = jj_count_offd; C_offd_data[jj_count_offd] = a_b_product; C_offd_j[jj_count_offd] = i3-num_cols_diag_P; jj_count_offd++; } else C_offd_data[P_marker[i3]] += a_b_product; } for (jj3 = P_ext_diag_i[i2]; jj3 < P_ext_diag_i[i2+1]; jj3++) { i3 = P_ext_diag_j[jj3]; a_b_product = a_entry * P_ext_diag_data[jj3]; if (P_marker[i3] < jj_row_begin_diag) { P_marker[i3] = jj_count_diag; C_diag_data[jj_count_diag] = a_b_product; C_diag_j[jj_count_diag] = i3; jj_count_diag++; } else C_diag_data[P_marker[i3]] += a_b_product; } } else { /* Interpolation mat should be 0 where i1 and i2 correspond to different "functions". As we haven't created an entry for C(i1,i2), nothing needs to be done. */ } } } /*----------------------------------------------------------------- * Loop over entries in row i1 of A_diag. *-----------------------------------------------------------------*/ for (jj2 = A_diag_i[i1]; jj2 < A_diag_i[i1+1]; jj2++) { i2 = A_diag_j[jj2]; if( dof_func==NULL || dof_func[i1] == dof_func[i2] ) { /* interpolate only like "functions" */ a_entry = A_diag_data[jj2]; /*----------------------------------------------------------- * Loop over entries in row i2 of P_diag. *-----------------------------------------------------------*/ for (jj3 = P_diag_i[i2]; jj3 < P_diag_i[i2+1]; jj3++) { i3 = P_diag_j[jj3]; a_b_product = a_entry * P_diag_data[jj3]; /*-------------------------------------------------------- * Check P_marker to see that C_{i1,i3} has not already * been accounted for. If it has not, create a new entry. * If it has, add new contribution. *--------------------------------------------------------*/ if (P_marker[i3] < jj_row_begin_diag) { P_marker[i3] = jj_count_diag; C_diag_data[jj_count_diag] = a_b_product; C_diag_j[jj_count_diag] = i3; jj_count_diag++; } else { C_diag_data[P_marker[i3]] += a_b_product; } } if (num_cols_offd_P) { for (jj3 = P_offd_i[i2]; jj3 < P_offd_i[i2+1]; jj3++) { i3 = num_cols_diag_P+map_P_to_C[P_offd_j[jj3]]; a_b_product = a_entry * P_offd_data[jj3]; /*-------------------------------------------------------- * Check P_marker to see that C_{i1,i3} has not already * been accounted for. If it has not, create a new entry. * If it has, add new contribution. *--------------------------------------------------------*/ if (P_marker[i3] < jj_row_begin_offd) { P_marker[i3] = jj_count_offd; C_offd_data[jj_count_offd] = a_b_product; C_offd_j[jj_count_offd] = i3-num_cols_diag_P; jj_count_offd++; } else { C_offd_data[P_marker[i3]] += a_b_product; } } } } else { /* Interpolation mat should be 0 where i1 and i2 correspond to different "functions". As we haven't created an entry for C(i1,i2), nothing needs to be done. */ } } } else /* i1 is a coarse row.*/ /* Copy P coarse-row values to C. This is useful if C is meant to become a replacement for P */ { if (num_cols_offd_P) { for (jj2 = P_offd_i[i1]; jj2 < P_offd_i[i1+1]; jj2++) { C_offd_j[jj_count_offd] = P_offd_j[jj_count_offd]; C_offd_data[jj_count_offd] = P_offd_data[jj_count_offd]; ++jj_count_offd; } } for (jj2 = P_diag_i[i1]; jj2 < P_diag_i[i1+1]; jj2++) { C_diag_j[jj_count_diag] = P_diag_j[jj2]; C_diag_data[jj_count_diag] = P_diag_data[jj2]; ++jj_count_diag; } } } C = hypre_ParCSRMatrixCreate( comm, n_rows_A_global, n_cols_P_global, row_starts_A, col_starts_P, num_cols_offd_C, C_diag_size, C_offd_size ); /* Note that C does not own the partitionings */ hypre_ParCSRMatrixSetRowStartsOwner(C,0); hypre_ParCSRMatrixSetColStartsOwner(C,0); C_diag = hypre_ParCSRMatrixDiag(C); hypre_CSRMatrixData(C_diag) = C_diag_data; hypre_CSRMatrixI(C_diag) = C_diag_i; hypre_CSRMatrixJ(C_diag) = C_diag_j; C_offd = hypre_ParCSRMatrixOffd(C); hypre_CSRMatrixI(C_offd) = C_offd_i; hypre_ParCSRMatrixOffd(C) = C_offd; if (num_cols_offd_C) { hypre_CSRMatrixData(C_offd) = C_offd_data; hypre_CSRMatrixJ(C_offd) = C_offd_j; hypre_ParCSRMatrixColMapOffd(C) = col_map_offd_C; } /*----------------------------------------------------------------------- * Free various arrays *-----------------------------------------------------------------------*/ hypre_TFree(P_marker); hypre_TFree(P_ext_diag_i); if (P_ext_diag_size) { hypre_TFree(P_ext_diag_j); hypre_TFree(P_ext_diag_data); } hypre_TFree(P_ext_offd_i); if (P_ext_offd_size) { hypre_TFree(P_ext_offd_j); hypre_TFree(P_ext_offd_data); } if (num_cols_offd_P) hypre_TFree(map_P_to_C); return C; } void hypre_ParMatScaleDiagInv_F( hypre_ParCSRMatrix * C, hypre_ParCSRMatrix * A, HYPRE_Complex weight, HYPRE_Int * CF_marker ) /* hypre_ParMatScaleDiagInv scales certain rows of its first * argument by premultiplying with a submatrix of the inverse of * the diagonal of its second argument; and _also_ multiplying by the scalar * third argument. * The marker array determines rows are changed and which diagonal elements * are used. */ { /* If A=(Aij),C=(Cik), i&j in Fine+Coarse, k in Coarse, we want new Cik = (1/aii)*Cik, for Fine i only, all k. Unlike a matmul, this computation is purely local, only the diag blocks are involved. */ hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); hypre_CSRMatrix *C_diag = hypre_ParCSRMatrixDiag(C); hypre_CSRMatrix *C_offd = hypre_ParCSRMatrixOffd(C); HYPRE_Complex *A_diag_data = hypre_CSRMatrixData(A_diag); HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag); HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag); HYPRE_Complex *C_diag_data = hypre_CSRMatrixData(C_diag); HYPRE_Complex *C_offd_data = hypre_CSRMatrixData(C_offd); HYPRE_Int *C_diag_i = hypre_CSRMatrixI(C_diag); HYPRE_Int *C_offd_i = hypre_CSRMatrixI(C_offd); HYPRE_Int num_rows_diag_C = hypre_CSRMatrixNumRows(C_diag); HYPRE_Int num_cols_offd_C = hypre_CSRMatrixNumCols(C_offd); HYPRE_Int i1, i2; HYPRE_Int jj2, jj3; HYPRE_Complex a_entry; /*----------------------------------------------------------------------- * Loop over C_diag rows. *-----------------------------------------------------------------------*/ for (i1 = 0; i1 < num_rows_diag_C; i1++) { if ( CF_marker[i1] < 0 ) /* Fine data only */ { /*----------------------------------------------------------------- * Loop over A_diag data *-----------------------------------------------------------------*/ for (jj2 = A_diag_i[i1]; jj2 < A_diag_i[i1+1]; jj2++) { i2 = A_diag_j[jj2]; if ( i1==i2 ) /* diagonal of A only */ { a_entry = A_diag_data[jj2] * weight; /*----------------------------------------------------------- * Loop over entries in current row of C_diag. *-----------------------------------------------------------*/ for (jj3 = C_diag_i[i2]; jj3 < C_diag_i[i2+1]; jj3++) { C_diag_data[jj3] = C_diag_data[jj3] / a_entry; } /*----------------------------------------------------------- * Loop over entries in current row of C_offd. *-----------------------------------------------------------*/ if ( num_cols_offd_C ) { for (jj3 = C_offd_i[i2]; jj3 < C_offd_i[i2+1]; jj3++) { C_offd_data[jj3] = C_offd_data[jj3] / a_entry; } } } } } } } hypre_ParCSRMatrix * hypre_ParMatMinus_F( hypre_ParCSRMatrix * P, hypre_ParCSRMatrix * C, HYPRE_Int * CF_marker ) /* hypre_ParMatMinus_F subtracts selected rows of its second argument from selected rows of its first argument. The marker array determines which rows are affected - those for which CF_marker<0. The result is returned as a new matrix. */ { /* If P=(Pik),C=(Cik), i in Fine+Coarse, k in Coarse, we want new Pik = Pik - Cik, for Fine i only, all k. This computation is purely local. */ /* This is _not_ a general-purpose matrix subtraction function. This is written for an interpolation problem where it is known that C(i,k) exists whenever P(i,k) does (because C=A*P where A has nonzero diagonal elements). */ hypre_ParCSRMatrix *Pnew; hypre_CSRMatrix *P_diag = hypre_ParCSRMatrixDiag(P); hypre_CSRMatrix *P_offd = hypre_ParCSRMatrixOffd(P); hypre_CSRMatrix *C_diag = hypre_ParCSRMatrixDiag(C); hypre_CSRMatrix *C_offd = hypre_ParCSRMatrixOffd(C); hypre_CSRMatrix *Pnew_diag; hypre_CSRMatrix *Pnew_offd; HYPRE_Complex *P_diag_data = hypre_CSRMatrixData(P_diag); HYPRE_Int *P_diag_i = hypre_CSRMatrixI(P_diag); HYPRE_Int *P_diag_j = hypre_CSRMatrixJ(P_diag); HYPRE_Complex *P_offd_data = hypre_CSRMatrixData(P_offd); HYPRE_Int *P_offd_i = hypre_CSRMatrixI(P_offd); HYPRE_Int *P_offd_j = hypre_CSRMatrixJ(P_offd); HYPRE_Int *P_col_map_offd = hypre_ParCSRMatrixColMapOffd( P ); HYPRE_Complex *C_diag_data = hypre_CSRMatrixData(C_diag); HYPRE_Int *C_diag_i = hypre_CSRMatrixI(C_diag); HYPRE_Int *C_diag_j = hypre_CSRMatrixJ(C_diag); HYPRE_Complex *C_offd_data = hypre_CSRMatrixData(C_offd); HYPRE_Int *C_offd_i = hypre_CSRMatrixI(C_offd); HYPRE_Int *C_offd_j = hypre_CSRMatrixJ(C_offd); HYPRE_Int *C_col_map_offd = hypre_ParCSRMatrixColMapOffd( C ); HYPRE_Int *Pnew_diag_i; HYPRE_Int *Pnew_diag_j; HYPRE_Complex *Pnew_diag_data; HYPRE_Int *Pnew_offd_i; HYPRE_Int *Pnew_offd_j; HYPRE_Complex *Pnew_offd_data; HYPRE_Int *Pnew_j2m; HYPRE_Int *Pnew_col_map_offd; HYPRE_Int num_rows_diag_C = hypre_CSRMatrixNumRows(C_diag); /* HYPRE_Int num_rows_offd_C = hypre_CSRMatrixNumRows(C_offd); */ HYPRE_Int num_cols_offd_C = hypre_CSRMatrixNumCols(C_offd); HYPRE_Int num_cols_offd_P = hypre_CSRMatrixNumCols(P_offd); HYPRE_Int num_cols_offd_Pnew, num_rows_offd_Pnew; HYPRE_Int i1, jmin, jmax, jrange, jrangem1; HYPRE_Int j, m, mc, mp, jc, jp, jP, jC, jg, jCg, jPg; HYPRE_Complex dc, dp; /* Pnew = hypre_ParCSRMatrixCompleteClone( C );*/ Pnew = hypre_ParCSRMatrixUnion( C, P ); ; hypre_ParCSRMatrixZero_F( Pnew, CF_marker ); /* fine rows of Pnew set to 0 */ hypre_ParCSRMatrixCopy_C( Pnew, C, CF_marker ); /* coarse rows of Pnew copied * from C (or P) */ /* ...Zero_F may not be needed depending on how Pnew is made */ Pnew_diag = hypre_ParCSRMatrixDiag(Pnew); Pnew_offd = hypre_ParCSRMatrixOffd(Pnew); Pnew_diag_i = hypre_CSRMatrixI(Pnew_diag); Pnew_diag_j = hypre_CSRMatrixJ(Pnew_diag); Pnew_offd_i = hypre_CSRMatrixI(Pnew_offd); Pnew_offd_j = hypre_CSRMatrixJ(Pnew_offd); Pnew_diag_data = hypre_CSRMatrixData(Pnew_diag); Pnew_offd_data = hypre_CSRMatrixData(Pnew_offd); Pnew_col_map_offd = hypre_ParCSRMatrixColMapOffd( Pnew ); num_rows_offd_Pnew = hypre_CSRMatrixNumRows(Pnew_offd); num_cols_offd_Pnew = hypre_CSRMatrixNumCols(Pnew_offd); /* Find the j-ranges, needed to allocate a "reverse lookup" array. */ /* This is the max j - min j over P and Pnew (which here is a copy of C). Only the diag block is considered. */ /* For scalability reasons (jrange can get big) this won't work for the offd block. Also, indexing is more complicated in the offd block (c.f. col_map_offd). It's not clear, though whether the "quadratic" algorithm I'm using for the offd block is really any slower than the more complicated "linear" algorithm here. */ jrange = 0; jrangem1=-1; for ( i1 = 0; i1 < num_rows_diag_C; i1++ ) { /* only Fine rows matter */ if ( CF_marker[i1]<0 && hypre_CSRMatrixNumNonzeros(Pnew_diag)>0 ) { jmin = Pnew_diag_j[ Pnew_diag_i[i1] ]; jmax = Pnew_diag_j[ Pnew_diag_i[i1+1]-1 ]; jrangem1 = jmax-jmin; jrange = hypre_max(jrange,jrangem1+1); /* If columns (of a given row) were in increasing order, the above would be sufficient. If not, the following would be necessary (and sufficient) */ jmin = Pnew_diag_j[ Pnew_diag_i[i1] ]; jmax = Pnew_diag_j[ Pnew_diag_i[i1] ]; for ( m=Pnew_diag_i[i1]+1; m<Pnew_diag_i[i1+1]; ++m ) { j = Pnew_diag_j[m]; jmin = hypre_min( jmin, j ); jmax = hypre_max( jmax, j ); } for ( m=P_diag_i[i1]; m<P_diag_i[i1+1]; ++m ) { j = P_diag_j[m]; jmin = hypre_min( jmin, j ); jmax = hypre_max( jmax, j ); } jrangem1 = jmax-jmin; jrange = hypre_max(jrange,jrangem1+1); } } /*----------------------------------------------------------------------- * Loop over Pnew_diag rows. Construct a temporary reverse array: * If j is a column number, Pnew_j2m[j] is the array index for j, i.e. * Pnew_diag_j[ Pnew_j2m[j] ] = j *-----------------------------------------------------------------------*/ Pnew_j2m = hypre_CTAlloc( HYPRE_Int, jrange ); for ( i1 = 0; i1 < num_rows_diag_C; i1++ ) { /* Fine data only */ if ( CF_marker[i1]<0 && hypre_CSRMatrixNumNonzeros(Pnew_diag)>0 ) { /* just needed for an assertion below... */ for ( j=0; j<jrange; ++j ) Pnew_j2m[j] = -1; jmin = Pnew_diag_j[ Pnew_diag_i[i1] ]; /* If columns (of a given row) were in increasing order, the above line would be sufficient. If not, the following loop would have to be added (or store the jmin computed above )*/ for ( m=Pnew_diag_i[i1]+1; m<Pnew_diag_i[i1+1]; ++m ) { j = Pnew_diag_j[m]; jmin = hypre_min( jmin, j ); } for ( m=P_diag_i[i1]; m<P_diag_i[i1+1]; ++m ) { j = P_diag_j[m]; jmin = hypre_min( jmin, j ); } for ( m = Pnew_diag_i[i1]; m<Pnew_diag_i[i1+1]; ++m ) { j = Pnew_diag_j[m]; hypre_assert( j-jmin>=0 ); hypre_assert( j-jmin<jrange ); Pnew_j2m[ j-jmin ] = m; } /*----------------------------------------------------------------------- * Loop over C_diag data for the current row. * Subtract each C data entry from the corresponding Pnew entry. *-----------------------------------------------------------------------*/ for ( mc=C_diag_i[i1]; mc<C_diag_i[i1+1]; ++mc ) { jc = C_diag_j[mc]; dc = C_diag_data[mc]; m = Pnew_j2m[jc-jmin]; hypre_assert( m>=0 ); Pnew_diag_data[m] -= dc; } /*----------------------------------------------------------------------- * Loop over P_diag data for the current row. * Add each P data entry from the corresponding Pnew entry. *-----------------------------------------------------------------------*/ for ( mp=P_diag_i[i1]; mp<P_diag_i[i1+1]; ++mp ) { jp = P_diag_j[mp]; dp = P_diag_data[mp]; m = Pnew_j2m[jp-jmin]; hypre_assert( m>=0 ); Pnew_diag_data[m] += dp; } } } /*----------------------------------------------------------------------- * Repeat for the offd block. *-----------------------------------------------------------------------*/ for ( i1 = 0; i1 < num_rows_offd_Pnew; i1++ ) { /* Fine data only */ if ( CF_marker[i1]<0 && hypre_CSRMatrixNumNonzeros(Pnew_offd)>0 ) { if ( num_cols_offd_Pnew ) { /* This is a simple quadratic algorithm. If necessary I may try to implement the ideas used on the diag block later. */ for ( m = Pnew_offd_i[i1]; m<Pnew_offd_i[i1+1]; ++m ) { j = Pnew_offd_j[m]; jg = Pnew_col_map_offd[j]; Pnew_offd_data[m] = 0; if ( num_cols_offd_C ) for ( mc=C_offd_i[i1]; mc<C_offd_i[i1+1]; ++mc ) { jC = C_offd_j[mc]; jCg = C_col_map_offd[jC]; if ( jCg==jg ) Pnew_offd_data[m] -= C_offd_data[mc]; } if ( num_cols_offd_P ) for ( mp=P_offd_i[i1]; mp<P_offd_i[i1+1]; ++mp ) { jP = P_offd_j[mp]; jPg = P_col_map_offd[jP]; if ( jPg==jg ) Pnew_offd_data[m] += P_offd_data[mp]; } } } } } hypre_TFree(Pnew_j2m); return Pnew; } /* fine (marked <0 ) rows of Pnew set to 0 */ void hypre_ParCSRMatrixZero_F( hypre_ParCSRMatrix * P, HYPRE_Int * CF_marker ) { hypre_CSRMatrix *P_diag = hypre_ParCSRMatrixDiag(P); hypre_CSRMatrix *P_offd = hypre_ParCSRMatrixOffd(P); HYPRE_Complex *P_diag_data = hypre_CSRMatrixData(P_diag); HYPRE_Int *P_diag_i = hypre_CSRMatrixI(P_diag); HYPRE_Complex *P_offd_data = hypre_CSRMatrixData(P_offd); HYPRE_Int *P_offd_i = hypre_CSRMatrixI(P_offd); HYPRE_Int num_rows_diag_P = hypre_CSRMatrixNumRows(P_diag); HYPRE_Int num_rows_offd_P = hypre_CSRMatrixNumRows(P_offd); HYPRE_Int num_cols_offd_P = hypre_CSRMatrixNumCols(P_offd); HYPRE_Int i1, m; for ( i1= 0; i1 < num_rows_diag_P; i1++ ) { if ( CF_marker[i1] < 0 ) /* Fine rows only */ { for ( m=P_diag_i[i1]; m<P_diag_i[i1+1]; ++m ) { P_diag_data[m] = 0; } } } if ( num_cols_offd_P ) for ( i1= 0; i1 < num_rows_offd_P; i1++ ) { if ( CF_marker[i1] < 0 ) /* Fine rows only */ { for ( m=P_offd_i[i1]; m<P_offd_i[i1+1]; ++m ) { P_offd_data[m] = 0; } } } } /* coarse (marked >=0) rows of P copied from C Both matrices have the same sizes. */ void hypre_ParCSRMatrixCopy_C( hypre_ParCSRMatrix * P, hypre_ParCSRMatrix * C, HYPRE_Int * CF_marker ) { hypre_CSRMatrix *C_diag = hypre_ParCSRMatrixDiag(C); hypre_CSRMatrix *C_offd = hypre_ParCSRMatrixOffd(C); hypre_CSRMatrix *P_diag = hypre_ParCSRMatrixDiag(P); hypre_CSRMatrix *P_offd = hypre_ParCSRMatrixOffd(P); HYPRE_Complex *C_diag_data = hypre_CSRMatrixData(C_diag); HYPRE_Int *C_diag_i = hypre_CSRMatrixI(C_diag); HYPRE_Complex *C_offd_data = hypre_CSRMatrixData(C_offd); HYPRE_Int *C_offd_i = hypre_CSRMatrixI(C_offd); HYPRE_Complex *P_diag_data = hypre_CSRMatrixData(P_diag); HYPRE_Complex *P_offd_data = hypre_CSRMatrixData(P_offd); HYPRE_Int num_rows_diag_C = hypre_CSRMatrixNumRows(C_diag); HYPRE_Int num_rows_offd_C = hypre_CSRMatrixNumRows(C_offd); HYPRE_Int num_cols_offd_C = hypre_CSRMatrixNumCols(C_offd); HYPRE_Int i1, m; for ( i1= 0; i1 < num_rows_diag_C; i1++ ) { if ( CF_marker[i1] >= 0 ) /* Coarse rows only */ { for ( m=C_diag_i[i1]; m<C_diag_i[i1+1]; ++m ) { P_diag_data[m] = C_diag_data[m]; } } } if ( num_cols_offd_C ) for ( i1= 0; i1 < num_rows_offd_C; i1++ ) { if ( CF_marker[i1] >= 0 ) /* Coarse rows only */ { for ( m=C_offd_i[i1]; m<C_offd_i[i1+1]; ++m ) { P_offd_data[m] = C_offd_data[m]; } } } } /* RDF: Commented out due to issues with complex types and comparisons that * don't make sense anyway. The function wasn't being used, either. */ #if 0 /* Delete any matrix entry C(i,j) for which the corresponding entry P(i,j) doesn't exist - but only for "fine" rows C(i)<0 This is done as a purely local computation - C and P must have the same data distribution (among processors). */ void hypre_ParCSRMatrixDropEntries( hypre_ParCSRMatrix * C, hypre_ParCSRMatrix * P, HYPRE_Int * CF_marker ) { hypre_CSRMatrix *C_diag = hypre_ParCSRMatrixDiag(C); hypre_CSRMatrix *C_offd = hypre_ParCSRMatrixOffd(C); HYPRE_Complex *C_diag_data = hypre_CSRMatrixData(C_diag); HYPRE_Int *C_diag_i = hypre_CSRMatrixI(C_diag); HYPRE_Int *C_diag_j = hypre_CSRMatrixJ(C_diag); HYPRE_Complex *C_offd_data = hypre_CSRMatrixData(C_offd); HYPRE_Int *C_offd_i = hypre_CSRMatrixI(C_offd); HYPRE_Int *C_offd_j = hypre_CSRMatrixJ(C_offd); hypre_CSRMatrix *P_diag = hypre_ParCSRMatrixDiag(P); hypre_CSRMatrix *P_offd = hypre_ParCSRMatrixOffd(P); HYPRE_Int *P_diag_i = hypre_CSRMatrixI(P_diag); HYPRE_Int *P_diag_j = hypre_CSRMatrixJ(P_diag); HYPRE_Int *P_offd_i = hypre_CSRMatrixI(P_offd); HYPRE_Int *P_offd_j = hypre_CSRMatrixJ(P_offd); HYPRE_Int *new_C_diag_i; HYPRE_Int *new_C_offd_i; HYPRE_Int num_rows_diag_C = hypre_CSRMatrixNumRows(C_diag); HYPRE_Int num_rows_offd_C = hypre_CSRMatrixNumCols(C_offd); HYPRE_Int num_nonzeros_diag = hypre_CSRMatrixNumNonzeros(C_diag); HYPRE_Int num_nonzeros_offd = hypre_CSRMatrixNumNonzeros(C_offd); HYPRE_Complex vmax = 0.0; HYPRE_Complex vmin = 0.0; HYPRE_Complex v, old_sum, new_sum, scale; HYPRE_Int i1, m, m1d, m1o, jC, mP, keep; /* Repack the i,j,and data arrays of C so as to discard those elements for which there is no corresponding element in P. Elements of Coarse rows (CF_marker>=0) are always kept. The arrays are not re-allocated, so there will generally be unused space at the ends of the arrays. */ new_C_diag_i = hypre_CTAlloc( HYPRE_Int, num_rows_diag_C+1 ); new_C_offd_i = hypre_CTAlloc( HYPRE_Int, num_rows_offd_C+1 ); m1d = C_diag_i[0]; m1o = C_offd_i[0]; for ( i1 = 0; i1 < num_rows_diag_C; i1++ ) { old_sum = 0; new_sum = 0; for ( m=C_diag_i[i1]; m<C_diag_i[i1+1]; ++m ) { v = C_diag_data[m]; jC = C_diag_j[m]; old_sum += v; /* Do we know anything about the order of P_diag_j? It would be better not to search through it all here. If we know nothing, some ordering or index scheme will be needed for efficiency (worth doing iff this function gets called at all ) (may2006: this function is no longer called) */ keep=0; for ( mP=P_diag_i[i1]; mP<P_diag_i[i1+1]; ++mP ) { if ( jC==P_diag_j[m] ) { keep=1; break; } } if ( CF_marker[i1]>=0 || keep==1 ) { /* keep v in C */ new_sum += v; C_diag_j[m1d] = C_diag_j[m]; C_diag_data[m1d] = C_diag_data[m]; ++m1d; } else { /* discard v */ --num_nonzeros_diag; } } for ( m=C_offd_i[i1]; m<C_offd_i[i1+1]; ++m ) { v = C_offd_data[m]; jC = C_diag_j[m]; old_sum += v; keep=0; for ( mP=P_offd_i[i1]; mP<P_offd_i[i1+1]; ++mP ) { if ( jC==P_offd_j[m] ) { keep=1; break; } } if ( CF_marker[i1]>=0 || v>=vmax || v<=vmin ) /* RDF: Always true!? */ { /* keep v in C */ new_sum += v; C_offd_j[m1o] = C_offd_j[m]; C_offd_data[m1o] = C_offd_data[m]; ++m1o; } else { /* discard v */ --num_nonzeros_offd; } } new_C_diag_i[i1+1] = m1d; if ( i1<num_rows_offd_C ) new_C_offd_i[i1+1] = m1o; /* rescale to keep row sum the same */ if (new_sum!=0) scale = old_sum/new_sum; else scale = 1.0; for ( m=new_C_diag_i[i1]; m<new_C_diag_i[i1+1]; ++m ) C_diag_data[m] *= scale; if ( i1<num_rows_offd_C ) /* this test fails when there is no offd block */ for ( m=new_C_offd_i[i1]; m<new_C_offd_i[i1+1]; ++m ) C_offd_data[m] *= scale; } for ( i1 = 1; i1 <= num_rows_diag_C; i1++ ) { C_diag_i[i1] = new_C_diag_i[i1]; if ( i1<num_rows_offd_C ) C_offd_i[i1] = new_C_offd_i[i1]; } hypre_TFree( new_C_diag_i ); if ( num_rows_offd_C>0 ) hypre_TFree( new_C_offd_i ); hypre_CSRMatrixNumNonzeros(C_diag) = num_nonzeros_diag; hypre_CSRMatrixNumNonzeros(C_offd) = num_nonzeros_offd; /* SetNumNonzeros, SetDNumNonzeros are global, need hypre_MPI_Allreduce. I suspect, but don't know, that other parts of hypre do not assume that the correct values have been set. hypre_ParCSRMatrixSetNumNonzeros( C ); hypre_ParCSRMatrixSetDNumNonzeros( C );*/ hypre_ParCSRMatrixNumNonzeros( C ) = 0; hypre_ParCSRMatrixDNumNonzeros( C ) = 0.0; } #endif
51,595
37.940377
88
c
AMG
AMG-master/parcsr_mv/par_csr_matrix.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /****************************************************************************** * * Member functions for hypre_ParCSRMatrix class. * *****************************************************************************/ #include "_hypre_parcsr_mv.h" #include "../seq_mv/HYPRE_seq_mv.h" #include "../seq_mv/csr_matrix.h" /* In addition to publically accessible interface in HYPRE_mv.h, the implementation in this file uses accessor macros into the sequential matrix structure, and so includes the .h that defines that structure. Should those accessor functions become proper functions at some later date, this will not be necessary. AJC 4/99 */ #ifdef HYPRE_NO_GLOBAL_PARTITION HYPRE_Int hypre_FillResponseParToCSRMatrix(void*, HYPRE_Int, HYPRE_Int, void*, MPI_Comm, void**, HYPRE_Int*); #endif /*-------------------------------------------------------------------------- * hypre_ParCSRMatrixCreate *--------------------------------------------------------------------------*/ /* If create is called for HYPRE_NO_GLOBAL_PARTITION and row_starts and col_starts are NOT null, then it is assumed that they are array of length 2 containing the start row of the calling processor followed by the start row of the next processor - AHB 6/05 */ hypre_ParCSRMatrix * hypre_ParCSRMatrixCreate( MPI_Comm comm, HYPRE_Int global_num_rows, HYPRE_Int global_num_cols, HYPRE_Int *row_starts, HYPRE_Int *col_starts, HYPRE_Int num_cols_offd, HYPRE_Int num_nonzeros_diag, HYPRE_Int num_nonzeros_offd ) { hypre_ParCSRMatrix *matrix; HYPRE_Int num_procs, my_id; HYPRE_Int local_num_rows, local_num_cols; HYPRE_Int first_row_index, first_col_diag; matrix = hypre_CTAlloc(hypre_ParCSRMatrix, 1); hypre_MPI_Comm_rank(comm,&my_id); hypre_MPI_Comm_size(comm,&num_procs); if (!row_starts) { #ifdef HYPRE_NO_GLOBAL_PARTITION hypre_GenerateLocalPartitioning(global_num_rows, num_procs, my_id, &row_starts); #else hypre_GeneratePartitioning(global_num_rows, num_procs, &row_starts); #endif } if (!col_starts) { if (global_num_rows == global_num_cols) { col_starts = row_starts; } else { #ifdef HYPRE_NO_GLOBAL_PARTITION hypre_GenerateLocalPartitioning(global_num_cols, num_procs, my_id, &col_starts); #else hypre_GeneratePartitioning(global_num_cols, num_procs, &col_starts); #endif } } #ifdef HYPRE_NO_GLOBAL_PARTITION /* row_starts[0] is start of local rows. row_starts[1] is start of next processor's rows */ first_row_index = row_starts[0]; local_num_rows = row_starts[1]-first_row_index ; first_col_diag = col_starts[0]; local_num_cols = col_starts[1]-first_col_diag; #else first_row_index = row_starts[my_id]; local_num_rows = row_starts[my_id+1]-first_row_index; first_col_diag = col_starts[my_id]; local_num_cols = col_starts[my_id+1]-first_col_diag; #endif hypre_ParCSRMatrixComm(matrix) = comm; hypre_ParCSRMatrixDiag(matrix) = hypre_CSRMatrixCreate(local_num_rows, local_num_cols,num_nonzeros_diag); hypre_ParCSRMatrixOffd(matrix) = hypre_CSRMatrixCreate(local_num_rows, num_cols_offd,num_nonzeros_offd); hypre_ParCSRMatrixDiagT(matrix) = NULL; hypre_ParCSRMatrixOffdT(matrix) = NULL; // JSP: transposed matrices are optional hypre_ParCSRMatrixGlobalNumRows(matrix) = global_num_rows; hypre_ParCSRMatrixGlobalNumCols(matrix) = global_num_cols; hypre_ParCSRMatrixFirstRowIndex(matrix) = first_row_index; hypre_ParCSRMatrixFirstColDiag(matrix) = first_col_diag; hypre_ParCSRMatrixLastRowIndex(matrix) = first_row_index + local_num_rows - 1; hypre_ParCSRMatrixLastColDiag(matrix) = first_col_diag + local_num_cols - 1; hypre_ParCSRMatrixColMapOffd(matrix) = NULL; hypre_ParCSRMatrixAssumedPartition(matrix) = NULL; /* When NO_GLOBAL_PARTITION is set we could make these null, instead of leaving the range. If that change is made, then when this create is called from functions like the matrix-matrix multiply, be careful not to generate a new partition */ hypre_ParCSRMatrixRowStarts(matrix) = row_starts; hypre_ParCSRMatrixColStarts(matrix) = col_starts; hypre_ParCSRMatrixCommPkg(matrix) = NULL; hypre_ParCSRMatrixCommPkgT(matrix) = NULL; /* set defaults */ hypre_ParCSRMatrixOwnsData(matrix) = 1; hypre_ParCSRMatrixOwnsRowStarts(matrix) = 1; hypre_ParCSRMatrixOwnsColStarts(matrix) = 1; if (row_starts == col_starts) hypre_ParCSRMatrixOwnsColStarts(matrix) = 0; hypre_ParCSRMatrixRowindices(matrix) = NULL; hypre_ParCSRMatrixRowvalues(matrix) = NULL; hypre_ParCSRMatrixGetrowactive(matrix) = 0; return matrix; } /*-------------------------------------------------------------------------- * hypre_ParCSRMatrixDestroy *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParCSRMatrixDestroy( hypre_ParCSRMatrix *matrix ) { if (matrix) { if ( hypre_ParCSRMatrixOwnsData(matrix) ) { hypre_CSRMatrixDestroy(hypre_ParCSRMatrixDiag(matrix)); hypre_CSRMatrixDestroy(hypre_ParCSRMatrixOffd(matrix)); if ( hypre_ParCSRMatrixDiagT(matrix) ) { hypre_CSRMatrixDestroy(hypre_ParCSRMatrixDiagT(matrix)); } if ( hypre_ParCSRMatrixOffdT(matrix) ) { hypre_CSRMatrixDestroy(hypre_ParCSRMatrixOffdT(matrix)); } if (hypre_ParCSRMatrixColMapOffd(matrix)) hypre_TFree(hypre_ParCSRMatrixColMapOffd(matrix)); if (hypre_ParCSRMatrixCommPkg(matrix)) hypre_MatvecCommPkgDestroy(hypre_ParCSRMatrixCommPkg(matrix)); if (hypre_ParCSRMatrixCommPkgT(matrix)) hypre_MatvecCommPkgDestroy(hypre_ParCSRMatrixCommPkgT(matrix)); } if ( hypre_ParCSRMatrixOwnsRowStarts(matrix) ) hypre_TFree(hypre_ParCSRMatrixRowStarts(matrix)); if ( hypre_ParCSRMatrixOwnsColStarts(matrix) ) hypre_TFree(hypre_ParCSRMatrixColStarts(matrix)); hypre_TFree(hypre_ParCSRMatrixRowindices(matrix)); hypre_TFree(hypre_ParCSRMatrixRowvalues(matrix)); if (hypre_ParCSRMatrixAssumedPartition(matrix)) hypre_AssumedPartitionDestroy(hypre_ParCSRMatrixAssumedPartition(matrix)); hypre_TFree(matrix); } return hypre_error_flag; } /*-------------------------------------------------------------------------- * hypre_ParCSRMatrixInitialize *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParCSRMatrixInitialize( hypre_ParCSRMatrix *matrix ) { if (!matrix) { hypre_error_in_arg(1); return hypre_error_flag; } hypre_CSRMatrixInitialize(hypre_ParCSRMatrixDiag(matrix)); hypre_CSRMatrixInitialize(hypre_ParCSRMatrixOffd(matrix)); hypre_ParCSRMatrixColMapOffd(matrix) = hypre_CTAlloc(HYPRE_Int,hypre_CSRMatrixNumCols( hypre_ParCSRMatrixOffd(matrix))); return hypre_error_flag; } /*-------------------------------------------------------------------------- * hypre_ParCSRMatrixSetNumNonzeros *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParCSRMatrixSetNumNonzeros( hypre_ParCSRMatrix *matrix ) { MPI_Comm comm; hypre_CSRMatrix *diag; HYPRE_Int *diag_i; hypre_CSRMatrix *offd; HYPRE_Int *offd_i; HYPRE_Int local_num_rows; HYPRE_Int total_num_nonzeros; HYPRE_Int local_num_nonzeros; if (!matrix) { hypre_error_in_arg(1); return hypre_error_flag; } comm = hypre_ParCSRMatrixComm(matrix); diag = hypre_ParCSRMatrixDiag(matrix); diag_i = hypre_CSRMatrixI(diag); offd = hypre_ParCSRMatrixOffd(matrix); offd_i = hypre_CSRMatrixI(offd); local_num_rows = hypre_CSRMatrixNumRows(diag); local_num_nonzeros = diag_i[local_num_rows] + offd_i[local_num_rows]; hypre_MPI_Allreduce(&local_num_nonzeros, &total_num_nonzeros, 1, HYPRE_MPI_INT, hypre_MPI_SUM, comm); hypre_ParCSRMatrixNumNonzeros(matrix) = total_num_nonzeros; return hypre_error_flag; } /*-------------------------------------------------------------------------- * hypre_ParCSRMatrixSetDNumNonzeros *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParCSRMatrixSetDNumNonzeros( hypre_ParCSRMatrix *matrix ) { MPI_Comm comm; hypre_CSRMatrix *diag; HYPRE_Int *diag_i; hypre_CSRMatrix *offd; HYPRE_Int *offd_i; HYPRE_Int local_num_rows; HYPRE_Real total_num_nonzeros; HYPRE_Real local_num_nonzeros; if (!matrix) { hypre_error_in_arg(1); return hypre_error_flag; } comm = hypre_ParCSRMatrixComm(matrix); diag = hypre_ParCSRMatrixDiag(matrix); diag_i = hypre_CSRMatrixI(diag); offd = hypre_ParCSRMatrixOffd(matrix); offd_i = hypre_CSRMatrixI(offd); local_num_rows = hypre_CSRMatrixNumRows(diag); local_num_nonzeros = (HYPRE_Real) diag_i[local_num_rows] + (HYPRE_Real) offd_i[local_num_rows]; hypre_MPI_Allreduce(&local_num_nonzeros, &total_num_nonzeros, 1, HYPRE_MPI_REAL, hypre_MPI_SUM, comm); hypre_ParCSRMatrixDNumNonzeros(matrix) = total_num_nonzeros; return hypre_error_flag; } /*-------------------------------------------------------------------------- * hypre_ParCSRMatrixSetDataOwner *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParCSRMatrixSetDataOwner( hypre_ParCSRMatrix *matrix, HYPRE_Int owns_data ) { if (!matrix) { hypre_error_in_arg(1); return hypre_error_flag; } hypre_ParCSRMatrixOwnsData(matrix) = owns_data; return hypre_error_flag; } /*-------------------------------------------------------------------------- * hypre_ParCSRMatrixSetRowStartsOwner *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParCSRMatrixSetRowStartsOwner( hypre_ParCSRMatrix *matrix, HYPRE_Int owns_row_starts ) { if (!matrix) { hypre_error_in_arg(1); return hypre_error_flag; } hypre_ParCSRMatrixOwnsRowStarts(matrix) = owns_row_starts; return hypre_error_flag; } /*-------------------------------------------------------------------------- * hypre_ParCSRMatrixSetColStartsOwner *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParCSRMatrixSetColStartsOwner( hypre_ParCSRMatrix *matrix, HYPRE_Int owns_col_starts ) { if (!matrix) { hypre_error_in_arg(1); return hypre_error_flag; } hypre_ParCSRMatrixOwnsColStarts(matrix) = owns_col_starts; return hypre_error_flag; } /*-------------------------------------------------------------------------- * hypre_ParCSRMatrixRead *--------------------------------------------------------------------------*/ hypre_ParCSRMatrix * hypre_ParCSRMatrixRead( MPI_Comm comm, const char *file_name ) { hypre_ParCSRMatrix *matrix; hypre_CSRMatrix *diag; hypre_CSRMatrix *offd; HYPRE_Int my_id, i, num_procs; char new_file_d[80], new_file_o[80], new_file_info[80]; HYPRE_Int global_num_rows, global_num_cols, num_cols_offd; HYPRE_Int local_num_rows; HYPRE_Int *row_starts; HYPRE_Int *col_starts; HYPRE_Int *col_map_offd; FILE *fp; HYPRE_Int equal = 1; #ifdef HYPRE_NO_GLOBAL_PARTITION HYPRE_Int row_s, row_e, col_s, col_e; #endif hypre_MPI_Comm_rank(comm,&my_id); hypre_MPI_Comm_size(comm,&num_procs); #ifdef HYPRE_NO_GLOBAL_PARTITION row_starts = hypre_CTAlloc(HYPRE_Int, 2); col_starts = hypre_CTAlloc(HYPRE_Int, 2); #else row_starts = hypre_CTAlloc(HYPRE_Int, num_procs+1); col_starts = hypre_CTAlloc(HYPRE_Int, num_procs+1); #endif hypre_sprintf(new_file_d,"%s.D.%d",file_name,my_id); hypre_sprintf(new_file_o,"%s.O.%d",file_name,my_id); hypre_sprintf(new_file_info,"%s.INFO.%d",file_name,my_id); fp = fopen(new_file_info, "r"); hypre_fscanf(fp, "%d", &global_num_rows); hypre_fscanf(fp, "%d", &global_num_cols); hypre_fscanf(fp, "%d", &num_cols_offd); #ifdef HYPRE_NO_GLOBAL_PARTITION /* the bgl input file should only contain the EXACT range for local processor */ hypre_fscanf(fp, "%d %d %d %d", &row_s, &row_e, &col_s, &col_e); row_starts[0] = row_s; row_starts[1] = row_e; col_starts[0] = col_s; col_starts[1] = col_e; #else for (i=0; i < num_procs; i++) hypre_fscanf(fp, "%d %d", &row_starts[i], &col_starts[i]); row_starts[num_procs] = global_num_rows; col_starts[num_procs] = global_num_cols; #endif col_map_offd = hypre_CTAlloc(HYPRE_Int, num_cols_offd); for (i=0; i < num_cols_offd; i++) hypre_fscanf(fp, "%d", &col_map_offd[i]); fclose(fp); #ifdef HYPRE_NO_GLOBAL_PARTITION for (i=1; i >= 0; i--) { if (row_starts[i] != col_starts[i]) { equal = 0; break; } } #else for (i=num_procs; i >= 0; i--) { if (row_starts[i] != col_starts[i]) { equal = 0; break; } } #endif if (equal) { hypre_TFree(col_starts); col_starts = row_starts; } diag = hypre_CSRMatrixRead(new_file_d); local_num_rows = hypre_CSRMatrixNumRows(diag); if (num_cols_offd) { offd = hypre_CSRMatrixRead(new_file_o); } else { offd = hypre_CSRMatrixCreate(local_num_rows,0,0); hypre_CSRMatrixInitialize(offd); } matrix = hypre_CTAlloc(hypre_ParCSRMatrix, 1); hypre_ParCSRMatrixComm(matrix) = comm; hypre_ParCSRMatrixGlobalNumRows(matrix) = global_num_rows; hypre_ParCSRMatrixGlobalNumCols(matrix) = global_num_cols; #ifdef HYPRE_NO_GLOBAL_PARTITION hypre_ParCSRMatrixFirstRowIndex(matrix) = row_s; hypre_ParCSRMatrixFirstColDiag(matrix) = col_s; hypre_ParCSRMatrixLastRowIndex(matrix) = row_e - 1; hypre_ParCSRMatrixLastColDiag(matrix) = col_e - 1; #else hypre_ParCSRMatrixFirstRowIndex(matrix) = row_starts[my_id]; hypre_ParCSRMatrixFirstColDiag(matrix) = col_starts[my_id]; hypre_ParCSRMatrixLastRowIndex(matrix) = row_starts[my_id+1]-1; hypre_ParCSRMatrixLastColDiag(matrix) = col_starts[my_id+1]-1; #endif hypre_ParCSRMatrixRowStarts(matrix) = row_starts; hypre_ParCSRMatrixColStarts(matrix) = col_starts; hypre_ParCSRMatrixCommPkg(matrix) = NULL; /* set defaults */ hypre_ParCSRMatrixOwnsData(matrix) = 1; hypre_ParCSRMatrixOwnsRowStarts(matrix) = 1; hypre_ParCSRMatrixOwnsColStarts(matrix) = 1; if (row_starts == col_starts) hypre_ParCSRMatrixOwnsColStarts(matrix) = 0; hypre_ParCSRMatrixDiag(matrix) = diag; hypre_ParCSRMatrixOffd(matrix) = offd; if (num_cols_offd) hypre_ParCSRMatrixColMapOffd(matrix) = col_map_offd; else hypre_ParCSRMatrixColMapOffd(matrix) = NULL; return matrix; } /*-------------------------------------------------------------------------- * hypre_ParCSRMatrixPrint *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParCSRMatrixPrint( hypre_ParCSRMatrix *matrix, const char *file_name ) { MPI_Comm comm; HYPRE_Int global_num_rows; HYPRE_Int global_num_cols; HYPRE_Int *col_map_offd; #ifndef HYPRE_NO_GLOBAL_PARTITION HYPRE_Int *row_starts; HYPRE_Int *col_starts; #endif HYPRE_Int my_id, i, num_procs; char new_file_d[80], new_file_o[80], new_file_info[80]; FILE *fp; HYPRE_Int num_cols_offd = 0; #ifdef HYPRE_NO_GLOBAL_PARTITION HYPRE_Int row_s, row_e, col_s, col_e; #endif if (!matrix) { hypre_error_in_arg(1); return hypre_error_flag; } comm = hypre_ParCSRMatrixComm(matrix); global_num_rows = hypre_ParCSRMatrixGlobalNumRows(matrix); global_num_cols = hypre_ParCSRMatrixGlobalNumCols(matrix); col_map_offd = hypre_ParCSRMatrixColMapOffd(matrix); #ifndef HYPRE_NO_GLOBAL_PARTITION row_starts = hypre_ParCSRMatrixRowStarts(matrix); col_starts = hypre_ParCSRMatrixColStarts(matrix); #endif if (hypre_ParCSRMatrixOffd(matrix)) num_cols_offd = hypre_CSRMatrixNumCols(hypre_ParCSRMatrixOffd(matrix)); hypre_MPI_Comm_rank(comm, &my_id); hypre_MPI_Comm_size(comm, &num_procs); hypre_sprintf(new_file_d,"%s.D.%d",file_name,my_id); hypre_sprintf(new_file_o,"%s.O.%d",file_name,my_id); hypre_sprintf(new_file_info,"%s.INFO.%d",file_name,my_id); hypre_CSRMatrixPrint(hypre_ParCSRMatrixDiag(matrix),new_file_d); if (num_cols_offd != 0) hypre_CSRMatrixPrint(hypre_ParCSRMatrixOffd(matrix),new_file_o); fp = fopen(new_file_info, "w"); hypre_fprintf(fp, "%d\n", global_num_rows); hypre_fprintf(fp, "%d\n", global_num_cols); hypre_fprintf(fp, "%d\n", num_cols_offd); #ifdef HYPRE_NO_GLOBAL_PARTITION row_s = hypre_ParCSRMatrixFirstRowIndex(matrix); row_e = hypre_ParCSRMatrixLastRowIndex(matrix); col_s = hypre_ParCSRMatrixFirstColDiag(matrix); col_e = hypre_ParCSRMatrixLastColDiag(matrix); /* add 1 to the ends because this is a starts partition */ hypre_fprintf(fp, "%d %d %d %d\n", row_s, row_e + 1, col_s, col_e + 1); #else for (i=0; i < num_procs; i++) hypre_fprintf(fp, "%d %d\n", row_starts[i], col_starts[i]); #endif for (i=0; i < num_cols_offd; i++) hypre_fprintf(fp, "%d\n", col_map_offd[i]); fclose(fp); return hypre_error_flag; } /*-------------------------------------------------------------------------- * hypre_ParCSRMatrixPrintIJ *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParCSRMatrixPrintIJ( const hypre_ParCSRMatrix *matrix, const HYPRE_Int base_i, const HYPRE_Int base_j, const char *filename ) { MPI_Comm comm; HYPRE_Int first_row_index; HYPRE_Int first_col_diag; hypre_CSRMatrix *diag; hypre_CSRMatrix *offd; HYPRE_Int *col_map_offd; HYPRE_Int num_rows; HYPRE_Int *row_starts; HYPRE_Int *col_starts; HYPRE_Complex *diag_data; HYPRE_Int *diag_i; HYPRE_Int *diag_j; HYPRE_Complex *offd_data; HYPRE_Int *offd_i; HYPRE_Int *offd_j; HYPRE_Int myid, num_procs, i, j, I, J; char new_filename[255]; FILE *file; HYPRE_Int num_nonzeros_offd; HYPRE_Int ilower, iupper, jlower, jupper; if (!matrix) { hypre_error_in_arg(1); return hypre_error_flag; } comm = hypre_ParCSRMatrixComm(matrix); first_row_index = hypre_ParCSRMatrixFirstRowIndex(matrix); first_col_diag = hypre_ParCSRMatrixFirstColDiag(matrix); diag = hypre_ParCSRMatrixDiag(matrix); offd = hypre_ParCSRMatrixOffd(matrix); col_map_offd = hypre_ParCSRMatrixColMapOffd(matrix); num_rows = hypre_ParCSRMatrixNumRows(matrix); row_starts = hypre_ParCSRMatrixRowStarts(matrix); col_starts = hypre_ParCSRMatrixColStarts(matrix); hypre_MPI_Comm_rank(comm, &myid); hypre_MPI_Comm_size(comm, &num_procs); hypre_sprintf(new_filename,"%s.%05d", filename, myid); if ((file = fopen(new_filename, "w")) == NULL) { hypre_error_w_msg(HYPRE_ERROR_GENERIC,"Error: can't open output file %s\n"); return hypre_error_flag; } num_nonzeros_offd = hypre_CSRMatrixNumNonzeros(offd); diag_data = hypre_CSRMatrixData(diag); diag_i = hypre_CSRMatrixI(diag); diag_j = hypre_CSRMatrixJ(diag); offd_i = hypre_CSRMatrixI(offd); if (num_nonzeros_offd) { offd_data = hypre_CSRMatrixData(offd); offd_j = hypre_CSRMatrixJ(offd); } #ifdef HYPRE_NO_GLOBAL_PARTITION ilower = row_starts[0]+base_i; iupper = row_starts[1]+base_i - 1; jlower = col_starts[0]+base_j; jupper = col_starts[1]+base_j - 1; #else ilower = row_starts[myid] +base_i; iupper = row_starts[myid+1]+base_i - 1; jlower = col_starts[myid] +base_j; jupper = col_starts[myid+1]+base_j - 1; #endif hypre_fprintf(file, "%d %d %d %d\n", ilower, iupper, jlower, jupper); for (i = 0; i < num_rows; i++) { I = first_row_index + i + base_i; /* print diag columns */ for (j = diag_i[i]; j < diag_i[i+1]; j++) { J = first_col_diag + diag_j[j] + base_j; if ( diag_data ) { #ifdef HYPRE_COMPLEX hypre_fprintf(file, "%d %d %.14e , %.14e\n", I, J, hypre_creal(diag_data[j]), hypre_cimag(diag_data[j])); #else hypre_fprintf(file, "%d %d %.14e\n", I, J, diag_data[j]); #endif } else hypre_fprintf(file, "%d %d\n", I, J); } /* print offd columns */ if ( num_nonzeros_offd ) { for (j = offd_i[i]; j < offd_i[i+1]; j++) { J = col_map_offd[offd_j[j]] + base_j; if ( offd_data ) { #ifdef HYPRE_COMPLEX hypre_fprintf(file, "%d %d %.14e , %.14e\n", I, J, hypre_creal(offd_data[j]), hypre_cimag(offd_data[j])); #else hypre_fprintf(file, "%d %d %.14e\n", I, J, offd_data[j]); #endif } else hypre_fprintf(file, "%d %d\n", I, J ); } } } fclose(file); return hypre_error_flag; } /*-------------------------------------------------------------------------- * hypre_ParCSRMatrixReadIJ *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParCSRMatrixReadIJ( MPI_Comm comm, const char *filename, HYPRE_Int *base_i_ptr, HYPRE_Int *base_j_ptr, hypre_ParCSRMatrix **matrix_ptr) { HYPRE_Int global_num_rows; HYPRE_Int global_num_cols; HYPRE_Int first_row_index; HYPRE_Int first_col_diag; HYPRE_Int last_col_diag; hypre_ParCSRMatrix *matrix; hypre_CSRMatrix *diag; hypre_CSRMatrix *offd; HYPRE_Int *col_map_offd; HYPRE_Int *row_starts; HYPRE_Int *col_starts; HYPRE_Int num_rows; HYPRE_Int base_i, base_j; HYPRE_Complex *diag_data; HYPRE_Int *diag_i; HYPRE_Int *diag_j; HYPRE_Complex *offd_data; HYPRE_Int *offd_i; HYPRE_Int *offd_j; HYPRE_Int *aux_offd_j; HYPRE_Int myid, num_procs, i, j, I, J; char new_filename[255]; FILE *file; HYPRE_Int num_cols_offd, num_nonzeros_diag, num_nonzeros_offd; HYPRE_Int equal, i_col, num_cols; HYPRE_Int diag_cnt, offd_cnt, row_cnt; HYPRE_Complex data; hypre_MPI_Comm_size(comm, &num_procs); hypre_MPI_Comm_rank(comm, &myid); hypre_sprintf(new_filename,"%s.%05d", filename, myid); if ((file = fopen(new_filename, "r")) == NULL) { hypre_error_w_msg(HYPRE_ERROR_GENERIC,"Error: can't open output file %s\n"); return hypre_error_flag; } hypre_fscanf(file, "%d %d", &global_num_rows, &global_num_cols); hypre_fscanf(file, "%d %d %d", &num_rows, &num_cols, &num_cols_offd); hypre_fscanf(file, "%d %d", &num_nonzeros_diag, &num_nonzeros_offd); row_starts = hypre_CTAlloc(HYPRE_Int,num_procs+1); col_starts = hypre_CTAlloc(HYPRE_Int,num_procs+1); for (i = 0; i <= num_procs; i++) hypre_fscanf(file, "%d %d", &row_starts[i], &col_starts[i]); base_i = row_starts[0]; base_j = col_starts[0]; equal = 1; for (i = 0; i <= num_procs; i++) { row_starts[i] -= base_i; col_starts[i] -= base_j; if (row_starts[i] != col_starts[i]) equal = 0; } if (equal) { hypre_TFree(col_starts); col_starts = row_starts; } matrix = hypre_ParCSRMatrixCreate(comm, global_num_rows, global_num_cols, row_starts, col_starts, num_cols_offd, num_nonzeros_diag, num_nonzeros_offd); hypre_ParCSRMatrixInitialize(matrix); diag = hypre_ParCSRMatrixDiag(matrix); offd = hypre_ParCSRMatrixOffd(matrix); diag_data = hypre_CSRMatrixData(diag); diag_i = hypre_CSRMatrixI(diag); diag_j = hypre_CSRMatrixJ(diag); offd_i = hypre_CSRMatrixI(offd); if (num_nonzeros_offd) { offd_data = hypre_CSRMatrixData(offd); offd_j = hypre_CSRMatrixJ(offd); } first_row_index = hypre_ParCSRMatrixFirstRowIndex(matrix); first_col_diag = hypre_ParCSRMatrixFirstColDiag(matrix); last_col_diag = first_col_diag+num_cols-1; diag_cnt = 0; offd_cnt = 0; row_cnt = 0; for (i = 0; i < num_nonzeros_diag+num_nonzeros_offd; i++) { /* read values */ hypre_fscanf(file, "%d %d %le", &I, &J, &data); I = I-base_i-first_row_index; J -= base_j; if (I > row_cnt) { diag_i[I] = diag_cnt; offd_i[I] = offd_cnt; row_cnt++; } if (J < first_col_diag || J > last_col_diag) { offd_j[offd_cnt] = J; offd_data[offd_cnt++] = data; } else { diag_j[diag_cnt] = J - first_col_diag; diag_data[diag_cnt++] = data; } } diag_i[num_rows] = diag_cnt; offd_i[num_rows] = offd_cnt; fclose(file); /* generate col_map_offd */ if (num_nonzeros_offd) { aux_offd_j = hypre_CTAlloc(HYPRE_Int, num_nonzeros_offd); for (i=0; i < num_nonzeros_offd; i++) aux_offd_j[i] = offd_j[i]; hypre_qsort0(aux_offd_j,0,num_nonzeros_offd-1); col_map_offd = hypre_ParCSRMatrixColMapOffd(matrix); col_map_offd[0] = aux_offd_j[0]; offd_cnt = 0; for (i=1; i < num_nonzeros_offd; i++) { if (aux_offd_j[i] > col_map_offd[offd_cnt]) col_map_offd[++offd_cnt] = aux_offd_j[i]; } for (i=0; i < num_nonzeros_offd; i++) { offd_j[i] = hypre_BinarySearch(col_map_offd, offd_j[i], num_cols_offd); } hypre_TFree(aux_offd_j); } /* move diagonal element in first position in each row */ for (i=0; i < num_rows; i++) { i_col = diag_i[i]; for (j=i_col; j < diag_i[i+1]; j++) { if (diag_j[j] == i) { diag_j[j] = diag_j[i_col]; data = diag_data[j]; diag_data[j] = diag_data[i_col]; diag_data[i_col] = data; diag_j[i_col] = i; break; } } } *base_i_ptr = base_i; *base_j_ptr = base_j; *matrix_ptr = matrix; return hypre_error_flag; } /*-------------------------------------------------------------------------- * hypre_ParCSRMatrixGetLocalRange * returns the row numbers of the rows stored on this processor. * "End" is actually the row number of the last row on this processor. *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParCSRMatrixGetLocalRange( hypre_ParCSRMatrix *matrix, HYPRE_Int *row_start, HYPRE_Int *row_end, HYPRE_Int *col_start, HYPRE_Int *col_end ) { HYPRE_Int my_id; if (!matrix) { hypre_error_in_arg(1); return hypre_error_flag; } hypre_MPI_Comm_rank( hypre_ParCSRMatrixComm(matrix), &my_id ); #ifdef HYPRE_NO_GLOBAL_PARTITION *row_start = hypre_ParCSRMatrixFirstRowIndex(matrix); *row_end = hypre_ParCSRMatrixLastRowIndex(matrix); *col_start = hypre_ParCSRMatrixFirstColDiag(matrix); *col_end = hypre_ParCSRMatrixLastColDiag(matrix); #else *row_start = hypre_ParCSRMatrixRowStarts(matrix)[ my_id ]; *row_end = hypre_ParCSRMatrixRowStarts(matrix)[ my_id + 1 ]-1; *col_start = hypre_ParCSRMatrixColStarts(matrix)[ my_id ]; *col_end = hypre_ParCSRMatrixColStarts(matrix)[ my_id + 1 ]-1; #endif return hypre_error_flag; } /*-------------------------------------------------------------------------- * hypre_ParCSRMatrixGetRow * Returns global column indices and/or values for a given row in the global * matrix. Global row number is used, but the row must be stored locally or * an error is returned. This implementation copies from the two matrices that * store the local data, storing them in the hypre_ParCSRMatrix structure. * Only a single row can be accessed via this function at any one time; the * corresponding RestoreRow function must be called, to avoid bleeding memory, * and to be able to look at another row. * Either one of col_ind and values can be left null, and those values will * not be returned. * All indices are returned in 0-based indexing, no matter what is used under * the hood. EXCEPTION: currently this only works if the local CSR matrices * use 0-based indexing. * This code, semantics, implementation, etc., are all based on PETSc's hypre_MPI_AIJ * matrix code, adjusted for our data and software structures. * AJC 4/99. *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParCSRMatrixGetRow( hypre_ParCSRMatrix *mat, HYPRE_Int row, HYPRE_Int *size, HYPRE_Int **col_ind, HYPRE_Complex **values ) { HYPRE_Int my_id; HYPRE_Int row_start, row_end; hypre_CSRMatrix *Aa; hypre_CSRMatrix *Ba; if (!mat) { hypre_error_in_arg(1); return hypre_error_flag; } Aa = (hypre_CSRMatrix *) hypre_ParCSRMatrixDiag(mat); Ba = (hypre_CSRMatrix *) hypre_ParCSRMatrixOffd(mat); if (hypre_ParCSRMatrixGetrowactive(mat)) return(-1); hypre_MPI_Comm_rank( hypre_ParCSRMatrixComm(mat), &my_id ); hypre_ParCSRMatrixGetrowactive(mat) = 1; #ifdef HYPRE_NO_GLOBAL_PARTITION row_start = hypre_ParCSRMatrixFirstRowIndex(mat); row_end = hypre_ParCSRMatrixLastRowIndex(mat) + 1; #else row_end = hypre_ParCSRMatrixRowStarts(mat)[ my_id + 1 ]; row_start = hypre_ParCSRMatrixRowStarts(mat)[ my_id ]; #endif if (row < row_start || row >= row_end) return(-1); /* if buffer is not allocated and some information is requested, allocate buffer */ if (!hypre_ParCSRMatrixRowvalues(mat) && ( col_ind || values )) { /* allocate enough space to hold information from the longest row. */ HYPRE_Int max = 1,tmp; HYPRE_Int i; HYPRE_Int m = row_end-row_start; for ( i=0; i<m; i++ ) { tmp = hypre_CSRMatrixI(Aa)[i+1] - hypre_CSRMatrixI(Aa)[i] + hypre_CSRMatrixI(Ba)[i+1] - hypre_CSRMatrixI(Ba)[i]; if (max < tmp) { max = tmp; } } hypre_ParCSRMatrixRowvalues(mat) = (HYPRE_Complex *) hypre_CTAlloc ( HYPRE_Complex, max ); hypre_ParCSRMatrixRowindices(mat) = (HYPRE_Int *) hypre_CTAlloc ( HYPRE_Int, max ); } /* Copy from dual sequential matrices into buffer */ { HYPRE_Complex *vworkA, *vworkB, *v_p; HYPRE_Int i, *cworkA, *cworkB; HYPRE_Int cstart = hypre_ParCSRMatrixFirstColDiag(mat); HYPRE_Int nztot, nzA, nzB, lrow=row-row_start; HYPRE_Int *cmap, *idx_p; nzA = hypre_CSRMatrixI(Aa)[lrow+1]-hypre_CSRMatrixI(Aa)[lrow]; cworkA = &( hypre_CSRMatrixJ(Aa)[ hypre_CSRMatrixI(Aa)[lrow] ] ); vworkA = &( hypre_CSRMatrixData(Aa)[ hypre_CSRMatrixI(Aa)[lrow] ] ); nzB = hypre_CSRMatrixI(Ba)[lrow+1]-hypre_CSRMatrixI(Ba)[lrow]; cworkB = &( hypre_CSRMatrixJ(Ba)[ hypre_CSRMatrixI(Ba)[lrow] ] ); vworkB = &( hypre_CSRMatrixData(Ba)[ hypre_CSRMatrixI(Ba)[lrow] ] ); nztot = nzA + nzB; cmap = hypre_ParCSRMatrixColMapOffd(mat); if (values || col_ind) { if (nztot) { /* Sort by increasing column numbers, assuming A and B already sorted */ HYPRE_Int imark = -1; if (values) { *values = v_p = hypre_ParCSRMatrixRowvalues(mat); for ( i=0; i<nzB; i++ ) { if (cmap[cworkB[i]] < cstart) v_p[i] = vworkB[i]; else break; } imark = i; for ( i=0; i<nzA; i++ ) v_p[imark+i] = vworkA[i]; for ( i=imark; i<nzB; i++ ) v_p[nzA+i] = vworkB[i]; } if (col_ind) { *col_ind = idx_p = hypre_ParCSRMatrixRowindices(mat); if (imark > -1) { for ( i=0; i<imark; i++ ) { idx_p[i] = cmap[cworkB[i]]; } } else { for ( i=0; i<nzB; i++ ) { if (cmap[cworkB[i]] < cstart) idx_p[i] = cmap[cworkB[i]]; else break; } imark = i; } for ( i=0; i<nzA; i++ ) idx_p[imark+i] = cstart + cworkA[i]; for ( i=imark; i<nzB; i++ ) idx_p[nzA+i] = cmap[cworkB[i]]; } } else { if (col_ind) *col_ind = 0; if (values) *values = 0; } } *size = nztot; } /* End of copy */ return hypre_error_flag; } /*-------------------------------------------------------------------------- * hypre_ParCSRMatrixRestoreRow *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParCSRMatrixRestoreRow( hypre_ParCSRMatrix *matrix, HYPRE_Int row, HYPRE_Int *size, HYPRE_Int **col_ind, HYPRE_Complex **values ) { if (!hypre_ParCSRMatrixGetrowactive(matrix)) { hypre_error(HYPRE_ERROR_GENERIC); return hypre_error_flag; } hypre_ParCSRMatrixGetrowactive(matrix)=0; return hypre_error_flag; } /*-------------------------------------------------------------------------- * hypre_CSRMatrixToParCSRMatrix: * generates a ParCSRMatrix distributed across the processors in comm * from a CSRMatrix on proc 0 . * * This shouldn't be used with the HYPRE_NO_GLOBAL_PARTITON option * *--------------------------------------------------------------------------*/ hypre_ParCSRMatrix * hypre_CSRMatrixToParCSRMatrix( MPI_Comm comm, hypre_CSRMatrix *A, HYPRE_Int *row_starts, HYPRE_Int *col_starts ) { HYPRE_Int *global_data; HYPRE_Int global_size; HYPRE_Int global_num_rows; HYPRE_Int global_num_cols; HYPRE_Int *local_num_rows; HYPRE_Int num_procs, my_id; HYPRE_Int *local_num_nonzeros=NULL; HYPRE_Int num_nonzeros; HYPRE_Complex *a_data; HYPRE_Int *a_i; HYPRE_Int *a_j; hypre_CSRMatrix *local_A; hypre_MPI_Request *requests; hypre_MPI_Status *status, status0; hypre_MPI_Datatype *csr_matrix_datatypes; hypre_ParCSRMatrix *par_matrix; HYPRE_Int first_col_diag; HYPRE_Int last_col_diag; HYPRE_Int i, j, ind; hypre_MPI_Comm_rank(comm, &my_id); hypre_MPI_Comm_size(comm, &num_procs); global_data = hypre_CTAlloc(HYPRE_Int, 2*num_procs+6); if (my_id == 0) { global_size = 3; if (row_starts) { if (col_starts) { if (col_starts != row_starts) { /* contains code for what to expect, if 0: row_starts = col_starts, only row_starts given if 1: only row_starts given, col_starts = NULL if 2: both row_starts and col_starts given if 3: only col_starts given, row_starts = NULL */ global_data[3] = 2; global_size = 2*num_procs+6; for (i=0; i < num_procs+1; i++) global_data[i+4] = row_starts[i]; for (i=0; i < num_procs+1; i++) global_data[i+num_procs+5] = col_starts[i]; } else { global_data[3] = 0; global_size = num_procs+5; for (i=0; i < num_procs+1; i++) global_data[i+4] = row_starts[i]; } } else { global_data[3] = 1; global_size = num_procs+5; for (i=0; i < num_procs+1; i++) global_data[i+4] = row_starts[i]; } } else { if (col_starts) { global_data[3] = 3; global_size = num_procs+5; for (i=0; i < num_procs+1; i++) global_data[i+4] = col_starts[i]; } } global_data[0] = hypre_CSRMatrixNumRows(A); global_data[1] = hypre_CSRMatrixNumCols(A); global_data[2] = global_size; a_data = hypre_CSRMatrixData(A); a_i = hypre_CSRMatrixI(A); a_j = hypre_CSRMatrixJ(A); } hypre_MPI_Bcast(global_data,3,HYPRE_MPI_INT,0,comm); global_num_rows = global_data[0]; global_num_cols = global_data[1]; global_size = global_data[2]; if (global_size > 3) { hypre_MPI_Bcast(&global_data[3],global_size-3,HYPRE_MPI_INT,0,comm); if (my_id > 0) { if (global_data[3] < 3) { row_starts = hypre_CTAlloc(HYPRE_Int, num_procs+1); for (i=0; i< num_procs+1; i++) { row_starts[i] = global_data[i+4]; } if (global_data[3] == 0) col_starts = row_starts; if (global_data[3] == 2) { col_starts = hypre_CTAlloc(HYPRE_Int, num_procs+1); for (i=0; i < num_procs+1; i++) { col_starts[i] = global_data[i+num_procs+5]; } } } else { col_starts = hypre_CTAlloc(HYPRE_Int, num_procs+1); for (i=0; i< num_procs+1; i++) { col_starts[i] = global_data[i+4]; } } } } hypre_TFree(global_data); local_num_rows = hypre_CTAlloc(HYPRE_Int, num_procs); csr_matrix_datatypes = hypre_CTAlloc(hypre_MPI_Datatype, num_procs); par_matrix = hypre_ParCSRMatrixCreate( comm, global_num_rows, global_num_cols,row_starts,col_starts,0,0,0); row_starts = hypre_ParCSRMatrixRowStarts(par_matrix); col_starts = hypre_ParCSRMatrixColStarts(par_matrix); for (i=0; i < num_procs; i++) local_num_rows[i] = row_starts[i+1] - row_starts[i]; if (my_id == 0) { local_num_nonzeros = hypre_CTAlloc(HYPRE_Int, num_procs); for (i=0; i < num_procs-1; i++) local_num_nonzeros[i] = a_i[row_starts[i+1]] - a_i[row_starts[i]]; local_num_nonzeros[num_procs-1] = a_i[global_num_rows] - a_i[row_starts[num_procs-1]]; } hypre_MPI_Scatter(local_num_nonzeros,1,HYPRE_MPI_INT,&num_nonzeros,1, HYPRE_MPI_INT,0,comm); if (my_id == 0) num_nonzeros = local_num_nonzeros[0]; local_A = hypre_CSRMatrixCreate(local_num_rows[my_id], global_num_cols, num_nonzeros); if (my_id == 0) { requests = hypre_CTAlloc (hypre_MPI_Request, num_procs-1); status = hypre_CTAlloc(hypre_MPI_Status, num_procs-1); j=0; for (i=1; i < num_procs; i++) { ind = a_i[row_starts[i]]; hypre_BuildCSRMatrixMPIDataType(local_num_nonzeros[i], local_num_rows[i], &a_data[ind], &a_i[row_starts[i]], &a_j[ind], &csr_matrix_datatypes[i]); hypre_MPI_Isend(hypre_MPI_BOTTOM, 1, csr_matrix_datatypes[i], i, 0, comm, &requests[j++]); hypre_MPI_Type_free(&csr_matrix_datatypes[i]); } hypre_CSRMatrixData(local_A) = a_data; hypre_CSRMatrixI(local_A) = a_i; hypre_CSRMatrixJ(local_A) = a_j; hypre_CSRMatrixOwnsData(local_A) = 0; hypre_MPI_Waitall(num_procs-1,requests,status); hypre_TFree(requests); hypre_TFree(status); hypre_TFree(local_num_nonzeros); } else { hypre_CSRMatrixInitialize(local_A); hypre_BuildCSRMatrixMPIDataType(num_nonzeros, local_num_rows[my_id], hypre_CSRMatrixData(local_A), hypre_CSRMatrixI(local_A), hypre_CSRMatrixJ(local_A), csr_matrix_datatypes); hypre_MPI_Recv(hypre_MPI_BOTTOM,1,csr_matrix_datatypes[0],0,0,comm,&status0); hypre_MPI_Type_free(csr_matrix_datatypes); } first_col_diag = col_starts[my_id]; last_col_diag = col_starts[my_id+1]-1; GenerateDiagAndOffd(local_A, par_matrix, first_col_diag, last_col_diag); /* set pointers back to NULL before destroying */ if (my_id == 0) { hypre_CSRMatrixData(local_A) = NULL; hypre_CSRMatrixI(local_A) = NULL; hypre_CSRMatrixJ(local_A) = NULL; } hypre_CSRMatrixDestroy(local_A); hypre_TFree(local_num_rows); hypre_TFree(csr_matrix_datatypes); return par_matrix; } HYPRE_Int GenerateDiagAndOffd(hypre_CSRMatrix *A, hypre_ParCSRMatrix *matrix, HYPRE_Int first_col_diag, HYPRE_Int last_col_diag) { HYPRE_Int i, j; HYPRE_Int jo, jd; HYPRE_Int num_rows = hypre_CSRMatrixNumRows(A); HYPRE_Int num_cols = hypre_CSRMatrixNumCols(A); HYPRE_Complex *a_data = hypre_CSRMatrixData(A); HYPRE_Int *a_i = hypre_CSRMatrixI(A); HYPRE_Int *a_j = hypre_CSRMatrixJ(A); hypre_CSRMatrix *diag = hypre_ParCSRMatrixDiag(matrix); hypre_CSRMatrix *offd = hypre_ParCSRMatrixOffd(matrix); HYPRE_Int *col_map_offd; HYPRE_Complex *diag_data, *offd_data; HYPRE_Int *diag_i, *offd_i; HYPRE_Int *diag_j, *offd_j; HYPRE_Int *marker; HYPRE_Int num_cols_diag, num_cols_offd; HYPRE_Int first_elmt = a_i[0]; HYPRE_Int num_nonzeros = a_i[num_rows]-first_elmt; HYPRE_Int counter; num_cols_diag = last_col_diag - first_col_diag +1; num_cols_offd = 0; if (num_cols - num_cols_diag) { hypre_CSRMatrixInitialize(diag); diag_i = hypre_CSRMatrixI(diag); hypre_CSRMatrixInitialize(offd); offd_i = hypre_CSRMatrixI(offd); marker = hypre_CTAlloc(HYPRE_Int,num_cols); for (i=0; i < num_cols; i++) marker[i] = 0; jo = 0; jd = 0; for (i=0; i < num_rows; i++) { offd_i[i] = jo; diag_i[i] = jd; for (j=a_i[i]-first_elmt; j < a_i[i+1]-first_elmt; j++) if (a_j[j] < first_col_diag || a_j[j] > last_col_diag) { if (!marker[a_j[j]]) { marker[a_j[j]] = 1; num_cols_offd++; } jo++; } else { jd++; } } offd_i[num_rows] = jo; diag_i[num_rows] = jd; hypre_ParCSRMatrixColMapOffd(matrix) = hypre_CTAlloc(HYPRE_Int,num_cols_offd); col_map_offd = hypre_ParCSRMatrixColMapOffd(matrix); counter = 0; for (i=0; i < num_cols; i++) if (marker[i]) { col_map_offd[counter] = i; marker[i] = counter; counter++; } hypre_CSRMatrixNumNonzeros(diag) = jd; hypre_CSRMatrixInitialize(diag); diag_data = hypre_CSRMatrixData(diag); diag_j = hypre_CSRMatrixJ(diag); hypre_CSRMatrixNumNonzeros(offd) = jo; hypre_CSRMatrixNumCols(offd) = num_cols_offd; hypre_CSRMatrixInitialize(offd); offd_data = hypre_CSRMatrixData(offd); offd_j = hypre_CSRMatrixJ(offd); jo = 0; jd = 0; for (i=0; i < num_rows; i++) { for (j=a_i[i]-first_elmt; j < a_i[i+1]-first_elmt; j++) if (a_j[j] < first_col_diag || a_j[j] > last_col_diag) { offd_data[jo] = a_data[j]; offd_j[jo++] = marker[a_j[j]]; } else { diag_data[jd] = a_data[j]; diag_j[jd++] = a_j[j]-first_col_diag; } } hypre_TFree(marker); } else { hypre_CSRMatrixNumNonzeros(diag) = num_nonzeros; hypre_CSRMatrixInitialize(diag); diag_data = hypre_CSRMatrixData(diag); diag_i = hypre_CSRMatrixI(diag); diag_j = hypre_CSRMatrixJ(diag); for (i=0; i < num_nonzeros; i++) { diag_data[i] = a_data[i]; diag_j[i] = a_j[i]; } offd_i = hypre_CTAlloc(HYPRE_Int, num_rows+1); for (i=0; i < num_rows+1; i++) { diag_i[i] = a_i[i]; offd_i[i] = 0; } hypre_CSRMatrixNumCols(offd) = 0; hypre_CSRMatrixI(offd) = offd_i; } return hypre_error_flag; } hypre_CSRMatrix * hypre_MergeDiagAndOffd(hypre_ParCSRMatrix *par_matrix) { hypre_CSRMatrix *diag = hypre_ParCSRMatrixDiag(par_matrix); hypre_CSRMatrix *offd = hypre_ParCSRMatrixOffd(par_matrix); hypre_CSRMatrix *matrix; HYPRE_Int num_cols = hypre_ParCSRMatrixGlobalNumCols(par_matrix); HYPRE_Int first_col_diag = hypre_ParCSRMatrixFirstColDiag(par_matrix); HYPRE_Int *col_map_offd = hypre_ParCSRMatrixColMapOffd(par_matrix); HYPRE_Int num_rows = hypre_CSRMatrixNumRows(diag); HYPRE_Int *diag_i = hypre_CSRMatrixI(diag); HYPRE_Int *diag_j = hypre_CSRMatrixJ(diag); HYPRE_Complex *diag_data = hypre_CSRMatrixData(diag); HYPRE_Int *offd_i = hypre_CSRMatrixI(offd); HYPRE_Int *offd_j = hypre_CSRMatrixJ(offd); HYPRE_Complex *offd_data = hypre_CSRMatrixData(offd); HYPRE_Int *matrix_i; HYPRE_Int *matrix_j; HYPRE_Complex *matrix_data; HYPRE_Int num_nonzeros, i, j; HYPRE_Int count; HYPRE_Int size, rest, num_threads, ii; num_nonzeros = diag_i[num_rows] + offd_i[num_rows]; matrix = hypre_CSRMatrixCreate(num_rows,num_cols,num_nonzeros); hypre_CSRMatrixInitialize(matrix); matrix_i = hypre_CSRMatrixI(matrix); matrix_j = hypre_CSRMatrixJ(matrix); matrix_data = hypre_CSRMatrixData(matrix); num_threads = hypre_NumThreads(); size = num_rows/num_threads; rest = num_rows - size*num_threads; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(ii, i, j, count) HYPRE_SMP_SCHEDULE #endif for (ii=0; ii < num_threads; ii++) { HYPRE_Int ns, ne; if (ii < rest) { ns = ii*size+ii; ne = (ii+1)*size+ii+1; } else { ns = ii*size+rest; ne = (ii+1)*size+rest; } count = diag_i[ns]+offd_i[ns];; for (i=ns; i < ne; i++) { matrix_i[i] = count; for (j=diag_i[i]; j < diag_i[i+1]; j++) { matrix_data[count] = diag_data[j]; matrix_j[count++] = diag_j[j]+first_col_diag; } for (j=offd_i[i]; j < offd_i[i+1]; j++) { matrix_data[count] = offd_data[j]; matrix_j[count++] = col_map_offd[offd_j[j]]; } } } /* end parallel region */ matrix_i[num_rows] = num_nonzeros; return matrix; } /*-------------------------------------------------------------------------- * hypre_ParCSRMatrixToCSRMatrixAll: * generates a CSRMatrix from a ParCSRMatrix on all processors that have * parts of the ParCSRMatrix *--------------------------------------------------------------------------*/ hypre_CSRMatrix * hypre_ParCSRMatrixToCSRMatrixAll(hypre_ParCSRMatrix *par_matrix) { MPI_Comm comm = hypre_ParCSRMatrixComm(par_matrix); hypre_CSRMatrix *matrix; hypre_CSRMatrix *local_matrix; HYPRE_Int num_rows = hypre_ParCSRMatrixGlobalNumRows(par_matrix); HYPRE_Int num_cols = hypre_ParCSRMatrixGlobalNumCols(par_matrix); #ifndef HYPRE_NO_GLOBAL_PARTITION HYPRE_Int *row_starts = hypre_ParCSRMatrixRowStarts(par_matrix); #endif HYPRE_Int *matrix_i; HYPRE_Int *matrix_j; HYPRE_Complex *matrix_data; HYPRE_Int *local_matrix_i; HYPRE_Int *local_matrix_j; HYPRE_Complex *local_matrix_data; HYPRE_Int i, j; HYPRE_Int local_num_rows; HYPRE_Int local_num_nonzeros; HYPRE_Int num_nonzeros; HYPRE_Int num_data; HYPRE_Int num_requests; HYPRE_Int vec_len, offset; HYPRE_Int start_index; HYPRE_Int proc_id; HYPRE_Int num_procs, my_id; HYPRE_Int num_types; HYPRE_Int *used_procs; hypre_MPI_Request *requests; hypre_MPI_Status *status; #ifdef HYPRE_NO_GLOBAL_PARTITION HYPRE_Int *new_vec_starts; HYPRE_Int num_contacts; HYPRE_Int contact_proc_list[1]; HYPRE_Int contact_send_buf[1]; HYPRE_Int contact_send_buf_starts[2]; HYPRE_Int max_response_size; HYPRE_Int *response_recv_buf=NULL; HYPRE_Int *response_recv_buf_starts = NULL; hypre_DataExchangeResponse response_obj; hypre_ProcListElements send_proc_obj; HYPRE_Int *send_info = NULL; hypre_MPI_Status status1; HYPRE_Int count, tag1 = 11112, tag2 = 22223, tag3 = 33334; HYPRE_Int start; #endif hypre_MPI_Comm_size(comm, &num_procs); hypre_MPI_Comm_rank(comm, &my_id); #ifdef HYPRE_NO_GLOBAL_PARTITION local_num_rows = hypre_ParCSRMatrixLastRowIndex(par_matrix) - hypre_ParCSRMatrixFirstRowIndex(par_matrix) + 1; local_matrix = hypre_MergeDiagAndOffd(par_matrix); /* creates matrix */ local_matrix_i = hypre_CSRMatrixI(local_matrix); local_matrix_j = hypre_CSRMatrixJ(local_matrix); local_matrix_data = hypre_CSRMatrixData(local_matrix); /* determine procs that have vector data and store their ids in used_procs */ /* we need to do an exchange data for this. If I own row then I will contact processor 0 with the endpoint of my local range */ if (local_num_rows > 0) { num_contacts = 1; contact_proc_list[0] = 0; contact_send_buf[0] = hypre_ParCSRMatrixLastRowIndex(par_matrix); contact_send_buf_starts[0] = 0; contact_send_buf_starts[1] = 1; } else { num_contacts = 0; contact_send_buf_starts[0] = 0; contact_send_buf_starts[1] = 0; } /*build the response object*/ /*send_proc_obj will be for saving info from contacts */ send_proc_obj.length = 0; send_proc_obj.storage_length = 10; send_proc_obj.id = hypre_CTAlloc(HYPRE_Int, send_proc_obj.storage_length); send_proc_obj.vec_starts = hypre_CTAlloc(HYPRE_Int, send_proc_obj.storage_length + 1); send_proc_obj.vec_starts[0] = 0; send_proc_obj.element_storage_length = 10; send_proc_obj.elements = hypre_CTAlloc(HYPRE_Int, send_proc_obj.element_storage_length); max_response_size = 0; /* each response is null */ response_obj.fill_response = hypre_FillResponseParToCSRMatrix; response_obj.data1 = NULL; response_obj.data2 = &send_proc_obj; /*this is where we keep info from contacts*/ hypre_DataExchangeList(num_contacts, contact_proc_list, contact_send_buf, contact_send_buf_starts, sizeof(HYPRE_Int), sizeof(HYPRE_Int), &response_obj, max_response_size, 1, comm, (void**) &response_recv_buf, &response_recv_buf_starts); /* now processor 0 should have a list of ranges for processors that have rows - these are in send_proc_obj - it needs to create the new list of processors and also an array of vec starts - and send to those who own row*/ if (my_id) { if (local_num_rows) { /* look for a message from processor 0 */ hypre_MPI_Probe(0, tag1, comm, &status1); hypre_MPI_Get_count(&status1, HYPRE_MPI_INT, &count); send_info = hypre_CTAlloc(HYPRE_Int, count); hypre_MPI_Recv(send_info, count, HYPRE_MPI_INT, 0, tag1, comm, &status1); /* now unpack */ num_types = send_info[0]; used_procs = hypre_CTAlloc(HYPRE_Int, num_types); new_vec_starts = hypre_CTAlloc(HYPRE_Int, num_types+1); for (i=1; i<= num_types; i++) { used_procs[i-1] = send_info[i]; } for (i=num_types+1; i< count; i++) { new_vec_starts[i-num_types-1] = send_info[i] ; } } else /* clean up and exit */ { hypre_TFree(send_proc_obj.vec_starts); hypre_TFree(send_proc_obj.id); hypre_TFree(send_proc_obj.elements); if(response_recv_buf) hypre_TFree(response_recv_buf); if(response_recv_buf_starts) hypre_TFree(response_recv_buf_starts); if (hypre_CSRMatrixOwnsData(local_matrix)) hypre_CSRMatrixDestroy(local_matrix); else hypre_TFree(local_matrix); return NULL; } } else /* my_id ==0 */ { num_types = send_proc_obj.length; used_procs = hypre_CTAlloc(HYPRE_Int, num_types); new_vec_starts = hypre_CTAlloc(HYPRE_Int, num_types+1); new_vec_starts[0] = 0; for (i=0; i< num_types; i++) { used_procs[i] = send_proc_obj.id[i]; new_vec_starts[i+1] = send_proc_obj.elements[i]+1; } hypre_qsort0(used_procs, 0, num_types-1); hypre_qsort0(new_vec_starts, 0, num_types); /*now we need to put into an array to send */ count = 2*num_types+2; send_info = hypre_CTAlloc(HYPRE_Int, count); send_info[0] = num_types; for (i=1; i<= num_types; i++) { send_info[i] = used_procs[i-1]; } for (i=num_types+1; i< count; i++) { send_info[i] = new_vec_starts[i-num_types-1]; } requests = hypre_CTAlloc(hypre_MPI_Request, num_types); status = hypre_CTAlloc(hypre_MPI_Status, num_types); /* don't send to myself - these are sorted so my id would be first*/ start = 0; if (num_types && used_procs[0] == 0) { start = 1; } for (i=start; i < num_types; i++) { hypre_MPI_Isend(send_info, count, HYPRE_MPI_INT, used_procs[i], tag1, comm, &requests[i-start]); } hypre_MPI_Waitall(num_types-start, requests, status); hypre_TFree(status); hypre_TFree(requests); } /* clean up */ hypre_TFree(send_proc_obj.vec_starts); hypre_TFree(send_proc_obj.id); hypre_TFree(send_proc_obj.elements); hypre_TFree(send_info); if(response_recv_buf) hypre_TFree(response_recv_buf); if(response_recv_buf_starts) hypre_TFree(response_recv_buf_starts); /* now proc 0 can exit if it has no rows */ if (!local_num_rows) { if (hypre_CSRMatrixOwnsData(local_matrix)) hypre_CSRMatrixDestroy(local_matrix); else hypre_TFree(local_matrix); hypre_TFree(new_vec_starts); hypre_TFree(used_procs); return NULL; } /* everyone left has rows and knows: new_vec_starts, num_types, and used_procs */ /* this matrix should be rather small */ matrix_i = hypre_CTAlloc(HYPRE_Int, num_rows+1); num_requests = 4*num_types; requests = hypre_CTAlloc(hypre_MPI_Request, num_requests); status = hypre_CTAlloc(hypre_MPI_Status, num_requests); /* exchange contents of local_matrix_i - here we are sending to ourself also*/ j = 0; for (i = 0; i < num_types; i++) { proc_id = used_procs[i]; vec_len = new_vec_starts[i+1] - new_vec_starts[i]; hypre_MPI_Irecv(&matrix_i[new_vec_starts[i]+1], vec_len, HYPRE_MPI_INT, proc_id, tag2, comm, &requests[j++]); } for (i = 0; i < num_types; i++) { proc_id = used_procs[i]; hypre_MPI_Isend(&local_matrix_i[1], local_num_rows, HYPRE_MPI_INT, proc_id, tag2, comm, &requests[j++]); } hypre_MPI_Waitall(j, requests, status); /* generate matrix_i from received data */ /* global numbering?*/ offset = matrix_i[new_vec_starts[1]]; for (i=1; i < num_types; i++) { for (j = new_vec_starts[i]; j < new_vec_starts[i+1]; j++) matrix_i[j+1] += offset; offset = matrix_i[new_vec_starts[i+1]]; } num_nonzeros = matrix_i[num_rows]; matrix = hypre_CSRMatrixCreate(num_rows, num_cols, num_nonzeros); hypre_CSRMatrixI(matrix) = matrix_i; hypre_CSRMatrixInitialize(matrix); matrix_j = hypre_CSRMatrixJ(matrix); matrix_data = hypre_CSRMatrixData(matrix); /* generate datatypes for further data exchange and exchange remaining data, i.e. column info and actual data */ j = 0; for (i = 0; i < num_types; i++) { proc_id = used_procs[i]; start_index = matrix_i[new_vec_starts[i]]; num_data = matrix_i[new_vec_starts[i+1]] - start_index; hypre_MPI_Irecv(&matrix_data[start_index], num_data, HYPRE_MPI_COMPLEX, used_procs[i], tag1, comm, &requests[j++]); hypre_MPI_Irecv(&matrix_j[start_index], num_data, HYPRE_MPI_INT, used_procs[i], tag3, comm, &requests[j++]); } local_num_nonzeros = local_matrix_i[local_num_rows]; for (i=0; i < num_types; i++) { hypre_MPI_Isend(local_matrix_data, local_num_nonzeros, HYPRE_MPI_COMPLEX, used_procs[i], tag1, comm, &requests[j++]); hypre_MPI_Isend(local_matrix_j, local_num_nonzeros, HYPRE_MPI_INT, used_procs[i], tag3, comm, &requests[j++]); } hypre_MPI_Waitall(num_requests, requests, status); hypre_TFree(new_vec_starts); #else local_num_rows = row_starts[my_id+1] - row_starts[my_id]; /* if my_id contains no data, return NULL */ if (!local_num_rows) return NULL; local_matrix = hypre_MergeDiagAndOffd(par_matrix); local_matrix_i = hypre_CSRMatrixI(local_matrix); local_matrix_j = hypre_CSRMatrixJ(local_matrix); local_matrix_data = hypre_CSRMatrixData(local_matrix); matrix_i = hypre_CTAlloc(HYPRE_Int, num_rows+1); /* determine procs that have vector data and store their ids in used_procs */ num_types = 0; for (i=0; i < num_procs; i++) if (row_starts[i+1]-row_starts[i] && i-my_id) num_types++; num_requests = 4*num_types; used_procs = hypre_CTAlloc(HYPRE_Int, num_types); j = 0; for (i=0; i < num_procs; i++) if (row_starts[i+1]-row_starts[i] && i-my_id) used_procs[j++] = i; requests = hypre_CTAlloc(hypre_MPI_Request, num_requests); status = hypre_CTAlloc(hypre_MPI_Status, num_requests); /* data_type = hypre_CTAlloc(hypre_MPI_Datatype, num_types+1); */ /* exchange contents of local_matrix_i */ j = 0; for (i = 0; i < num_types; i++) { proc_id = used_procs[i]; vec_len = row_starts[proc_id+1] - row_starts[proc_id]; hypre_MPI_Irecv(&matrix_i[row_starts[proc_id]+1], vec_len, HYPRE_MPI_INT, proc_id, 0, comm, &requests[j++]); } for (i = 0; i < num_types; i++) { proc_id = used_procs[i]; hypre_MPI_Isend(&local_matrix_i[1], local_num_rows, HYPRE_MPI_INT, proc_id, 0, comm, &requests[j++]); } vec_len = row_starts[my_id+1] - row_starts[my_id]; for (i=1; i <= vec_len; i++) matrix_i[row_starts[my_id]+i] = local_matrix_i[i]; hypre_MPI_Waitall(j, requests, status); /* generate matrix_i from received data */ offset = matrix_i[row_starts[1]]; for (i=1; i < num_procs; i++) { for (j = row_starts[i]; j < row_starts[i+1]; j++) matrix_i[j+1] += offset; offset = matrix_i[row_starts[i+1]]; } num_nonzeros = matrix_i[num_rows]; matrix = hypre_CSRMatrixCreate(num_rows, num_cols, num_nonzeros); hypre_CSRMatrixI(matrix) = matrix_i; hypre_CSRMatrixInitialize(matrix); matrix_j = hypre_CSRMatrixJ(matrix); matrix_data = hypre_CSRMatrixData(matrix); /* generate datatypes for further data exchange and exchange remaining data, i.e. column info and actual data */ j = 0; for (i = 0; i < num_types; i++) { proc_id = used_procs[i]; start_index = matrix_i[row_starts[proc_id]]; num_data = matrix_i[row_starts[proc_id+1]] - start_index; hypre_MPI_Irecv(&matrix_data[start_index], num_data, HYPRE_MPI_COMPLEX, used_procs[i], 0, comm, &requests[j++]); hypre_MPI_Irecv(&matrix_j[start_index], num_data, HYPRE_MPI_INT, used_procs[i], 0, comm, &requests[j++]); } local_num_nonzeros = local_matrix_i[local_num_rows]; for (i=0; i < num_types; i++) { hypre_MPI_Isend(local_matrix_data, local_num_nonzeros, HYPRE_MPI_COMPLEX, used_procs[i], 0, comm, &requests[j++]); hypre_MPI_Isend(local_matrix_j, local_num_nonzeros, HYPRE_MPI_INT, used_procs[i], 0, comm, &requests[j++]); } start_index = matrix_i[row_starts[my_id]]; for (i=0; i < local_num_nonzeros; i++) { matrix_j[start_index+i] = local_matrix_j[i]; matrix_data[start_index+i] = local_matrix_data[i]; } hypre_MPI_Waitall(num_requests, requests, status); start_index = matrix_i[row_starts[my_id]]; for (i=0; i < local_num_nonzeros; i++) { matrix_j[start_index+i] = local_matrix_j[i]; matrix_data[start_index+i] = local_matrix_data[i]; } hypre_MPI_Waitall(num_requests, requests, status); #endif if (hypre_CSRMatrixOwnsData(local_matrix)) hypre_CSRMatrixDestroy(local_matrix); else hypre_TFree(local_matrix); if (num_requests) { hypre_TFree(requests); hypre_TFree(status); hypre_TFree(used_procs); } return matrix; } /*-------------------------------------------------------------------------- * hypre_ParCSRMatrixCopy, * copies B to A, * if copy_data = 0, only the structure of A is copied to B * the routine does not check whether the dimensions of A and B are compatible *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParCSRMatrixCopy( hypre_ParCSRMatrix *A, hypre_ParCSRMatrix *B, HYPRE_Int copy_data ) { hypre_CSRMatrix *A_diag; hypre_CSRMatrix *A_offd; HYPRE_Int *col_map_offd_A; hypre_CSRMatrix *B_diag; hypre_CSRMatrix *B_offd; HYPRE_Int *col_map_offd_B; HYPRE_Int num_cols_offd; HYPRE_Int i; if (!A) { hypre_error_in_arg(1); return hypre_error_flag; } if (!B) { hypre_error_in_arg(1); return hypre_error_flag; } A_diag = hypre_ParCSRMatrixDiag(A); A_offd = hypre_ParCSRMatrixOffd(A); col_map_offd_A = hypre_ParCSRMatrixColMapOffd(A); B_diag = hypre_ParCSRMatrixDiag(B); B_offd = hypre_ParCSRMatrixOffd(B); col_map_offd_B = hypre_ParCSRMatrixColMapOffd(B); num_cols_offd = hypre_CSRMatrixNumCols(A_offd); hypre_CSRMatrixCopy(A_diag, B_diag, copy_data); hypre_CSRMatrixCopy(A_offd, B_offd, copy_data); if (num_cols_offd && col_map_offd_B == NULL) { col_map_offd_B = hypre_CTAlloc(HYPRE_Int,num_cols_offd); hypre_ParCSRMatrixColMapOffd(B) = col_map_offd_B; } for (i = 0; i < num_cols_offd; i++) col_map_offd_B[i] = col_map_offd_A[i]; return hypre_error_flag; } /*-------------------------------------------------------------------- * hypre_FillResponseParToCSRMatrix * Fill response function for determining the send processors * data exchange *--------------------------------------------------------------------*/ HYPRE_Int hypre_FillResponseParToCSRMatrix( void *p_recv_contact_buf, HYPRE_Int contact_size, HYPRE_Int contact_proc, void *ro, MPI_Comm comm, void **p_send_response_buf, HYPRE_Int *response_message_size ) { HYPRE_Int myid; HYPRE_Int i, index, count, elength; HYPRE_Int *recv_contact_buf = (HYPRE_Int * ) p_recv_contact_buf; hypre_DataExchangeResponse *response_obj = (hypre_DataExchangeResponse*)ro; hypre_ProcListElements *send_proc_obj = (hypre_ProcListElements*)response_obj->data2; hypre_MPI_Comm_rank(comm, &myid ); /*check to see if we need to allocate more space in send_proc_obj for ids*/ if (send_proc_obj->length == send_proc_obj->storage_length) { send_proc_obj->storage_length +=10; /*add space for 10 more processors*/ send_proc_obj->id = hypre_TReAlloc(send_proc_obj->id,HYPRE_Int, send_proc_obj->storage_length); send_proc_obj->vec_starts = hypre_TReAlloc(send_proc_obj->vec_starts,HYPRE_Int, send_proc_obj->storage_length + 1); } /*initialize*/ count = send_proc_obj->length; index = send_proc_obj->vec_starts[count]; /*this is the number of elements*/ /*send proc*/ send_proc_obj->id[count] = contact_proc; /*do we need more storage for the elements?*/ if (send_proc_obj->element_storage_length < index + contact_size) { elength = hypre_max(contact_size, 10); elength += index; send_proc_obj->elements = hypre_TReAlloc(send_proc_obj->elements, HYPRE_Int, elength); send_proc_obj->element_storage_length = elength; } /*populate send_proc_obj*/ for (i=0; i< contact_size; i++) { send_proc_obj->elements[index++] = recv_contact_buf[i]; } send_proc_obj->vec_starts[count+1] = index; send_proc_obj->length++; /*output - no message to return (confirmation) */ *response_message_size = 0; return hypre_error_flag; } /*-------------------------------------------------------------------------- * hypre_ParCSRMatrixCompleteClone * Creates and returns a new copy of the argument, A. * Data is not copied, only structural information is reproduced. * The following variables are not copied because they will be constructed * later if needed: CommPkg, CommPkgT, rowindices, rowvalues *--------------------------------------------------------------------------*/ /* This differs from Hypre_ParCSRMatrixClone in parcsr_ls/par_gsmg.c, because that Clone function makes a matrix with different global parameters. */ hypre_ParCSRMatrix * hypre_ParCSRMatrixCompleteClone( hypre_ParCSRMatrix * A ) { hypre_ParCSRMatrix * B = hypre_CTAlloc(hypre_ParCSRMatrix, 1); HYPRE_Int i, ncols_offd; hypre_ParCSRMatrixComm( B ) = hypre_ParCSRMatrixComm( A ); hypre_ParCSRMatrixGlobalNumRows( B ) = hypre_ParCSRMatrixGlobalNumRows( A ); hypre_ParCSRMatrixGlobalNumCols( B ) = hypre_ParCSRMatrixGlobalNumCols( A ); hypre_ParCSRMatrixFirstRowIndex( B ) = hypre_ParCSRMatrixFirstRowIndex( A ); hypre_ParCSRMatrixFirstColDiag( B ) = hypre_ParCSRMatrixFirstColDiag( A ); hypre_ParCSRMatrixLastRowIndex( B ) = hypre_ParCSRMatrixLastRowIndex( A ); hypre_ParCSRMatrixLastColDiag( B ) = hypre_ParCSRMatrixLastColDiag( A ); hypre_ParCSRMatrixDiag( B ) = hypre_CSRMatrixClone( hypre_ParCSRMatrixDiag( A ) ); hypre_ParCSRMatrixOffd( B ) = hypre_CSRMatrixClone( hypre_ParCSRMatrixOffd( A ) ); hypre_ParCSRMatrixRowStarts( B ) = hypre_ParCSRMatrixRowStarts( A ); hypre_ParCSRMatrixColStarts( B ) = hypre_ParCSRMatrixColStarts( A ); /* note that B doesn't own row_starts & col_starts; this isn't a full copy */ hypre_ParCSRMatrixCommPkg( B ) = NULL; hypre_ParCSRMatrixCommPkgT( B ) = NULL; hypre_ParCSRMatrixOwnsData( B ) = 1; hypre_ParCSRMatrixOwnsRowStarts( B ) = 0; hypre_ParCSRMatrixOwnsColStarts( B ) = 0; hypre_ParCSRMatrixNumNonzeros( B ) = hypre_ParCSRMatrixNumNonzeros( A ); hypre_ParCSRMatrixDNumNonzeros( B ) = hypre_ParCSRMatrixNumNonzeros( A ); hypre_ParCSRMatrixRowindices( B ) = NULL; hypre_ParCSRMatrixRowvalues( B ) = NULL; hypre_ParCSRMatrixGetrowactive( B ) = 0; ncols_offd = hypre_CSRMatrixNumCols( hypre_ParCSRMatrixOffd( B ) ); hypre_ParCSRMatrixColMapOffd( B ) = hypre_CTAlloc( HYPRE_Int, ncols_offd ); for ( i=0; i<ncols_offd; ++i ) hypre_ParCSRMatrixColMapOffd( B )[i] = hypre_ParCSRMatrixColMapOffd( A )[i]; return B; } /*-------------------------------------------------------------------------- * hypre_ParCSRMatrixUnion * Creates and returns a new matrix whose elements are the union of A and B. * Data is not copied, only structural information is created. * A and B must have the same communicator, numbers and distributions of rows * and columns (they can differ in which row-column pairs are nonzero, thus * in which columns are in a offd block) *--------------------------------------------------------------------------*/ hypre_ParCSRMatrix * hypre_ParCSRMatrixUnion( hypre_ParCSRMatrix * A, hypre_ParCSRMatrix * B ) { hypre_ParCSRMatrix * C; HYPRE_Int * col_map_offd_C = NULL; HYPRE_Int num_procs, my_id, p; MPI_Comm comm = hypre_ParCSRMatrixComm( A ); hypre_MPI_Comm_rank(comm,&my_id); hypre_MPI_Comm_size(comm,&num_procs); C = hypre_CTAlloc( hypre_ParCSRMatrix, 1 ); hypre_ParCSRMatrixComm( C ) = hypre_ParCSRMatrixComm( A ); hypre_ParCSRMatrixGlobalNumRows( C ) = hypre_ParCSRMatrixGlobalNumRows( A ); hypre_ParCSRMatrixGlobalNumCols( C ) = hypre_ParCSRMatrixGlobalNumCols( A ); hypre_ParCSRMatrixFirstRowIndex( C ) = hypre_ParCSRMatrixFirstRowIndex( A ); hypre_assert( hypre_ParCSRMatrixFirstRowIndex( B ) == hypre_ParCSRMatrixFirstRowIndex( A ) ); hypre_ParCSRMatrixRowStarts( C ) = hypre_ParCSRMatrixRowStarts( A ); hypre_ParCSRMatrixOwnsRowStarts( C ) = 0; hypre_ParCSRMatrixColStarts( C ) = hypre_ParCSRMatrixColStarts( A ); hypre_ParCSRMatrixOwnsColStarts( C ) = 0; for ( p=0; p<=num_procs; ++p ) hypre_assert( hypre_ParCSRMatrixColStarts(A) == hypre_ParCSRMatrixColStarts(B) ); hypre_ParCSRMatrixFirstColDiag( C ) = hypre_ParCSRMatrixFirstColDiag( A ); hypre_ParCSRMatrixLastRowIndex( C ) = hypre_ParCSRMatrixLastRowIndex( A ); hypre_ParCSRMatrixLastColDiag( C ) = hypre_ParCSRMatrixLastColDiag( A ); hypre_ParCSRMatrixDiag( C ) = hypre_CSRMatrixUnion( hypre_ParCSRMatrixDiag(A), hypre_ParCSRMatrixDiag(B), 0, 0, 0 ); hypre_ParCSRMatrixOffd( C ) = hypre_CSRMatrixUnion( hypre_ParCSRMatrixOffd(A), hypre_ParCSRMatrixOffd(B), hypre_ParCSRMatrixColMapOffd(A), hypre_ParCSRMatrixColMapOffd(B), &col_map_offd_C ); hypre_ParCSRMatrixColMapOffd( C ) = col_map_offd_C; hypre_ParCSRMatrixCommPkg( C ) = NULL; hypre_ParCSRMatrixCommPkgT( C ) = NULL; hypre_ParCSRMatrixOwnsData( C ) = 1; /* SetNumNonzeros, SetDNumNonzeros are global, need hypre_MPI_Allreduce. I suspect, but don't know, that other parts of hypre do not assume that the correct values have been set. hypre_ParCSRMatrixSetNumNonzeros( C ); hypre_ParCSRMatrixSetDNumNonzeros( C );*/ hypre_ParCSRMatrixNumNonzeros( C ) = 0; hypre_ParCSRMatrixDNumNonzeros( C ) = 0.0; hypre_ParCSRMatrixRowindices( C ) = NULL; hypre_ParCSRMatrixRowvalues( C ) = NULL; hypre_ParCSRMatrixGetrowactive( C ) = 0; return C; }
73,331
32.93429
109
c
AMG
AMG-master/parcsr_mv/par_csr_matrix.h
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /****************************************************************************** * * Header info for Parallel CSR Matrix data structures * * Note: this matrix currently uses 0-based indexing. * *****************************************************************************/ #ifndef hypre_PAR_CSR_MATRIX_HEADER #define hypre_PAR_CSR_MATRIX_HEADER /*-------------------------------------------------------------------------- * Parallel CSR Matrix *--------------------------------------------------------------------------*/ #ifndef HYPRE_PAR_CSR_MATRIX_STRUCT #define HYPRE_PAR_CSR_MATRIX_STRUCT #endif typedef struct hypre_ParCSRMatrix_struct { MPI_Comm comm; HYPRE_Int global_num_rows; HYPRE_Int global_num_cols; HYPRE_Int first_row_index; HYPRE_Int first_col_diag; /* need to know entire local range in case row_starts and col_starts are null (i.e., bgl) AHB 6/05*/ HYPRE_Int last_row_index; HYPRE_Int last_col_diag; hypre_CSRMatrix *diag; hypre_CSRMatrix *offd; hypre_CSRMatrix *diagT, *offdT; /* JSP: transposed matrices are created lazily and optional */ HYPRE_Int *col_map_offd; /* maps columns of offd to global columns */ HYPRE_Int *row_starts; /* array of length num_procs+1, row_starts[i] contains the global number of the first row on proc i, first_row_index = row_starts[my_id], row_starts[num_procs] = global_num_rows */ HYPRE_Int *col_starts; /* array of length num_procs+1, col_starts[i] contains the global number of the first column of diag on proc i, first_col_diag = col_starts[my_id], col_starts[num_procs] = global_num_cols */ hypre_ParCSRCommPkg *comm_pkg; hypre_ParCSRCommPkg *comm_pkgT; /* Does the ParCSRMatrix create/destroy `diag', `offd', `col_map_offd'? */ HYPRE_Int owns_data; /* Does the ParCSRMatrix create/destroy `row_starts', `col_starts'? */ HYPRE_Int owns_row_starts; HYPRE_Int owns_col_starts; HYPRE_Int num_nonzeros; HYPRE_Real d_num_nonzeros; /* Buffers used by GetRow to hold row currently being accessed. AJC, 4/99 */ HYPRE_Int *rowindices; HYPRE_Complex *rowvalues; HYPRE_Int getrowactive; hypre_IJAssumedPart *assumed_partition; /* only populated if no_global_partition option is used (compile-time option)*/ } hypre_ParCSRMatrix; /*-------------------------------------------------------------------------- * Accessor functions for the Parallel CSR Matrix structure *--------------------------------------------------------------------------*/ #define hypre_ParCSRMatrixComm(matrix) ((matrix) -> comm) #define hypre_ParCSRMatrixGlobalNumRows(matrix) ((matrix) -> global_num_rows) #define hypre_ParCSRMatrixGlobalNumCols(matrix) ((matrix) -> global_num_cols) #define hypre_ParCSRMatrixFirstRowIndex(matrix) ((matrix) -> first_row_index) #define hypre_ParCSRMatrixFirstColDiag(matrix) ((matrix) -> first_col_diag) #define hypre_ParCSRMatrixLastRowIndex(matrix) ((matrix) -> last_row_index) #define hypre_ParCSRMatrixLastColDiag(matrix) ((matrix) -> last_col_diag) #define hypre_ParCSRMatrixDiag(matrix) ((matrix) -> diag) #define hypre_ParCSRMatrixOffd(matrix) ((matrix) -> offd) #define hypre_ParCSRMatrixDiagT(matrix) ((matrix) -> diagT) #define hypre_ParCSRMatrixOffdT(matrix) ((matrix) -> offdT) #define hypre_ParCSRMatrixColMapOffd(matrix) ((matrix) -> col_map_offd) #define hypre_ParCSRMatrixRowStarts(matrix) ((matrix) -> row_starts) #define hypre_ParCSRMatrixColStarts(matrix) ((matrix) -> col_starts) #define hypre_ParCSRMatrixCommPkg(matrix) ((matrix) -> comm_pkg) #define hypre_ParCSRMatrixCommPkgT(matrix) ((matrix) -> comm_pkgT) #define hypre_ParCSRMatrixOwnsData(matrix) ((matrix) -> owns_data) #define hypre_ParCSRMatrixOwnsRowStarts(matrix) ((matrix) -> owns_row_starts) #define hypre_ParCSRMatrixOwnsColStarts(matrix) ((matrix) -> owns_col_starts) #define hypre_ParCSRMatrixNumRows(matrix) \ hypre_CSRMatrixNumRows(hypre_ParCSRMatrixDiag(matrix)) #define hypre_ParCSRMatrixNumCols(matrix) \ hypre_CSRMatrixNumCols(hypre_ParCSRMatrixDiag(matrix)) #define hypre_ParCSRMatrixNumNonzeros(matrix) ((matrix) -> num_nonzeros) #define hypre_ParCSRMatrixDNumNonzeros(matrix) ((matrix) -> d_num_nonzeros) #define hypre_ParCSRMatrixRowindices(matrix) ((matrix) -> rowindices) #define hypre_ParCSRMatrixRowvalues(matrix) ((matrix) -> rowvalues) #define hypre_ParCSRMatrixGetrowactive(matrix) ((matrix) -> getrowactive) #define hypre_ParCSRMatrixAssumedPartition(matrix) ((matrix) -> assumed_partition) /*-------------------------------------------------------------------------- * Parallel CSR Boolean Matrix *--------------------------------------------------------------------------*/ typedef struct { MPI_Comm comm; HYPRE_Int global_num_rows; HYPRE_Int global_num_cols; HYPRE_Int first_row_index; HYPRE_Int first_col_diag; HYPRE_Int last_row_index; HYPRE_Int last_col_diag; hypre_CSRBooleanMatrix *diag; hypre_CSRBooleanMatrix *offd; HYPRE_Int *col_map_offd; HYPRE_Int *row_starts; HYPRE_Int *col_starts; hypre_ParCSRCommPkg *comm_pkg; hypre_ParCSRCommPkg *comm_pkgT; HYPRE_Int owns_data; HYPRE_Int owns_row_starts; HYPRE_Int owns_col_starts; HYPRE_Int num_nonzeros; HYPRE_Int *rowindices; HYPRE_Int getrowactive; } hypre_ParCSRBooleanMatrix; /*-------------------------------------------------------------------------- * Accessor functions for the Parallel CSR Boolean Matrix structure *--------------------------------------------------------------------------*/ #define hypre_ParCSRBooleanMatrix_Get_Comm(matrix) ((matrix)->comm) #define hypre_ParCSRBooleanMatrix_Get_GlobalNRows(matrix) ((matrix)->global_num_rows) #define hypre_ParCSRBooleanMatrix_Get_GlobalNCols(matrix) ((matrix)->global_num_cols) #define hypre_ParCSRBooleanMatrix_Get_StartRow(matrix) ((matrix)->first_row_index) #define hypre_ParCSRBooleanMatrix_Get_FirstRowIndex(matrix) ((matrix)->first_row_index) #define hypre_ParCSRBooleanMatrix_Get_FirstColDiag(matrix) ((matrix)->first_col_diag) #define hypre_ParCSRBooleanMatrix_Get_LastRowIndex(matrix) ((matrix)->last_row_index) #define hypre_ParCSRBooleanMatrix_Get_LastColDiag(matrix) ((matrix)->last_col_diag) #define hypre_ParCSRBooleanMatrix_Get_Diag(matrix) ((matrix)->diag) #define hypre_ParCSRBooleanMatrix_Get_Offd(matrix) ((matrix)->offd) #define hypre_ParCSRBooleanMatrix_Get_ColMapOffd(matrix) ((matrix)->col_map_offd) #define hypre_ParCSRBooleanMatrix_Get_RowStarts(matrix) ((matrix)->row_starts) #define hypre_ParCSRBooleanMatrix_Get_ColStarts(matrix) ((matrix)->col_starts) #define hypre_ParCSRBooleanMatrix_Get_CommPkg(matrix) ((matrix)->comm_pkg) #define hypre_ParCSRBooleanMatrix_Get_CommPkgT(matrix) ((matrix)->comm_pkgT) #define hypre_ParCSRBooleanMatrix_Get_OwnsData(matrix) ((matrix)->owns_data) #define hypre_ParCSRBooleanMatrix_Get_OwnsRowStarts(matrix) ((matrix)->owns_row_starts) #define hypre_ParCSRBooleanMatrix_Get_OwnsColStarts(matrix) ((matrix)->owns_col_starts) #define hypre_ParCSRBooleanMatrix_Get_NRows(matrix) ((matrix->diag->num_rows)) #define hypre_ParCSRBooleanMatrix_Get_NCols(matrix) ((matrix->diag->num_cols)) #define hypre_ParCSRBooleanMatrix_Get_NNZ(matrix) ((matrix)->num_nonzeros) #define hypre_ParCSRBooleanMatrix_Get_Rowindices(matrix) ((matrix)->rowindices) #define hypre_ParCSRBooleanMatrix_Get_Getrowactive(matrix) ((matrix)->getrowactive) #endif
9,164
49.357143
87
h
AMG
AMG-master/parcsr_mv/par_csr_matvec.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /****************************************************************************** * * Matvec functions for hypre_CSRMatrix class. * *****************************************************************************/ #include "_hypre_parcsr_mv.h" #include <assert.h> /*-------------------------------------------------------------------------- * hypre_ParCSRMatrixMatvec *--------------------------------------------------------------------------*/ // y = alpha*A*x + beta*b HYPRE_Int hypre_ParCSRMatrixMatvecOutOfPlace( HYPRE_Complex alpha, hypre_ParCSRMatrix *A, hypre_ParVector *x, HYPRE_Complex beta, hypre_ParVector *b, hypre_ParVector *y ) { hypre_ParCSRCommHandle **comm_handle; hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A); hypre_CSRMatrix *diag = hypre_ParCSRMatrixDiag(A); hypre_CSRMatrix *offd = hypre_ParCSRMatrixOffd(A); hypre_Vector *x_local = hypre_ParVectorLocalVector(x); hypre_Vector *b_local = hypre_ParVectorLocalVector(b); hypre_Vector *y_local = hypre_ParVectorLocalVector(y); HYPRE_Int num_rows = hypre_ParCSRMatrixGlobalNumRows(A); HYPRE_Int num_cols = hypre_ParCSRMatrixGlobalNumCols(A); hypre_Vector *x_tmp; HYPRE_Int x_size = hypre_ParVectorGlobalSize(x); HYPRE_Int b_size = hypre_ParVectorGlobalSize(b); HYPRE_Int y_size = hypre_ParVectorGlobalSize(y); HYPRE_Int num_vectors = hypre_VectorNumVectors(x_local); HYPRE_Int num_cols_offd = hypre_CSRMatrixNumCols(offd); HYPRE_Int ierr = 0; HYPRE_Int num_sends, i, j, jv, index, start; HYPRE_Int vecstride = hypre_VectorVectorStride( x_local ); HYPRE_Int idxstride = hypre_VectorIndexStride( x_local ); HYPRE_Complex *x_tmp_data, **x_buf_data; HYPRE_Complex *x_local_data = hypre_VectorData(x_local); /*--------------------------------------------------------------------- * Check for size compatibility. ParMatvec returns ierr = 11 if * length of X doesn't equal the number of columns of A, * ierr = 12 if the length of Y doesn't equal the number of rows * of A, and ierr = 13 if both are true. * * Because temporary vectors are often used in ParMatvec, none of * these conditions terminates processing, and the ierr flag * is informational only. *--------------------------------------------------------------------*/ hypre_assert( idxstride>0 ); if (num_cols != x_size) ierr = 11; if (num_rows != y_size || num_rows != b_size) ierr = 12; if (num_cols != x_size && (num_rows != y_size || num_rows != b_size)) ierr = 13; hypre_assert( hypre_VectorNumVectors(b_local)==num_vectors ); hypre_assert( hypre_VectorNumVectors(y_local)==num_vectors ); if ( num_vectors==1 ) x_tmp = hypre_SeqVectorCreate( num_cols_offd ); else { hypre_assert( num_vectors>1 ); x_tmp = hypre_SeqMultiVectorCreate( num_cols_offd, num_vectors ); } /*--------------------------------------------------------------------- * If there exists no CommPkg for A, a CommPkg is generated using * equally load balanced partitionings *--------------------------------------------------------------------*/ if (!comm_pkg) { hypre_MatvecCommPkgCreate(A); comm_pkg = hypre_ParCSRMatrixCommPkg(A); } #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_PACK_UNPACK] -= hypre_MPI_Wtime(); #endif HYPRE_Int use_persistent_comm = 0; #ifdef HYPRE_USING_PERSISTENT_COMM use_persistent_comm = num_vectors == 1; // JSP TODO: we can use persistent communication for multi-vectors, // but then we need different communication handles for different // num_vectors. hypre_ParCSRPersistentCommHandle *persistent_comm_handle; #endif if ( use_persistent_comm ) { #ifdef HYPRE_USING_PERSISTENT_COMM persistent_comm_handle = hypre_ParCSRCommPkgGetPersistentCommHandle(1, comm_pkg); HYPRE_Int num_recvs = hypre_ParCSRCommPkgNumRecvs(comm_pkg); hypre_assert(num_cols_offd == hypre_ParCSRCommPkgRecvVecStart(comm_pkg, num_recvs)); hypre_VectorData(x_tmp) = (HYPRE_Complex *)persistent_comm_handle->recv_data; hypre_SeqVectorSetDataOwner(x_tmp, 0); #endif } else { comm_handle = hypre_CTAlloc(hypre_ParCSRCommHandle*,num_vectors); } hypre_SeqVectorInitialize(x_tmp); x_tmp_data = hypre_VectorData(x_tmp); num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); if (!use_persistent_comm) { x_buf_data = hypre_CTAlloc( HYPRE_Complex*, num_vectors ); for ( jv=0; jv<num_vectors; ++jv ) x_buf_data[jv] = hypre_CTAlloc(HYPRE_Complex, hypre_ParCSRCommPkgSendMapStart (comm_pkg, num_sends)); } if ( num_vectors==1 ) { HYPRE_Int begin = hypre_ParCSRCommPkgSendMapStart(comm_pkg, 0); HYPRE_Int end = hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for HYPRE_SMP_SCHEDULE #endif for (i = begin; i < end; i++) { #ifdef HYPRE_USING_PERSISTENT_COMM ((HYPRE_Complex *)persistent_comm_handle->send_data)[i - begin] #else x_buf_data[0][i - begin] #endif = x_local_data[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,i)]; } } else for ( jv=0; jv<num_vectors; ++jv ) { index = 0; for (i = 0; i < num_sends; i++) { start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j = start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++) x_buf_data[jv][index++] = x_local_data[ jv*vecstride + idxstride*hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j) ]; } } hypre_assert( idxstride==1 ); /* ... The assert is because the following loop only works for 'column' storage of a multivector. This needs to be fixed to work more generally, at least for 'row' storage. This in turn, means either change CommPkg so num_sends is no.zones*no.vectors (not no.zones) or, less dangerously, put a stride in the logic of CommHandleCreate (stride either from a new arg or a new variable inside CommPkg). Or put the num_vector iteration inside CommHandleCreate (perhaps a new multivector variant of it). */ #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_PACK_UNPACK] += hypre_MPI_Wtime(); hypre_profile_times[HYPRE_TIMER_ID_HALO_EXCHANGE] -= hypre_MPI_Wtime(); #endif if (use_persistent_comm) { #ifdef HYPRE_USING_PERSISTENT_COMM hypre_ParCSRPersistentCommHandleStart(persistent_comm_handle); #endif } else { for ( jv=0; jv<num_vectors; ++jv ) { comm_handle[jv] = hypre_ParCSRCommHandleCreate ( 1, comm_pkg, x_buf_data[jv], &(x_tmp_data[jv*num_cols_offd]) ); } } #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_HALO_EXCHANGE] += hypre_MPI_Wtime(); #endif hypre_CSRMatrixMatvecOutOfPlace( alpha, diag, x_local, beta, b_local, y_local, 0); #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_HALO_EXCHANGE] -= hypre_MPI_Wtime(); #endif if (use_persistent_comm) { #ifdef HYPRE_USING_PERSISTENT_COMM hypre_ParCSRPersistentCommHandleWait(persistent_comm_handle); #endif } else { for ( jv=0; jv<num_vectors; ++jv ) { hypre_ParCSRCommHandleDestroy(comm_handle[jv]); comm_handle[jv] = NULL; } hypre_TFree(comm_handle); } #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_HALO_EXCHANGE] += hypre_MPI_Wtime(); #endif if (num_cols_offd) hypre_CSRMatrixMatvec( alpha, offd, x_tmp, 1.0, y_local); #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_PACK_UNPACK] -= hypre_MPI_Wtime(); #endif hypre_SeqVectorDestroy(x_tmp); x_tmp = NULL; if (!use_persistent_comm) { for ( jv=0; jv<num_vectors; ++jv ) hypre_TFree(x_buf_data[jv]); hypre_TFree(x_buf_data); } #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_PACK_UNPACK] += hypre_MPI_Wtime(); #endif return ierr; } HYPRE_Int hypre_ParCSRMatrixMatvec( HYPRE_Complex alpha, hypre_ParCSRMatrix *A, hypre_ParVector *x, HYPRE_Complex beta, hypre_ParVector *y ) { return hypre_ParCSRMatrixMatvecOutOfPlace(alpha, A, x, beta, y, y); } /*-------------------------------------------------------------------------- * hypre_ParCSRMatrixMatvecT * * Performs y <- alpha * A^T * x + beta * y * *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParCSRMatrixMatvecT( HYPRE_Complex alpha, hypre_ParCSRMatrix *A, hypre_ParVector *x, HYPRE_Complex beta, hypre_ParVector *y ) { hypre_ParCSRCommHandle **comm_handle; hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A); hypre_CSRMatrix *diag = hypre_ParCSRMatrixDiag(A); hypre_CSRMatrix *offd = hypre_ParCSRMatrixOffd(A); hypre_Vector *x_local = hypre_ParVectorLocalVector(x); hypre_Vector *y_local = hypre_ParVectorLocalVector(y); hypre_Vector *y_tmp; HYPRE_Int vecstride = hypre_VectorVectorStride( y_local ); HYPRE_Int idxstride = hypre_VectorIndexStride( y_local ); HYPRE_Complex *y_tmp_data, **y_buf_data; HYPRE_Complex *y_local_data = hypre_VectorData(y_local); HYPRE_Int num_rows = hypre_ParCSRMatrixGlobalNumRows(A); HYPRE_Int num_cols = hypre_ParCSRMatrixGlobalNumCols(A); HYPRE_Int num_cols_offd = hypre_CSRMatrixNumCols(offd); HYPRE_Int x_size = hypre_ParVectorGlobalSize(x); HYPRE_Int y_size = hypre_ParVectorGlobalSize(y); HYPRE_Int num_vectors = hypre_VectorNumVectors(y_local); HYPRE_Int i, j, jv, index, start, num_sends; HYPRE_Int ierr = 0; /*--------------------------------------------------------------------- * Check for size compatibility. MatvecT returns ierr = 1 if * length of X doesn't equal the number of rows of A, * ierr = 2 if the length of Y doesn't equal the number of * columns of A, and ierr = 3 if both are true. * * Because temporary vectors are often used in MatvecT, none of * these conditions terminates processing, and the ierr flag * is informational only. *--------------------------------------------------------------------*/ if (num_rows != x_size) ierr = 1; if (num_cols != y_size) ierr = 2; if (num_rows != x_size && num_cols != y_size) ierr = 3; /*----------------------------------------------------------------------- *-----------------------------------------------------------------------*/ if ( num_vectors==1 ) { y_tmp = hypre_SeqVectorCreate(num_cols_offd); } else { y_tmp = hypre_SeqMultiVectorCreate(num_cols_offd,num_vectors); } /*--------------------------------------------------------------------- * If there exists no CommPkg for A, a CommPkg is generated using * equally load balanced partitionings *--------------------------------------------------------------------*/ if (!comm_pkg) { hypre_MatvecCommPkgCreate(A); comm_pkg = hypre_ParCSRMatrixCommPkg(A); } #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_PACK_UNPACK] -= hypre_MPI_Wtime(); #endif HYPRE_Int use_persistent_comm = 0; #ifdef HYPRE_USING_PERSISTENT_COMM use_persistent_comm = num_vectors == 1; // JSP TODO: we can use persistent communication for multi-vectors, // but then we need different communication handles for different // num_vectors. hypre_ParCSRPersistentCommHandle *persistent_comm_handle; #endif if (use_persistent_comm) { #ifdef HYPRE_USING_PERSISTENT_COMM // JSP TODO: we should be also able to use persistent communication for multiple vectors persistent_comm_handle = hypre_ParCSRCommPkgGetPersistentCommHandle(2, comm_pkg); HYPRE_Int num_recvs = hypre_ParCSRCommPkgNumRecvs(comm_pkg); hypre_assert(num_cols_offd == hypre_ParCSRCommPkgRecvVecStart(comm_pkg, num_recvs)); hypre_VectorData(y_tmp) = (HYPRE_Complex *)persistent_comm_handle->send_data; hypre_SeqVectorSetDataOwner(y_tmp, 0); #endif } else { comm_handle = hypre_CTAlloc(hypre_ParCSRCommHandle*,num_vectors); } hypre_SeqVectorInitialize(y_tmp); num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); if (!use_persistent_comm) { y_buf_data = hypre_CTAlloc( HYPRE_Complex*, num_vectors ); for ( jv=0; jv<num_vectors; ++jv ) y_buf_data[jv] = hypre_CTAlloc(HYPRE_Complex, hypre_ParCSRCommPkgSendMapStart (comm_pkg, num_sends)); } y_tmp_data = hypre_VectorData(y_tmp); y_local_data = hypre_VectorData(y_local); hypre_assert( idxstride==1 ); /* only 'column' storage of multivectors * implemented so far */ #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_PACK_UNPACK] += hypre_MPI_Wtime(); #endif if (num_cols_offd) { if (A->offdT) { // offdT is optional. Used only if it's present. hypre_CSRMatrixMatvec(alpha, A->offdT, x_local, 0.0, y_tmp); } else { hypre_CSRMatrixMatvecT(alpha, offd, x_local, 0.0, y_tmp); } } #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_HALO_EXCHANGE] -= hypre_MPI_Wtime(); #endif if (use_persistent_comm) { #ifdef HYPRE_USING_PERSISTENT_COMM hypre_ParCSRPersistentCommHandleStart(persistent_comm_handle); #endif } else { for ( jv=0; jv<num_vectors; ++jv ) { /* this is where we assume multivectors are 'column' storage */ comm_handle[jv] = hypre_ParCSRCommHandleCreate ( 2, comm_pkg, &(y_tmp_data[jv*num_cols_offd]), y_buf_data[jv] ); } } #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_HALO_EXCHANGE] += hypre_MPI_Wtime(); #endif if (A->diagT) { // diagT is optional. Used only if it's present. hypre_CSRMatrixMatvec(alpha, A->diagT, x_local, beta, y_local); } else { hypre_CSRMatrixMatvecT(alpha, diag, x_local, beta, y_local); } #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_HALO_EXCHANGE] -= hypre_MPI_Wtime(); #endif if (use_persistent_comm) { #ifdef HYPRE_USING_PERSISTENT_COMM hypre_ParCSRPersistentCommHandleWait(persistent_comm_handle); #endif } else { for ( jv=0; jv<num_vectors; ++jv ) { hypre_ParCSRCommHandleDestroy(comm_handle[jv]); comm_handle[jv] = NULL; } hypre_TFree(comm_handle); } #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_HALO_EXCHANGE] += hypre_MPI_Wtime(); hypre_profile_times[HYPRE_TIMER_ID_PACK_UNPACK] -= hypre_MPI_Wtime(); #endif if ( num_vectors==1 ) { index = 0; for (i = 0; i < num_sends; i++) { start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j = start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++) y_local_data[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)] #ifdef HYPRE_USING_PERSISTENT_COMM += ((HYPRE_Complex *)persistent_comm_handle->recv_data)[index++]; #else += y_buf_data[0][index++]; #endif } } else for ( jv=0; jv<num_vectors; ++jv ) { index = 0; for (i = 0; i < num_sends; i++) { start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j = start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++) y_local_data[ jv*vecstride + idxstride*hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j) ] += y_buf_data[jv][index++]; } } hypre_SeqVectorDestroy(y_tmp); y_tmp = NULL; if (!use_persistent_comm) { for ( jv=0; jv<num_vectors; ++jv ) hypre_TFree(y_buf_data[jv]); hypre_TFree(y_buf_data); } #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_PACK_UNPACK] += hypre_MPI_Wtime(); #endif return ierr; } /*-------------------------------------------------------------------------- * hypre_ParCSRMatrixMatvec_FF *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParCSRMatrixMatvec_FF( HYPRE_Complex alpha, hypre_ParCSRMatrix *A, hypre_ParVector *x, HYPRE_Complex beta, hypre_ParVector *y, HYPRE_Int *CF_marker, HYPRE_Int fpt ) { MPI_Comm comm = hypre_ParCSRMatrixComm(A); hypre_ParCSRCommHandle *comm_handle; hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A); hypre_CSRMatrix *diag = hypre_ParCSRMatrixDiag(A); hypre_CSRMatrix *offd = hypre_ParCSRMatrixOffd(A); hypre_Vector *x_local = hypre_ParVectorLocalVector(x); hypre_Vector *y_local = hypre_ParVectorLocalVector(y); HYPRE_Int num_rows = hypre_ParCSRMatrixGlobalNumRows(A); HYPRE_Int num_cols = hypre_ParCSRMatrixGlobalNumCols(A); hypre_Vector *x_tmp; HYPRE_Int x_size = hypre_ParVectorGlobalSize(x); HYPRE_Int y_size = hypre_ParVectorGlobalSize(y); HYPRE_Int num_cols_offd = hypre_CSRMatrixNumCols(offd); HYPRE_Int ierr = 0; HYPRE_Int num_sends, i, j, index, start, num_procs; HYPRE_Int *int_buf_data = NULL; HYPRE_Int *CF_marker_offd = NULL; HYPRE_Complex *x_tmp_data = NULL; HYPRE_Complex *x_buf_data = NULL; HYPRE_Complex *x_local_data = hypre_VectorData(x_local); /*--------------------------------------------------------------------- * Check for size compatibility. ParMatvec returns ierr = 11 if * length of X doesn't equal the number of columns of A, * ierr = 12 if the length of Y doesn't equal the number of rows * of A, and ierr = 13 if both are true. * * Because temporary vectors are often used in ParMatvec, none of * these conditions terminates processing, and the ierr flag * is informational only. *--------------------------------------------------------------------*/ hypre_MPI_Comm_size(comm,&num_procs); if (num_cols != x_size) ierr = 11; if (num_rows != y_size) ierr = 12; if (num_cols != x_size && num_rows != y_size) ierr = 13; if (num_procs > 1) { if (num_cols_offd) { x_tmp = hypre_SeqVectorCreate( num_cols_offd ); hypre_SeqVectorInitialize(x_tmp); x_tmp_data = hypre_VectorData(x_tmp); } /*--------------------------------------------------------------------- * If there exists no CommPkg for A, a CommPkg is generated using * equally load balanced partitionings *--------------------------------------------------------------------*/ if (!comm_pkg) { hypre_MatvecCommPkgCreate(A); comm_pkg = hypre_ParCSRMatrixCommPkg(A); } num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); if (num_sends) x_buf_data = hypre_CTAlloc(HYPRE_Complex, hypre_ParCSRCommPkgSendMapStart (comm_pkg, num_sends)); index = 0; for (i = 0; i < num_sends; i++) { start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j = start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++) x_buf_data[index++] = x_local_data[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)]; } comm_handle = hypre_ParCSRCommHandleCreate ( 1, comm_pkg, x_buf_data, x_tmp_data ); } hypre_CSRMatrixMatvec_FF( alpha, diag, x_local, beta, y_local, CF_marker, CF_marker, fpt); if (num_procs > 1) { hypre_ParCSRCommHandleDestroy(comm_handle); comm_handle = NULL; if (num_sends) int_buf_data = hypre_CTAlloc(HYPRE_Int, hypre_ParCSRCommPkgSendMapStart (comm_pkg, num_sends)); if (num_cols_offd) CF_marker_offd = hypre_CTAlloc(HYPRE_Int, num_cols_offd); index = 0; for (i = 0; i < num_sends; i++) { start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j = start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++) int_buf_data[index++] = CF_marker[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)]; } comm_handle = hypre_ParCSRCommHandleCreate(11,comm_pkg,int_buf_data,CF_marker_offd ); hypre_ParCSRCommHandleDestroy(comm_handle); comm_handle = NULL; if (num_cols_offd) hypre_CSRMatrixMatvec_FF( alpha, offd, x_tmp, 1.0, y_local, CF_marker, CF_marker_offd, fpt); hypre_SeqVectorDestroy(x_tmp); x_tmp = NULL; hypre_TFree(x_buf_data); hypre_TFree(int_buf_data); hypre_TFree(CF_marker_offd); } return ierr; }
22,782
34.992101
94
c
AMG
AMG-master/parcsr_mv/par_vector.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /****************************************************************************** * * Member functions for hypre_Vector class. * *****************************************************************************/ #include "_hypre_parcsr_mv.h" #include <assert.h> #ifdef HYPRE_NO_GLOBAL_PARTITION HYPRE_Int hypre_FillResponseParToVectorAll(void*, HYPRE_Int, HYPRE_Int, void*, MPI_Comm, void**, HYPRE_Int*); #endif /*-------------------------------------------------------------------------- * hypre_ParVectorCreate *--------------------------------------------------------------------------*/ /* If create is called for HYPRE_NO_GLOBAL_PARTITION and partitioning is NOT null, then it is assumed that it is array of length 2 containing the start row of the calling processor followed by the start row of the next processor - AHB 6/05 */ hypre_ParVector * hypre_ParVectorCreate( MPI_Comm comm, HYPRE_Int global_size, HYPRE_Int *partitioning ) { hypre_ParVector *vector; HYPRE_Int num_procs, my_id; if (global_size < 0) { hypre_error_in_arg(2); return NULL; } vector = hypre_CTAlloc(hypre_ParVector, 1); hypre_MPI_Comm_rank(comm,&my_id); if (!partitioning) { hypre_MPI_Comm_size(comm,&num_procs); #ifdef HYPRE_NO_GLOBAL_PARTITION hypre_GenerateLocalPartitioning(global_size, num_procs, my_id, &partitioning); #else hypre_GeneratePartitioning(global_size, num_procs, &partitioning); #endif } hypre_ParVectorAssumedPartition(vector) = NULL; hypre_ParVectorComm(vector) = comm; hypre_ParVectorGlobalSize(vector) = global_size; #ifdef HYPRE_NO_GLOBAL_PARTITION hypre_ParVectorFirstIndex(vector) = partitioning[0]; hypre_ParVectorLastIndex(vector) = partitioning[1]-1; hypre_ParVectorPartitioning(vector) = partitioning; hypre_ParVectorLocalVector(vector) = hypre_SeqVectorCreate(partitioning[1]-partitioning[0]); #else hypre_ParVectorFirstIndex(vector) = partitioning[my_id]; hypre_ParVectorLastIndex(vector) = partitioning[my_id+1] -1; hypre_ParVectorPartitioning(vector) = partitioning; hypre_ParVectorLocalVector(vector) = hypre_SeqVectorCreate(partitioning[my_id+1]-partitioning[my_id]); #endif /* set defaults */ hypre_ParVectorOwnsData(vector) = 1; hypre_ParVectorOwnsPartitioning(vector) = 1; hypre_ParVectorActualLocalSize(vector) = 0; return vector; } /*-------------------------------------------------------------------------- * hypre_ParMultiVectorCreate *--------------------------------------------------------------------------*/ hypre_ParVector * hypre_ParMultiVectorCreate( MPI_Comm comm, HYPRE_Int global_size, HYPRE_Int *partitioning, HYPRE_Int num_vectors ) { /* note that global_size is the global length of a single vector */ hypre_ParVector * vector = hypre_ParVectorCreate( comm, global_size, partitioning ); hypre_ParVectorNumVectors(vector) = num_vectors; return vector; } /*-------------------------------------------------------------------------- * hypre_ParVectorDestroy *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParVectorDestroy( hypre_ParVector *vector ) { if (vector) { if ( hypre_ParVectorOwnsData(vector) ) { hypre_SeqVectorDestroy(hypre_ParVectorLocalVector(vector)); } if ( hypre_ParVectorOwnsPartitioning(vector) ) { hypre_TFree(hypre_ParVectorPartitioning(vector)); } if (hypre_ParVectorAssumedPartition(vector)) { hypre_AssumedPartitionDestroy(hypre_ParVectorAssumedPartition(vector)); } hypre_TFree(vector); } return hypre_error_flag; } /*-------------------------------------------------------------------------- * hypre_ParVectorInitialize *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParVectorInitialize( hypre_ParVector *vector ) { if (!vector) { hypre_error_in_arg(1); return hypre_error_flag; } hypre_SeqVectorInitialize(hypre_ParVectorLocalVector(vector)); hypre_ParVectorActualLocalSize(vector) = hypre_VectorSize(hypre_ParVectorLocalVector(vector)); return hypre_error_flag; } /*-------------------------------------------------------------------------- * hypre_ParVectorSetDataOwner *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParVectorSetDataOwner( hypre_ParVector *vector, HYPRE_Int owns_data ) { if (!vector) { hypre_error_in_arg(1); return hypre_error_flag; } hypre_ParVectorOwnsData(vector) = owns_data; return hypre_error_flag; } /*-------------------------------------------------------------------------- * hypre_ParVectorSetPartitioningOwner *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParVectorSetPartitioningOwner( hypre_ParVector *vector, HYPRE_Int owns_partitioning ) { if (!vector) { hypre_error_in_arg(1); return hypre_error_flag; } hypre_ParVectorOwnsPartitioning(vector) = owns_partitioning; return hypre_error_flag; } /*-------------------------------------------------------------------------- * hypre_ParVectorSetNumVectors * call before calling hypre_ParVectorInitialize * probably this will do more harm than good, use hypre_ParMultiVectorCreate *--------------------------------------------------------------------------*/ #if 0 HYPRE_Int hypre_ParVectorSetNumVectors( hypre_ParVector *vector, HYPRE_Int num_vectors ) { HYPRE_Int ierr=0; hypre_Vector *local_vector = hypre_ParVectorLocalVector(v); hypre_SeqVectorSetNumVectors( local_vector, num_vectors ); return ierr; } #endif /*-------------------------------------------------------------------------- * hypre_ParVectorRead *--------------------------------------------------------------------------*/ hypre_ParVector *hypre_ParVectorRead( MPI_Comm comm, const char *file_name ) { char new_file_name[80]; hypre_ParVector *par_vector; HYPRE_Int my_id, num_procs; HYPRE_Int *partitioning; HYPRE_Int global_size, i; FILE *fp; hypre_MPI_Comm_rank(comm,&my_id); hypre_MPI_Comm_size(comm,&num_procs); partitioning = hypre_CTAlloc(HYPRE_Int,num_procs+1); hypre_sprintf(new_file_name,"%s.INFO.%d",file_name,my_id); fp = fopen(new_file_name, "r"); hypre_fscanf(fp, "%d\n", &global_size); #ifdef HYPRE_NO_GLOBAL_PARTITION for (i=0; i < 2; i++) hypre_fscanf(fp, "%d\n", &partitioning[i]); fclose (fp); #else for (i=0; i < num_procs; i++) hypre_fscanf(fp, "%d\n", &partitioning[i]); fclose (fp); partitioning[num_procs] = global_size; #endif par_vector = hypre_CTAlloc(hypre_ParVector, 1); hypre_ParVectorComm(par_vector) = comm; hypre_ParVectorGlobalSize(par_vector) = global_size; #ifdef HYPRE_NO_GLOBAL_PARTITION hypre_ParVectorFirstIndex(par_vector) = partitioning[0]; hypre_ParVectorLastIndex(par_vector) = partitioning[1]-1; #else hypre_ParVectorFirstIndex(par_vector) = partitioning[my_id]; hypre_ParVectorLastIndex(par_vector) = partitioning[my_id+1]-1; #endif hypre_ParVectorPartitioning(par_vector) = partitioning; hypre_ParVectorOwnsData(par_vector) = 1; hypre_ParVectorOwnsPartitioning(par_vector) = 1; hypre_sprintf(new_file_name,"%s.%d",file_name,my_id); hypre_ParVectorLocalVector(par_vector) = hypre_SeqVectorRead(new_file_name); /* multivector code not written yet >>> */ hypre_assert( hypre_ParVectorNumVectors(par_vector) == 1 ); return par_vector; } /*-------------------------------------------------------------------------- * hypre_ParVectorPrint *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParVectorPrint( hypre_ParVector *vector, const char *file_name ) { char new_file_name[80]; hypre_Vector *local_vector; MPI_Comm comm; HYPRE_Int my_id, num_procs, i; HYPRE_Int *partitioning; HYPRE_Int global_size; FILE *fp; if (!vector) { hypre_error_in_arg(1); return hypre_error_flag; } local_vector = hypre_ParVectorLocalVector(vector); comm = hypre_ParVectorComm(vector); partitioning = hypre_ParVectorPartitioning(vector); global_size = hypre_ParVectorGlobalSize(vector); hypre_MPI_Comm_rank(comm,&my_id); hypre_MPI_Comm_size(comm,&num_procs); hypre_sprintf(new_file_name,"%s.%d",file_name,my_id); hypre_SeqVectorPrint(local_vector,new_file_name); hypre_sprintf(new_file_name,"%s.INFO.%d",file_name,my_id); fp = fopen(new_file_name, "w"); hypre_fprintf(fp, "%d\n", global_size); #ifdef HYPRE_NO_GLOBAL_PARTITION for (i=0; i < 2; i++) hypre_fprintf(fp, "%d\n", partitioning[i]); #else for (i=0; i < num_procs; i++) hypre_fprintf(fp, "%d\n", partitioning[i]); #endif fclose (fp); return hypre_error_flag; } /*-------------------------------------------------------------------------- * hypre_ParVectorSetConstantValues *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParVectorSetConstantValues( hypre_ParVector *v, HYPRE_Complex value ) { hypre_Vector *v_local = hypre_ParVectorLocalVector(v); return hypre_SeqVectorSetConstantValues(v_local,value); } /*-------------------------------------------------------------------------- * hypre_ParVectorSetRandomValues *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParVectorSetRandomValues( hypre_ParVector *v, HYPRE_Int seed ) { HYPRE_Int my_id; hypre_Vector *v_local = hypre_ParVectorLocalVector(v); MPI_Comm comm = hypre_ParVectorComm(v); hypre_MPI_Comm_rank(comm,&my_id); seed *= (my_id+1); return hypre_SeqVectorSetRandomValues(v_local,seed); } /*-------------------------------------------------------------------------- * hypre_ParVectorCopy *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParVectorCopy( hypre_ParVector *x, hypre_ParVector *y ) { hypre_Vector *x_local = hypre_ParVectorLocalVector(x); hypre_Vector *y_local = hypre_ParVectorLocalVector(y); return hypre_SeqVectorCopy(x_local, y_local); } /*-------------------------------------------------------------------------- * hypre_ParVectorCloneShallow * returns a complete copy of a hypre_ParVector x - a shallow copy, re-using * the partitioning and data arrays of x *--------------------------------------------------------------------------*/ hypre_ParVector * hypre_ParVectorCloneShallow( hypre_ParVector *x ) { hypre_ParVector * y = hypre_ParVectorCreate(hypre_ParVectorComm(x), hypre_ParVectorGlobalSize(x), hypre_ParVectorPartitioning(x)); hypre_ParVectorOwnsData(y) = 1; /* ...This vector owns its local vector, although the local vector doesn't * own _its_ data */ hypre_ParVectorOwnsPartitioning(y) = 0; hypre_SeqVectorDestroy( hypre_ParVectorLocalVector(y) ); hypre_ParVectorLocalVector(y) = hypre_SeqVectorCloneShallow( hypre_ParVectorLocalVector(x) ); hypre_ParVectorFirstIndex(y) = hypre_ParVectorFirstIndex(x); return y; } /*-------------------------------------------------------------------------- * hypre_ParVectorScale *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParVectorScale( HYPRE_Complex alpha, hypre_ParVector *y ) { hypre_Vector *y_local = hypre_ParVectorLocalVector(y); return hypre_SeqVectorScale( alpha, y_local); } /*-------------------------------------------------------------------------- * hypre_ParVectorAxpy *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParVectorAxpy( HYPRE_Complex alpha, hypre_ParVector *x, hypre_ParVector *y ) { hypre_Vector *x_local = hypre_ParVectorLocalVector(x); hypre_Vector *y_local = hypre_ParVectorLocalVector(y); return hypre_SeqVectorAxpy( alpha, x_local, y_local); } /*-------------------------------------------------------------------------- * hypre_ParVectorInnerProd *--------------------------------------------------------------------------*/ HYPRE_Real hypre_ParVectorInnerProd( hypre_ParVector *x, hypre_ParVector *y ) { MPI_Comm comm = hypre_ParVectorComm(x); hypre_Vector *x_local = hypre_ParVectorLocalVector(x); hypre_Vector *y_local = hypre_ParVectorLocalVector(y); HYPRE_Real result = 0.0; HYPRE_Real local_result = hypre_SeqVectorInnerProd(x_local, y_local); #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_ALL_REDUCE] -= hypre_MPI_Wtime(); #endif hypre_MPI_Allreduce(&local_result, &result, 1, HYPRE_MPI_REAL, hypre_MPI_SUM, comm); #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_ALL_REDUCE] += hypre_MPI_Wtime(); #endif return result; } /*-------------------------------------------------------------------------- * hypre_VectorToParVector: * generates a ParVector from a Vector on proc 0 and distributes the pieces * to the other procs in comm * * this is not being optimized to use HYPRE_NO_GLOBAL_PARTITION *--------------------------------------------------------------------------*/ hypre_ParVector * hypre_VectorToParVector ( MPI_Comm comm, hypre_Vector *v, HYPRE_Int *vec_starts ) { HYPRE_Int global_size; HYPRE_Int local_size; HYPRE_Int num_vectors; HYPRE_Int num_procs, my_id; HYPRE_Int global_vecstride, vecstride, idxstride; hypre_ParVector *par_vector; hypre_Vector *local_vector; HYPRE_Complex *v_data; HYPRE_Complex *local_data; hypre_MPI_Request *requests; hypre_MPI_Status *status, status0; HYPRE_Int i, j, k, p; hypre_MPI_Comm_size(comm,&num_procs); hypre_MPI_Comm_rank(comm,&my_id); if (my_id == 0) { global_size = hypre_VectorSize(v); v_data = hypre_VectorData(v); num_vectors = hypre_VectorNumVectors(v); /* for multivectors */ global_vecstride = hypre_VectorVectorStride(v); } hypre_MPI_Bcast(&global_size,1,HYPRE_MPI_INT,0,comm); hypre_MPI_Bcast(&num_vectors,1,HYPRE_MPI_INT,0,comm); hypre_MPI_Bcast(&global_vecstride,1,HYPRE_MPI_INT,0,comm); if ( num_vectors==1 ) par_vector = hypre_ParVectorCreate(comm, global_size, vec_starts); else par_vector = hypre_ParMultiVectorCreate(comm, global_size, vec_starts, num_vectors); vec_starts = hypre_ParVectorPartitioning(par_vector); local_size = vec_starts[my_id+1] - vec_starts[my_id]; hypre_ParVectorInitialize(par_vector); local_vector = hypre_ParVectorLocalVector(par_vector); local_data = hypre_VectorData(local_vector); vecstride = hypre_VectorVectorStride(local_vector); idxstride = hypre_VectorIndexStride(local_vector); /* <<< so far the only implemented multivector StorageMethod is 0 <<< */ hypre_assert( idxstride==1 ); if (my_id == 0) { requests = hypre_CTAlloc(hypre_MPI_Request,num_vectors*(num_procs-1)); status = hypre_CTAlloc(hypre_MPI_Status,num_vectors*(num_procs-1)); k = 0; for ( p=1; p<num_procs; p++) for ( j=0; j<num_vectors; ++j ) { hypre_MPI_Isend( &v_data[vec_starts[p]]+j*global_vecstride, (vec_starts[p+1]-vec_starts[p]), HYPRE_MPI_COMPLEX, p, 0, comm, &requests[k++] ); } if ( num_vectors==1 ) { for (i=0; i < local_size; i++) local_data[i] = v_data[i]; } else for ( j=0; j<num_vectors; ++j ) { for (i=0; i < local_size; i++) local_data[i+j*vecstride] = v_data[i+j*global_vecstride]; } hypre_MPI_Waitall(num_procs-1,requests, status); hypre_TFree(requests); hypre_TFree(status); } else { for ( j=0; j<num_vectors; ++j ) hypre_MPI_Recv( local_data+j*vecstride, local_size, HYPRE_MPI_COMPLEX, 0, 0, comm,&status0 ); } return par_vector; } /*-------------------------------------------------------------------------- * hypre_ParVectorToVectorAll: * generates a Vector on every proc which has a piece of the data * from a ParVector on several procs in comm, * vec_starts needs to contain the partitioning across all procs in comm *--------------------------------------------------------------------------*/ hypre_Vector * hypre_ParVectorToVectorAll( hypre_ParVector *par_v ) { MPI_Comm comm = hypre_ParVectorComm(par_v); HYPRE_Int global_size = hypre_ParVectorGlobalSize(par_v); #ifndef HYPRE_NO_GLOBAL_PARTITION HYPRE_Int *vec_starts = hypre_ParVectorPartitioning(par_v); #endif hypre_Vector *local_vector = hypre_ParVectorLocalVector(par_v); HYPRE_Int num_procs, my_id; HYPRE_Int num_vectors = hypre_ParVectorNumVectors(par_v); hypre_Vector *vector; HYPRE_Complex *vector_data; HYPRE_Complex *local_data; HYPRE_Int local_size; hypre_MPI_Request *requests; hypre_MPI_Status *status; HYPRE_Int i, j; HYPRE_Int *used_procs; HYPRE_Int num_types, num_requests; HYPRE_Int vec_len, proc_id; #ifdef HYPRE_NO_GLOBAL_PARTITION HYPRE_Int *new_vec_starts; HYPRE_Int num_contacts; HYPRE_Int contact_proc_list[1]; HYPRE_Int contact_send_buf[1]; HYPRE_Int contact_send_buf_starts[2]; HYPRE_Int max_response_size; HYPRE_Int *response_recv_buf=NULL; HYPRE_Int *response_recv_buf_starts = NULL; hypre_DataExchangeResponse response_obj; hypre_ProcListElements send_proc_obj; HYPRE_Int *send_info = NULL; hypre_MPI_Status status1; HYPRE_Int count, tag1 = 112, tag2 = 223; HYPRE_Int start; #endif hypre_MPI_Comm_size(comm, &num_procs); hypre_MPI_Comm_rank(comm, &my_id); #ifdef HYPRE_NO_GLOBAL_PARTITION local_size = hypre_ParVectorLastIndex(par_v) - hypre_ParVectorFirstIndex(par_v) + 1; /* determine procs which hold data of par_v and store ids in used_procs */ /* we need to do an exchange data for this. If I own row then I will contact processor 0 with the endpoint of my local range */ if (local_size > 0) { num_contacts = 1; contact_proc_list[0] = 0; contact_send_buf[0] = hypre_ParVectorLastIndex(par_v); contact_send_buf_starts[0] = 0; contact_send_buf_starts[1] = 1; } else { num_contacts = 0; contact_send_buf_starts[0] = 0; contact_send_buf_starts[1] = 0; } /*build the response object*/ /*send_proc_obj will be for saving info from contacts */ send_proc_obj.length = 0; send_proc_obj.storage_length = 10; send_proc_obj.id = hypre_CTAlloc(HYPRE_Int, send_proc_obj.storage_length); send_proc_obj.vec_starts = hypre_CTAlloc(HYPRE_Int, send_proc_obj.storage_length + 1); send_proc_obj.vec_starts[0] = 0; send_proc_obj.element_storage_length = 10; send_proc_obj.elements = hypre_CTAlloc(HYPRE_Int, send_proc_obj.element_storage_length); max_response_size = 0; /* each response is null */ response_obj.fill_response = hypre_FillResponseParToVectorAll; response_obj.data1 = NULL; response_obj.data2 = &send_proc_obj; /*this is where we keep info from contacts*/ hypre_DataExchangeList(num_contacts, contact_proc_list, contact_send_buf, contact_send_buf_starts, sizeof(HYPRE_Int), sizeof(HYPRE_Int), &response_obj, max_response_size, 1, comm, (void**) &response_recv_buf, &response_recv_buf_starts); /* now processor 0 should have a list of ranges for processors that have rows - these are in send_proc_obj - it needs to create the new list of processors and also an array of vec starts - and send to those who own row*/ if (my_id) { if (local_size) { /* look for a message from processor 0 */ hypre_MPI_Probe(0, tag1, comm, &status1); hypre_MPI_Get_count(&status1, HYPRE_MPI_INT, &count); send_info = hypre_CTAlloc(HYPRE_Int, count); hypre_MPI_Recv(send_info, count, HYPRE_MPI_INT, 0, tag1, comm, &status1); /* now unpack */ num_types = send_info[0]; used_procs = hypre_CTAlloc(HYPRE_Int, num_types); new_vec_starts = hypre_CTAlloc(HYPRE_Int, num_types+1); for (i=1; i<= num_types; i++) { used_procs[i-1] = send_info[i]; } for (i=num_types+1; i< count; i++) { new_vec_starts[i-num_types-1] = send_info[i] ; } } else /* clean up and exit */ { hypre_TFree(send_proc_obj.vec_starts); hypre_TFree(send_proc_obj.id); hypre_TFree(send_proc_obj.elements); if(response_recv_buf) hypre_TFree(response_recv_buf); if(response_recv_buf_starts) hypre_TFree(response_recv_buf_starts); return NULL; } } else /* my_id ==0 */ { num_types = send_proc_obj.length; used_procs = hypre_CTAlloc(HYPRE_Int, num_types); new_vec_starts = hypre_CTAlloc(HYPRE_Int, num_types+1); new_vec_starts[0] = 0; for (i=0; i< num_types; i++) { used_procs[i] = send_proc_obj.id[i]; new_vec_starts[i+1] = send_proc_obj.elements[i]+1; } hypre_qsort0(used_procs, 0, num_types-1); hypre_qsort0(new_vec_starts, 0, num_types); /*now we need to put into an array to send */ count = 2*num_types+2; send_info = hypre_CTAlloc(HYPRE_Int, count); send_info[0] = num_types; for (i=1; i<= num_types; i++) { send_info[i] = used_procs[i-1]; } for (i=num_types+1; i< count; i++) { send_info[i] = new_vec_starts[i-num_types-1]; } requests = hypre_CTAlloc(hypre_MPI_Request, num_types); status = hypre_CTAlloc(hypre_MPI_Status, num_types); /* don't send to myself - these are sorted so my id would be first*/ start = 0; if (used_procs[0] == 0) { start = 1; } for (i=start; i < num_types; i++) { hypre_MPI_Isend(send_info, count, HYPRE_MPI_INT, used_procs[i], tag1, comm, &requests[i-start]); } hypre_MPI_Waitall(num_types-start, requests, status); hypre_TFree(status); hypre_TFree(requests); } /* clean up */ hypre_TFree(send_proc_obj.vec_starts); hypre_TFree(send_proc_obj.id); hypre_TFree(send_proc_obj.elements); hypre_TFree(send_info); if(response_recv_buf) hypre_TFree(response_recv_buf); if(response_recv_buf_starts) hypre_TFree(response_recv_buf_starts); /* now proc 0 can exit if it has no rows */ if (!local_size) { hypre_TFree(used_procs); hypre_TFree(new_vec_starts); return NULL; } /* everyone left has rows and knows: new_vec_starts, num_types, and used_procs */ /* this vector should be rather small */ local_data = hypre_VectorData(local_vector); vector = hypre_SeqVectorCreate(global_size); hypre_VectorNumVectors(vector) = num_vectors; hypre_SeqVectorInitialize(vector); vector_data = hypre_VectorData(vector); num_requests = 2*num_types; requests = hypre_CTAlloc(hypre_MPI_Request, num_requests); status = hypre_CTAlloc(hypre_MPI_Status, num_requests); /* initialize data exchange among used_procs and generate vector - here we send to ourself also*/ j = 0; for (i = 0; i < num_types; i++) { proc_id = used_procs[i]; vec_len = new_vec_starts[i+1] - new_vec_starts[i]; hypre_MPI_Irecv(&vector_data[new_vec_starts[i]], num_vectors*vec_len, HYPRE_MPI_COMPLEX, proc_id, tag2, comm, &requests[j++]); } for (i = 0; i < num_types; i++) { hypre_MPI_Isend(local_data, num_vectors*local_size, HYPRE_MPI_COMPLEX, used_procs[i], tag2, comm, &requests[j++]); } hypre_MPI_Waitall(num_requests, requests, status); if (num_requests) { hypre_TFree(requests); hypre_TFree(status); hypre_TFree(used_procs); } hypre_TFree(new_vec_starts); #else local_size = vec_starts[my_id+1] - vec_starts[my_id]; /* if my_id contains no data, return NULL */ if (!local_size) return NULL; local_data = hypre_VectorData(local_vector); vector = hypre_SeqVectorCreate(global_size); hypre_VectorNumVectors(vector) = num_vectors; hypre_SeqVectorInitialize(vector); vector_data = hypre_VectorData(vector); /* determine procs which hold data of par_v and store ids in used_procs */ num_types = -1; for (i=0; i < num_procs; i++) if (vec_starts[i+1]-vec_starts[i]) num_types++; num_requests = 2*num_types; used_procs = hypre_CTAlloc(HYPRE_Int, num_types); j = 0; for (i=0; i < num_procs; i++) if (vec_starts[i+1]-vec_starts[i] && i-my_id) used_procs[j++] = i; requests = hypre_CTAlloc(hypre_MPI_Request, num_requests); status = hypre_CTAlloc(hypre_MPI_Status, num_requests); /* initialize data exchange among used_procs and generate vector */ j = 0; for (i = 0; i < num_types; i++) { proc_id = used_procs[i]; vec_len = vec_starts[proc_id+1] - vec_starts[proc_id]; hypre_MPI_Irecv(&vector_data[vec_starts[proc_id]], num_vectors*vec_len, HYPRE_MPI_COMPLEX, proc_id, 0, comm, &requests[j++]); } for (i = 0; i < num_types; i++) { hypre_MPI_Isend(local_data, num_vectors*local_size, HYPRE_MPI_COMPLEX, used_procs[i], 0, comm, &requests[j++]); } for (i=0; i < num_vectors*local_size; i++) vector_data[vec_starts[my_id]+i] = local_data[i]; hypre_MPI_Waitall(num_requests, requests, status); if (num_requests) { hypre_TFree(used_procs); hypre_TFree(requests); hypre_TFree(status); } #endif return vector; } /*-------------------------------------------------------------------------- * hypre_ParVectorPrintIJ *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParVectorPrintIJ( hypre_ParVector *vector, HYPRE_Int base_j, const char *filename ) { MPI_Comm comm; HYPRE_Int global_size; HYPRE_Int *partitioning; HYPRE_Complex *local_data; HYPRE_Int myid, num_procs, i, j, part0; char new_filename[255]; FILE *file; if (!vector) { hypre_error_in_arg(1); return hypre_error_flag; } comm = hypre_ParVectorComm(vector); global_size = hypre_ParVectorGlobalSize(vector); partitioning = hypre_ParVectorPartitioning(vector); /* multivector code not written yet >>> */ hypre_assert( hypre_ParVectorNumVectors(vector) == 1 ); if ( hypre_ParVectorNumVectors(vector) != 1 ) hypre_error_in_arg(1); hypre_MPI_Comm_rank(comm, &myid); hypre_MPI_Comm_size(comm, &num_procs); hypre_sprintf(new_filename,"%s.%05d", filename, myid); if ((file = fopen(new_filename, "w")) == NULL) { hypre_error_w_msg(HYPRE_ERROR_GENERIC,"Error: can't open output file %s\n"); return hypre_error_flag; } local_data = hypre_VectorData(hypre_ParVectorLocalVector(vector)); hypre_fprintf(file, "%d \n", global_size); #ifdef HYPRE_NO_GLOBAL_PARTITION for (i=0; i <= 2; i++) { hypre_fprintf(file, "%d \n", partitioning[i] + base_j); } #else for (i=0; i <= num_procs; i++) { hypre_fprintf(file, "%d \n", partitioning[i] + base_j); } #endif #ifdef HYPRE_NO_GLOBAL_PARTITION part0 = partitioning[0]; for (j = part0; j < partitioning[1]; j++) { hypre_fprintf(file, "%d %.14e\n", j + base_j, local_data[j-part0]); } #else part0 = partitioning[myid]; for (j = part0; j < partitioning[myid+1]; j++) { hypre_fprintf(file, "%d %.14e\n", j + base_j, local_data[j-part0]); } #endif fclose(file); return hypre_error_flag; } /*-------------------------------------------------------------------------- * hypre_ParVectorReadIJ *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParVectorReadIJ( MPI_Comm comm, const char *filename, HYPRE_Int *base_j_ptr, hypre_ParVector **vector_ptr ) { HYPRE_Int global_size; hypre_ParVector *vector; hypre_Vector *local_vector; HYPRE_Complex *local_data; HYPRE_Int *partitioning; HYPRE_Int base_j; HYPRE_Int myid, num_procs, i, j, J; char new_filename[255]; FILE *file; hypre_MPI_Comm_size(comm, &num_procs); hypre_MPI_Comm_rank(comm, &myid); hypre_sprintf(new_filename,"%s.%05d", filename, myid); if ((file = fopen(new_filename, "r")) == NULL) { hypre_error_w_msg(HYPRE_ERROR_GENERIC,"Error: can't open output file %s\n"); return hypre_error_flag; } hypre_fscanf(file, "%d", &global_size); #ifdef HYPRE_NO_GLOBAL_PARTITION /* this may need to be changed so that the base is available in the file! */ partitioning = hypre_CTAlloc(HYPRE_Int,2); hypre_fscanf(file, "%d", partitioning); for (i = 0; i < 2; i++) { hypre_fscanf(file, "%d", partitioning+i); } /* This is not yet implemented correctly! */ base_j = 0; #else partitioning = hypre_CTAlloc(HYPRE_Int,num_procs+1); hypre_fscanf(file, "%d", partitioning); for (i = 1; i <= num_procs; i++) { hypre_fscanf(file, "%d", partitioning+i); partitioning[i] -= partitioning[0]; } base_j = partitioning[0]; partitioning[0] = 0; #endif vector = hypre_ParVectorCreate(comm, global_size, partitioning); hypre_ParVectorInitialize(vector); local_vector = hypre_ParVectorLocalVector(vector); local_data = hypre_VectorData(local_vector); #ifdef HYPRE_NO_GLOBAL_PARTITION for (j = 0; j < partitioning[1] - partitioning[0]; j++) { hypre_fscanf(file, "%d %le", &J, local_data + j); } #else for (j = 0; j < partitioning[myid+1] - partitioning[myid]; j++) { hypre_fscanf(file, "%d %le", &J, local_data + j); } #endif fclose(file); *base_j_ptr = base_j; *vector_ptr = vector; /* multivector code not written yet >>> */ hypre_assert( hypre_ParVectorNumVectors(vector) == 1 ); if ( hypre_ParVectorNumVectors(vector) != 1 ) hypre_error(HYPRE_ERROR_GENERIC); return hypre_error_flag; } /*-------------------------------------------------------------------- * hypre_FillResponseParToVectorAll * Fill response function for determining the send processors * data exchange *--------------------------------------------------------------------*/ HYPRE_Int hypre_FillResponseParToVectorAll( void *p_recv_contact_buf, HYPRE_Int contact_size, HYPRE_Int contact_proc, void *ro, MPI_Comm comm, void **p_send_response_buf, HYPRE_Int *response_message_size ) { HYPRE_Int myid; HYPRE_Int i, index, count, elength; HYPRE_Int *recv_contact_buf = (HYPRE_Int * ) p_recv_contact_buf; hypre_DataExchangeResponse *response_obj = (hypre_DataExchangeResponse*)ro; hypre_ProcListElements *send_proc_obj = (hypre_ProcListElements*)response_obj->data2; hypre_MPI_Comm_rank(comm, &myid ); /*check to see if we need to allocate more space in send_proc_obj for ids*/ if (send_proc_obj->length == send_proc_obj->storage_length) { send_proc_obj->storage_length +=10; /*add space for 10 more processors*/ send_proc_obj->id = hypre_TReAlloc(send_proc_obj->id,HYPRE_Int, send_proc_obj->storage_length); send_proc_obj->vec_starts = hypre_TReAlloc(send_proc_obj->vec_starts,HYPRE_Int, send_proc_obj->storage_length + 1); } /*initialize*/ count = send_proc_obj->length; index = send_proc_obj->vec_starts[count]; /*this is the number of elements*/ /*send proc*/ send_proc_obj->id[count] = contact_proc; /*do we need more storage for the elements?*/ if (send_proc_obj->element_storage_length < index + contact_size) { elength = hypre_max(contact_size, 10); elength += index; send_proc_obj->elements = hypre_TReAlloc(send_proc_obj->elements, HYPRE_Int, elength); send_proc_obj->element_storage_length = elength; } /*populate send_proc_obj*/ for (i=0; i< contact_size; i++) { send_proc_obj->elements[index++] = recv_contact_buf[i]; } send_proc_obj->vec_starts[count+1] = index; send_proc_obj->length++; /*output - no message to return (confirmation) */ *response_message_size = 0; return hypre_error_flag; } /* ----------------------------------------------------------------------------- * return the sum of all local elements of the vector * ----------------------------------------------------------------------------- */ HYPRE_Complex hypre_ParVectorLocalSumElts( hypre_ParVector * vector ) { return hypre_VectorSumElts( hypre_ParVectorLocalVector(vector) ); }
35,481
31.732472
109
c
AMG
AMG-master/parcsr_mv/par_vector.h
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /****************************************************************************** * * Header info for Parallel Vector data structure * *****************************************************************************/ #ifndef hypre_PAR_VECTOR_HEADER #define hypre_PAR_VECTOR_HEADER /*-------------------------------------------------------------------------- * hypre_ParVector *--------------------------------------------------------------------------*/ #ifndef HYPRE_PAR_VECTOR_STRUCT #define HYPRE_PAR_VECTOR_STRUCT #endif typedef struct hypre_ParVector_struct { MPI_Comm comm; HYPRE_Int global_size; HYPRE_Int first_index; HYPRE_Int last_index; HYPRE_Int *partitioning; HYPRE_Int actual_local_size; /* stores actual length of data in local vector to allow memory manipulations for temporary vectors*/ hypre_Vector *local_vector; /* Does the Vector create/destroy `data'? */ HYPRE_Int owns_data; HYPRE_Int owns_partitioning; hypre_IJAssumedPart *assumed_partition; /* only populated if no_global_partition option is used (compile-time option) AND this partition needed (for setting off-proc elements, for example)*/ } hypre_ParVector; /*-------------------------------------------------------------------------- * Accessor functions for the Vector structure *--------------------------------------------------------------------------*/ #define hypre_ParVectorComm(vector) ((vector) -> comm) #define hypre_ParVectorGlobalSize(vector) ((vector) -> global_size) #define hypre_ParVectorFirstIndex(vector) ((vector) -> first_index) #define hypre_ParVectorLastIndex(vector) ((vector) -> last_index) #define hypre_ParVectorPartitioning(vector) ((vector) -> partitioning) #define hypre_ParVectorActualLocalSize(vector) ((vector) -> actual_local_size) #define hypre_ParVectorLocalVector(vector) ((vector) -> local_vector) #define hypre_ParVectorOwnsData(vector) ((vector) -> owns_data) #define hypre_ParVectorOwnsPartitioning(vector) ((vector) -> owns_partitioning) #define hypre_ParVectorNumVectors(vector)\ (hypre_VectorNumVectors( hypre_ParVectorLocalVector(vector) )) #define hypre_ParVectorAssumedPartition(vector) ((vector) -> assumed_partition) #endif
3,376
39.202381
94
h
AMG
AMG-master/seq_mv/HYPRE_csr_matrix.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /****************************************************************************** * * HYPRE_CSRMatrix interface * *****************************************************************************/ #include "seq_mv.h" /*-------------------------------------------------------------------------- * HYPRE_CSRMatrixCreate *--------------------------------------------------------------------------*/ HYPRE_CSRMatrix HYPRE_CSRMatrixCreate( HYPRE_Int num_rows, HYPRE_Int num_cols, HYPRE_Int *row_sizes ) { hypre_CSRMatrix *matrix; HYPRE_Int *matrix_i; HYPRE_Int i; matrix_i = hypre_CTAlloc(HYPRE_Int, num_rows + 1); matrix_i[0] = 0; for (i = 0; i < num_rows; i++) { matrix_i[i+1] = matrix_i[i] + row_sizes[i]; } matrix = hypre_CSRMatrixCreate(num_rows, num_cols, matrix_i[num_rows]); hypre_CSRMatrixI(matrix) = matrix_i; return ( (HYPRE_CSRMatrix) matrix ); } /*-------------------------------------------------------------------------- * HYPRE_CSRMatrixDestroy *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_CSRMatrixDestroy( HYPRE_CSRMatrix matrix ) { return( hypre_CSRMatrixDestroy( (hypre_CSRMatrix *) matrix ) ); } /*-------------------------------------------------------------------------- * HYPRE_CSRMatrixInitialize *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_CSRMatrixInitialize( HYPRE_CSRMatrix matrix ) { return ( hypre_CSRMatrixInitialize( (hypre_CSRMatrix *) matrix ) ); } /*-------------------------------------------------------------------------- * HYPRE_CSRMatrixRead *--------------------------------------------------------------------------*/ HYPRE_CSRMatrix HYPRE_CSRMatrixRead( char *file_name ) { return ( (HYPRE_CSRMatrix) hypre_CSRMatrixRead( file_name ) ); } /*-------------------------------------------------------------------------- * HYPRE_CSRMatrixPrint *--------------------------------------------------------------------------*/ void HYPRE_CSRMatrixPrint( HYPRE_CSRMatrix matrix, char *file_name ) { hypre_CSRMatrixPrint( (hypre_CSRMatrix *) matrix, file_name ); } /*-------------------------------------------------------------------------- * HYPRE_CSRMatrixGetNumRows *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_CSRMatrixGetNumRows( HYPRE_CSRMatrix matrix, HYPRE_Int *num_rows ) { hypre_CSRMatrix *csr_matrix = (hypre_CSRMatrix *) matrix; *num_rows = hypre_CSRMatrixNumRows( csr_matrix ); return 0; }
3,645
31.553571
81
c
AMG
AMG-master/seq_mv/HYPRE_seq_mv.h
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /****************************************************************************** * * Header file for HYPRE_mv library * *****************************************************************************/ #ifndef HYPRE_SEQ_MV_HEADER #define HYPRE_SEQ_MV_HEADER #include "../utilities/HYPRE_utilities.h" #ifdef __cplusplus extern "C" { #endif /*-------------------------------------------------------------------------- * Structures *--------------------------------------------------------------------------*/ struct hypre_CSRMatrix_struct; typedef struct hypre_CSRMatrix_struct *HYPRE_CSRMatrix; #ifndef HYPRE_VECTOR_STRUCT #define HYPRE_VECTOR_STRUCT struct hypre_Vector_struct; typedef struct hypre_Vector_struct *HYPRE_Vector; #endif /*-------------------------------------------------------------------------- * Prototypes *--------------------------------------------------------------------------*/ /* HYPRE_csr_matrix.c */ HYPRE_CSRMatrix HYPRE_CSRMatrixCreate( HYPRE_Int num_rows , HYPRE_Int num_cols , HYPRE_Int *row_sizes ); HYPRE_Int HYPRE_CSRMatrixDestroy( HYPRE_CSRMatrix matrix ); HYPRE_Int HYPRE_CSRMatrixInitialize( HYPRE_CSRMatrix matrix ); HYPRE_CSRMatrix HYPRE_CSRMatrixRead( char *file_name ); void HYPRE_CSRMatrixPrint( HYPRE_CSRMatrix matrix , char *file_name ); HYPRE_Int HYPRE_CSRMatrixGetNumRows( HYPRE_CSRMatrix matrix , HYPRE_Int *num_rows ); /* HYPRE_vector.c */ HYPRE_Vector HYPRE_VectorCreate( HYPRE_Int size ); HYPRE_Int HYPRE_VectorDestroy( HYPRE_Vector vector ); HYPRE_Int HYPRE_VectorInitialize( HYPRE_Vector vector ); HYPRE_Int HYPRE_VectorPrint( HYPRE_Vector vector , char *file_name ); HYPRE_Vector HYPRE_VectorRead( char *file_name ); typedef enum HYPRE_TimerID { // timers for solver phase HYPRE_TIMER_ID_MATVEC = 0, HYPRE_TIMER_ID_BLAS1, HYPRE_TIMER_ID_RELAX, HYPRE_TIMER_ID_GS_ELIM_SOLVE, // timers for solve MPI HYPRE_TIMER_ID_PACK_UNPACK, // copying data to/from send/recv buf HYPRE_TIMER_ID_HALO_EXCHANGE, // halo exchange in matvec and relax HYPRE_TIMER_ID_ALL_REDUCE, // timers for setup phase // coarsening HYPRE_TIMER_ID_CREATES, HYPRE_TIMER_ID_CREATE_2NDS, HYPRE_TIMER_ID_PMIS, // interpolation HYPRE_TIMER_ID_EXTENDED_I_INTERP, HYPRE_TIMER_ID_PARTIAL_INTERP, HYPRE_TIMER_ID_MULTIPASS_INTERP, HYPRE_TIMER_ID_INTERP_TRUNC, HYPRE_TIMER_ID_MATMUL, // matrix-matrix multiplication HYPRE_TIMER_ID_COARSE_PARAMS, // rap HYPRE_TIMER_ID_RAP, // timers for setup MPI HYPRE_TIMER_ID_RENUMBER_COLIDX, HYPRE_TIMER_ID_EXCHANGE_INTERP_DATA, // setup etc HYPRE_TIMER_ID_GS_ELIM_SETUP, // temporaries HYPRE_TIMER_ID_BEXT_A, HYPRE_TIMER_ID_BEXT_S, HYPRE_TIMER_ID_RENUMBER_COLIDX_RAP, HYPRE_TIMER_ID_MERGE, HYPRE_TIMER_ID_COUNT } HYPRE_TimerID; extern HYPRE_Real hypre_profile_times[HYPRE_TIMER_ID_COUNT]; #ifdef __cplusplus } #endif #endif
3,825
30.619835
104
h
AMG
AMG-master/seq_mv/HYPRE_vector.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /****************************************************************************** * * HYPRE_Vector interface * *****************************************************************************/ #include "seq_mv.h" /*-------------------------------------------------------------------------- * HYPRE_VectorCreate *--------------------------------------------------------------------------*/ HYPRE_Vector HYPRE_VectorCreate( HYPRE_Int size ) { return ( (HYPRE_Vector) hypre_SeqVectorCreate(size) ); } /*-------------------------------------------------------------------------- * HYPRE_VectorDestroy *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_VectorDestroy( HYPRE_Vector vector ) { return ( hypre_SeqVectorDestroy( (hypre_Vector *) vector ) ); } /*-------------------------------------------------------------------------- * HYPRE_VectorInitialize *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_VectorInitialize( HYPRE_Vector vector ) { return ( hypre_SeqVectorInitialize( (hypre_Vector *) vector ) ); } /*-------------------------------------------------------------------------- * HYPRE_VectorPrint *--------------------------------------------------------------------------*/ HYPRE_Int HYPRE_VectorPrint( HYPRE_Vector vector, char *file_name ) { return ( hypre_SeqVectorPrint( (hypre_Vector *) vector, file_name ) ); } /*-------------------------------------------------------------------------- * HYPRE_VectorRead *--------------------------------------------------------------------------*/ HYPRE_Vector HYPRE_VectorRead( char *file_name ) { return ( (HYPRE_Vector) hypre_SeqVectorRead( file_name ) ); }
2,727
33.1
81
c
AMG
AMG-master/seq_mv/csr_matop.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /****************************************************************************** * * Matrix operation functions for hypre_CSRMatrix class. * *****************************************************************************/ #include <assert.h> #include "seq_mv.h" #include "csr_matrix.h" /*-------------------------------------------------------------------------- * hypre_CSRMatrixAdd: * adds two CSR Matrices A and B and returns a CSR Matrix C; * Note: The routine does not check for 0-elements which might be generated * through cancellation of elements in A and B or already contained in A and B. To remove those, use hypre_CSRMatrixDeleteZeros *--------------------------------------------------------------------------*/ hypre_CSRMatrix * hypre_CSRMatrixAdd( hypre_CSRMatrix *A, hypre_CSRMatrix *B ) { HYPRE_Complex *A_data = hypre_CSRMatrixData(A); HYPRE_Int *A_i = hypre_CSRMatrixI(A); HYPRE_Int *A_j = hypre_CSRMatrixJ(A); HYPRE_Int nrows_A = hypre_CSRMatrixNumRows(A); HYPRE_Int ncols_A = hypre_CSRMatrixNumCols(A); HYPRE_Complex *B_data = hypre_CSRMatrixData(B); HYPRE_Int *B_i = hypre_CSRMatrixI(B); HYPRE_Int *B_j = hypre_CSRMatrixJ(B); HYPRE_Int nrows_B = hypre_CSRMatrixNumRows(B); HYPRE_Int ncols_B = hypre_CSRMatrixNumCols(B); hypre_CSRMatrix *C; HYPRE_Complex *C_data; HYPRE_Int *C_i; HYPRE_Int *C_j; HYPRE_Int ia, ib, ic, jcol, num_nonzeros; HYPRE_Int pos; HYPRE_Int *marker; if (nrows_A != nrows_B || ncols_A != ncols_B) { hypre_error_w_msg(HYPRE_ERROR_GENERIC,"Warning! incompatible matrix dimensions!\n"); return NULL; } marker = hypre_CTAlloc(HYPRE_Int, ncols_A); C_i = hypre_CTAlloc(HYPRE_Int, nrows_A+1); for (ia = 0; ia < ncols_A; ia++) marker[ia] = -1; num_nonzeros = 0; C_i[0] = 0; for (ic = 0; ic < nrows_A; ic++) { for (ia = A_i[ic]; ia < A_i[ic+1]; ia++) { jcol = A_j[ia]; marker[jcol] = ic; num_nonzeros++; } for (ib = B_i[ic]; ib < B_i[ic+1]; ib++) { jcol = B_j[ib]; if (marker[jcol] != ic) { marker[jcol] = ic; num_nonzeros++; } } C_i[ic+1] = num_nonzeros; } C = hypre_CSRMatrixCreate(nrows_A, ncols_A, num_nonzeros); hypre_CSRMatrixI(C) = C_i; hypre_CSRMatrixInitialize(C); C_j = hypre_CSRMatrixJ(C); C_data = hypre_CSRMatrixData(C); for (ia = 0; ia < ncols_A; ia++) marker[ia] = -1; pos = 0; for (ic = 0; ic < nrows_A; ic++) { for (ia = A_i[ic]; ia < A_i[ic+1]; ia++) { jcol = A_j[ia]; C_j[pos] = jcol; C_data[pos] = A_data[ia]; marker[jcol] = pos; pos++; } for (ib = B_i[ic]; ib < B_i[ic+1]; ib++) { jcol = B_j[ib]; if (marker[jcol] < C_i[ic]) { C_j[pos] = jcol; C_data[pos] = B_data[ib]; marker[jcol] = pos; pos++; } else { C_data[marker[jcol]] += B_data[ib]; } } } hypre_TFree(marker); return C; } /*-------------------------------------------------------------------------- * hypre_CSRMatrixMultiply * multiplies two CSR Matrices A and B and returns a CSR Matrix C; * Note: The routine does not check for 0-elements which might be generated * through cancellation of elements in A and B or already contained in A and B. To remove those, use hypre_CSRMatrixDeleteZeros *--------------------------------------------------------------------------*/ hypre_CSRMatrix * hypre_CSRMatrixMultiply( hypre_CSRMatrix *A, hypre_CSRMatrix *B) { HYPRE_Complex *A_data = hypre_CSRMatrixData(A); HYPRE_Int *A_i = hypre_CSRMatrixI(A); HYPRE_Int *A_j = hypre_CSRMatrixJ(A); HYPRE_Int nrows_A = hypre_CSRMatrixNumRows(A); HYPRE_Int ncols_A = hypre_CSRMatrixNumCols(A); HYPRE_Complex *B_data = hypre_CSRMatrixData(B); HYPRE_Int *B_i = hypre_CSRMatrixI(B); HYPRE_Int *B_j = hypre_CSRMatrixJ(B); HYPRE_Int nrows_B = hypre_CSRMatrixNumRows(B); HYPRE_Int ncols_B = hypre_CSRMatrixNumCols(B); hypre_CSRMatrix *C; HYPRE_Complex *C_data; HYPRE_Int *C_i; HYPRE_Int *C_j; HYPRE_Int ia, ib, ic, ja, jb, num_nonzeros=0; HYPRE_Int row_start, counter; HYPRE_Complex a_entry, b_entry; HYPRE_Int allsquare = 0; HYPRE_Int max_num_threads; HYPRE_Int *jj_count; if (ncols_A != nrows_B) { hypre_error_w_msg(HYPRE_ERROR_GENERIC,"Warning! incompatible matrix dimensions!\n"); return NULL; } if (nrows_A == ncols_B) allsquare = 1; C_i = hypre_CTAlloc(HYPRE_Int, nrows_A+1); max_num_threads = hypre_NumThreads(); jj_count = hypre_CTAlloc(HYPRE_Int, max_num_threads); #ifdef HYPRE_USING_OPENMP #pragma omp parallel private(ia, ib, ic, ja, jb, num_nonzeros, row_start, counter, a_entry, b_entry) #endif { HYPRE_Int *B_marker = NULL; HYPRE_Int ns, ne, ii, jj; HYPRE_Int size, rest, num_threads; HYPRE_Int i1; ii = hypre_GetThreadNum(); num_threads = hypre_NumActiveThreads(); size = nrows_A/num_threads; rest = nrows_A - size*num_threads; if (ii < rest) { ns = ii*size+ii; ne = (ii+1)*size+ii+1; } else { ns = ii*size+rest; ne = (ii+1)*size+rest; } B_marker = hypre_CTAlloc(HYPRE_Int, ncols_B); for (ib = 0; ib < ncols_B; ib++) B_marker[ib] = -1; num_nonzeros = 0; for (ic = ns; ic < ne; ic++) { C_i[ic] = num_nonzeros; if (allsquare) { B_marker[ic] = ic; num_nonzeros++; } for (ia = A_i[ic]; ia < A_i[ic+1]; ia++) { ja = A_j[ia]; for (ib = B_i[ja]; ib < B_i[ja+1]; ib++) { jb = B_j[ib]; if (B_marker[jb] != ic) { B_marker[jb] = ic; num_nonzeros++; } } } } jj_count[ii] = num_nonzeros; #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif if (ii) { jj = jj_count[0]; for (i1 = 1; i1 < ii; i1++) jj += jj_count[i1]; for (i1 = ns; i1 < ne; i1++) C_i[i1] += jj; } else { C_i[nrows_A] = 0; for (i1 = 0; i1 < num_threads; i1++) C_i[nrows_A] += jj_count[i1]; C = hypre_CSRMatrixCreate(nrows_A, ncols_B, C_i[nrows_A]); hypre_CSRMatrixI(C) = C_i; hypre_CSRMatrixInitialize(C); C_j = hypre_CSRMatrixJ(C); C_data = hypre_CSRMatrixData(C); } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif for (ib = 0; ib < ncols_B; ib++) B_marker[ib] = -1; counter = C_i[ns]; for (ic = ns; ic < ne; ic++) { row_start = C_i[ic]; if (allsquare) { B_marker[ic] = counter; C_data[counter] = 0; C_j[counter] = ic; counter++; } for (ia = A_i[ic]; ia < A_i[ic+1]; ia++) { ja = A_j[ia]; a_entry = A_data[ia]; for (ib = B_i[ja]; ib < B_i[ja+1]; ib++) { jb = B_j[ib]; b_entry = B_data[ib]; if (B_marker[jb] < row_start) { B_marker[jb] = counter; C_j[B_marker[jb]] = jb; C_data[B_marker[jb]] = a_entry*b_entry; counter++; } else C_data[B_marker[jb]] += a_entry*b_entry; } } } hypre_TFree(B_marker); } /*end parallel region */ hypre_TFree(jj_count); return C; } hypre_CSRMatrix * hypre_CSRMatrixDeleteZeros( hypre_CSRMatrix *A, HYPRE_Real tol) { HYPRE_Complex *A_data = hypre_CSRMatrixData(A); HYPRE_Int *A_i = hypre_CSRMatrixI(A); HYPRE_Int *A_j = hypre_CSRMatrixJ(A); HYPRE_Int nrows_A = hypre_CSRMatrixNumRows(A); HYPRE_Int ncols_A = hypre_CSRMatrixNumCols(A); HYPRE_Int num_nonzeros = hypre_CSRMatrixNumNonzeros(A); hypre_CSRMatrix *B; HYPRE_Complex *B_data; HYPRE_Int *B_i; HYPRE_Int *B_j; HYPRE_Int zeros; HYPRE_Int i, j; HYPRE_Int pos_A, pos_B; zeros = 0; for (i=0; i < num_nonzeros; i++) if (hypre_cabs(A_data[i]) <= tol) zeros++; if (zeros) { B = hypre_CSRMatrixCreate(nrows_A,ncols_A,num_nonzeros-zeros); hypre_CSRMatrixInitialize(B); B_i = hypre_CSRMatrixI(B); B_j = hypre_CSRMatrixJ(B); B_data = hypre_CSRMatrixData(B); B_i[0] = 0; pos_A = 0; pos_B = 0; for (i=0; i < nrows_A; i++) { for (j = A_i[i]; j < A_i[i+1]; j++) { if (hypre_cabs(A_data[j]) <= tol) { pos_A++; } else { B_data[pos_B] = A_data[pos_A]; B_j[pos_B] = A_j[pos_A]; pos_B++; pos_A++; } } B_i[i+1] = pos_B; } return B; } else return NULL; } /****************************************************************************** * * Finds transpose of a hypre_CSRMatrix * *****************************************************************************/ /** * idx = idx2*dim1 + idx1 * -> ret = idx1*dim2 + idx2 * = (idx%dim1)*dim2 + idx/dim1 */ static inline HYPRE_Int transpose_idx(HYPRE_Int idx, HYPRE_Int dim1, HYPRE_Int dim2) { return idx%dim1*dim2 + idx/dim1; } /*-------------------------------------------------------------------------- * hypre_CSRMatrixTranspose *--------------------------------------------------------------------------*/ HYPRE_Int hypre_CSRMatrixTranspose(hypre_CSRMatrix *A, hypre_CSRMatrix **AT, HYPRE_Int data) { HYPRE_Complex *A_data = hypre_CSRMatrixData(A); HYPRE_Int *A_i = hypre_CSRMatrixI(A); HYPRE_Int *A_j = hypre_CSRMatrixJ(A); HYPRE_Int num_rowsA = hypre_CSRMatrixNumRows(A); HYPRE_Int num_colsA = hypre_CSRMatrixNumCols(A); HYPRE_Int num_nonzerosA = hypre_CSRMatrixNumNonzeros(A); HYPRE_Complex *AT_data; /*HYPRE_Int *AT_i;*/ HYPRE_Int *AT_j; HYPRE_Int num_rowsAT; HYPRE_Int num_colsAT; HYPRE_Int num_nonzerosAT; HYPRE_Int max_col; HYPRE_Int i, j; /*-------------------------------------------------------------- * First, ascertain that num_cols and num_nonzeros has been set. * If not, set them. *--------------------------------------------------------------*/ if (! num_nonzerosA) { num_nonzerosA = A_i[num_rowsA]; } if (num_rowsA && num_nonzerosA && ! num_colsA) { max_col = -1; for (i = 0; i < num_rowsA; ++i) { for (j = A_i[i]; j < A_i[i+1]; j++) { if (A_j[j] > max_col) max_col = A_j[j]; } } num_colsA = max_col+1; } num_rowsAT = num_colsA; num_colsAT = num_rowsA; num_nonzerosAT = num_nonzerosA; *AT = hypre_CSRMatrixCreate(num_rowsAT, num_colsAT, num_nonzerosAT); if (0 == num_colsA) { // JSP: parallel counting sorting breaks down // when A has no columns hypre_CSRMatrixInitialize(*AT); return 0; } AT_j = hypre_CTAlloc(HYPRE_Int, num_nonzerosAT); hypre_CSRMatrixJ(*AT) = AT_j; if (data) { AT_data = hypre_CTAlloc(HYPRE_Complex, num_nonzerosAT); hypre_CSRMatrixData(*AT) = AT_data; } /*----------------------------------------------------------------- * Parallel count sort *-----------------------------------------------------------------*/ HYPRE_Int *bucket = hypre_TAlloc( HYPRE_Int, (num_colsA + 1)*hypre_NumThreads()); #ifdef HYPRE_USING_OPENMP #pragma omp parallel #endif { HYPRE_Int num_threads = hypre_NumActiveThreads(); HYPRE_Int my_thread_num = hypre_GetThreadNum(); HYPRE_Int iBegin = hypre_CSRMatrixGetLoadBalancedPartitionBegin(A); HYPRE_Int iEnd = hypre_CSRMatrixGetLoadBalancedPartitionEnd(A); hypre_assert(iBegin <= iEnd); hypre_assert(iBegin >= 0 && iBegin <= num_rowsA); hypre_assert(iEnd >= 0 && iEnd <= num_rowsA); HYPRE_Int i, j; memset(bucket + my_thread_num*num_colsA, 0, sizeof(HYPRE_Int)*num_colsA); /*----------------------------------------------------------------- * Count the number of entries that will go into each bucket * bucket is used as HYPRE_Int[num_threads][num_colsA] 2D array *-----------------------------------------------------------------*/ for (j = A_i[iBegin]; j < A_i[iEnd]; ++j) { HYPRE_Int idx = A_j[j]; bucket[my_thread_num*num_colsA + idx]++; } /*----------------------------------------------------------------- * Parallel prefix sum of bucket with length num_colsA * num_threads * accessed as if it is transposed as HYPRE_Int[num_colsA][num_threads] *-----------------------------------------------------------------*/ #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif for (i = my_thread_num*num_colsA + 1; i < (my_thread_num + 1)*num_colsA; ++i) { HYPRE_Int transpose_i = transpose_idx(i, num_threads, num_colsA); HYPRE_Int transpose_i_minus_1 = transpose_idx(i - 1, num_threads, num_colsA); bucket[transpose_i] += bucket[transpose_i_minus_1]; } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #pragma omp master #endif { for (i = 1; i < num_threads; ++i) { HYPRE_Int j0 = num_colsA*i - 1, j1 = num_colsA*(i + 1) - 1; HYPRE_Int transpose_j0 = transpose_idx(j0, num_threads, num_colsA); HYPRE_Int transpose_j1 = transpose_idx(j1, num_threads, num_colsA); bucket[transpose_j1] += bucket[transpose_j0]; } } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif if (my_thread_num > 0) { HYPRE_Int transpose_i0 = transpose_idx(num_colsA*my_thread_num - 1, num_threads, num_colsA); HYPRE_Int offset = bucket[transpose_i0]; for (i = my_thread_num*num_colsA; i < (my_thread_num + 1)*num_colsA - 1; ++i) { HYPRE_Int transpose_i = transpose_idx(i, num_threads, num_colsA); bucket[transpose_i] += offset; } } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif /*---------------------------------------------------------------- * Load the data and column numbers of AT *----------------------------------------------------------------*/ if (data) { for (i = iEnd - 1; i >= iBegin; --i) { for (j = A_i[i + 1] - 1; j >= A_i[i]; --j) { HYPRE_Int idx = A_j[j]; --bucket[my_thread_num*num_colsA + idx]; HYPRE_Int offset = bucket[my_thread_num*num_colsA + idx]; AT_data[offset] = A_data[j]; AT_j[offset] = i; } } } else { for (i = iEnd - 1; i >= iBegin; --i) { for (j = A_i[i + 1] - 1; j >= A_i[i]; --j) { HYPRE_Int idx = A_j[j]; --bucket[my_thread_num*num_colsA + idx]; HYPRE_Int offset = bucket[my_thread_num*num_colsA + idx]; AT_j[offset] = i; } } } } /*end parallel region */ hypre_CSRMatrixI(*AT) = bucket; // JSP: bucket is hypre_NumThreads() times longer than // the size needed for AT_i, but this should be OK. // If the memory size is a concern, we can allocate // a new memory for AT_i and copy from bucket. hypre_CSRMatrixI(*AT)[num_colsA] = num_nonzerosA; return(0); } /*-------------------------------------------------------------------------- * hypre_CSRMatrixReorder: * Reorders the column and data arrays of a square CSR matrix, such that the * first entry in each row is the diagonal one. *--------------------------------------------------------------------------*/ HYPRE_Int hypre_CSRMatrixReorder(hypre_CSRMatrix *A) { HYPRE_Int i, j, tempi, row_size; HYPRE_Complex tempd; HYPRE_Complex *A_data = hypre_CSRMatrixData(A); HYPRE_Int *A_i = hypre_CSRMatrixI(A); HYPRE_Int *A_j = hypre_CSRMatrixJ(A); HYPRE_Int num_rowsA = hypre_CSRMatrixNumRows(A); HYPRE_Int num_colsA = hypre_CSRMatrixNumCols(A); /* the matrix should be square */ if (num_rowsA != num_colsA) return -1; for (i = 0; i < num_rowsA; i++) { row_size = A_i[i+1]-A_i[i]; for (j = 0; j < row_size; j++) { if (A_j[j] == i) { if (j != 0) { tempi = A_j[0]; A_j[0] = A_j[j]; A_j[j] = tempi; tempd = A_data[0]; A_data[0] = A_data[j]; A_data[j] = tempd; } break; } /* diagonal element is missing */ if (j == row_size-1) return -2; } A_j += row_size; A_data += row_size; } return 0; } /*-------------------------------------------------------------------------- * hypre_CSRMatrixSumElts: * Returns the sum of all matrix elements. *--------------------------------------------------------------------------*/ HYPRE_Complex hypre_CSRMatrixSumElts( hypre_CSRMatrix *A ) { HYPRE_Complex sum = 0; HYPRE_Complex *data = hypre_CSRMatrixData( A ); HYPRE_Int num_nonzeros = hypre_CSRMatrixNumNonzeros(A); HYPRE_Int i; for ( i=0; i<num_nonzeros; ++i ) sum += data[i]; return sum; }
18,537
27.652241
100
c
AMG
AMG-master/seq_mv/csr_matrix.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /****************************************************************************** * * Member functions for hypre_CSRMatrix class. * *****************************************************************************/ #include "seq_mv.h" #ifdef HYPRE_PROFILE HYPRE_Real hypre_profile_times[HYPRE_TIMER_ID_COUNT] = { 0 }; #endif /*-------------------------------------------------------------------------- * hypre_CSRMatrixCreate *--------------------------------------------------------------------------*/ hypre_CSRMatrix * hypre_CSRMatrixCreate( HYPRE_Int num_rows, HYPRE_Int num_cols, HYPRE_Int num_nonzeros ) { hypre_CSRMatrix *matrix; matrix = hypre_CTAlloc(hypre_CSRMatrix, 1); hypre_CSRMatrixData(matrix) = NULL; hypre_CSRMatrixI(matrix) = NULL; hypre_CSRMatrixJ(matrix) = NULL; hypre_CSRMatrixRownnz(matrix) = NULL; hypre_CSRMatrixNumRows(matrix) = num_rows; hypre_CSRMatrixNumCols(matrix) = num_cols; hypre_CSRMatrixNumNonzeros(matrix) = num_nonzeros; /* set defaults */ hypre_CSRMatrixOwnsData(matrix) = 1; hypre_CSRMatrixNumRownnz(matrix) = num_rows; return matrix; } /*-------------------------------------------------------------------------- * hypre_CSRMatrixDestroy *--------------------------------------------------------------------------*/ HYPRE_Int hypre_CSRMatrixDestroy( hypre_CSRMatrix *matrix ) { HYPRE_Int ierr=0; if (matrix) { hypre_TFree(hypre_CSRMatrixI(matrix)); hypre_CSRMatrixI(matrix) = NULL; if (hypre_CSRMatrixRownnz(matrix)) hypre_TFree(hypre_CSRMatrixRownnz(matrix)); if ( hypre_CSRMatrixOwnsData(matrix) ) { hypre_TFree(hypre_CSRMatrixData(matrix)); hypre_TFree(hypre_CSRMatrixJ(matrix)); hypre_CSRMatrixData(matrix) = NULL; hypre_CSRMatrixJ(matrix) = NULL; } hypre_TFree(matrix); matrix = NULL; } return ierr; } /*-------------------------------------------------------------------------- * hypre_CSRMatrixInitialize *--------------------------------------------------------------------------*/ HYPRE_Int hypre_CSRMatrixInitialize( hypre_CSRMatrix *matrix ) { HYPRE_Int num_rows = hypre_CSRMatrixNumRows(matrix); HYPRE_Int num_nonzeros = hypre_CSRMatrixNumNonzeros(matrix); /* HYPRE_Int num_rownnz = hypre_CSRMatrixNumRownnz(matrix); */ HYPRE_Int ierr=0; if ( ! hypre_CSRMatrixData(matrix) && num_nonzeros ) hypre_CSRMatrixData(matrix) = hypre_CTAlloc(HYPRE_Complex, num_nonzeros); if ( ! hypre_CSRMatrixI(matrix) ) hypre_CSRMatrixI(matrix) = hypre_CTAlloc(HYPRE_Int, num_rows + 1); /* if ( ! hypre_CSRMatrixRownnz(matrix) ) hypre_CSRMatrixRownnz(matrix) = hypre_CTAlloc(HYPRE_Int, num_rownnz);*/ if ( ! hypre_CSRMatrixJ(matrix) && num_nonzeros ) hypre_CSRMatrixJ(matrix) = hypre_CTAlloc(HYPRE_Int, num_nonzeros); return ierr; } /*-------------------------------------------------------------------------- * hypre_CSRMatrixSetDataOwner *--------------------------------------------------------------------------*/ HYPRE_Int hypre_CSRMatrixSetDataOwner( hypre_CSRMatrix *matrix, HYPRE_Int owns_data ) { HYPRE_Int ierr=0; hypre_CSRMatrixOwnsData(matrix) = owns_data; return ierr; } /*-------------------------------------------------------------------------- * hypre_CSRMatrixSetRownnz * * function to set the substructure rownnz and num_rowsnnz inside the CSRMatrix * it needs the A_i substructure of CSRMatrix to find the nonzero rows. * It runs after the create CSR and when A_i is known..It does not check for * the existence of A_i or of the CSR matrix. *--------------------------------------------------------------------------*/ HYPRE_Int hypre_CSRMatrixSetRownnz( hypre_CSRMatrix *matrix ) { HYPRE_Int ierr=0; HYPRE_Int num_rows = hypre_CSRMatrixNumRows(matrix); HYPRE_Int *A_i = hypre_CSRMatrixI(matrix); HYPRE_Int *Arownnz; HYPRE_Int i, adiag; HYPRE_Int irownnz=0; for (i=0; i < num_rows; i++) { adiag = (A_i[i+1] - A_i[i]); if(adiag > 0) irownnz++; } hypre_CSRMatrixNumRownnz(matrix) = irownnz; if ((irownnz == 0) || (irownnz == num_rows)) { hypre_CSRMatrixRownnz(matrix) = NULL; } else { Arownnz = hypre_CTAlloc(HYPRE_Int, irownnz); irownnz = 0; for (i=0; i < num_rows; i++) { adiag = A_i[i+1]-A_i[i]; if(adiag > 0) Arownnz[irownnz++] = i; } hypre_CSRMatrixRownnz(matrix) = Arownnz; } return ierr; } /*-------------------------------------------------------------------------- * hypre_CSRMatrixRead *--------------------------------------------------------------------------*/ hypre_CSRMatrix * hypre_CSRMatrixRead( char *file_name ) { hypre_CSRMatrix *matrix; FILE *fp; HYPRE_Complex *matrix_data; HYPRE_Int *matrix_i; HYPRE_Int *matrix_j; HYPRE_Int num_rows; HYPRE_Int num_nonzeros; HYPRE_Int max_col = 0; HYPRE_Int file_base = 1; HYPRE_Int j; /*---------------------------------------------------------- * Read in the data *----------------------------------------------------------*/ fp = fopen(file_name, "r"); hypre_fscanf(fp, "%d", &num_rows); matrix_i = hypre_CTAlloc(HYPRE_Int, num_rows + 1); for (j = 0; j < num_rows+1; j++) { hypre_fscanf(fp, "%d", &matrix_i[j]); matrix_i[j] -= file_base; } num_nonzeros = matrix_i[num_rows]; matrix = hypre_CSRMatrixCreate(num_rows, num_rows, matrix_i[num_rows]); hypre_CSRMatrixI(matrix) = matrix_i; hypre_CSRMatrixInitialize(matrix); matrix_j = hypre_CSRMatrixJ(matrix); for (j = 0; j < num_nonzeros; j++) { hypre_fscanf(fp, "%d", &matrix_j[j]); matrix_j[j] -= file_base; if (matrix_j[j] > max_col) { max_col = matrix_j[j]; } } matrix_data = hypre_CSRMatrixData(matrix); for (j = 0; j < matrix_i[num_rows]; j++) { hypre_fscanf(fp, "%le", &matrix_data[j]); } fclose(fp); hypre_CSRMatrixNumNonzeros(matrix) = num_nonzeros; hypre_CSRMatrixNumCols(matrix) = ++max_col; return matrix; } /*-------------------------------------------------------------------------- * hypre_CSRMatrixPrint *--------------------------------------------------------------------------*/ HYPRE_Int hypre_CSRMatrixPrint( hypre_CSRMatrix *matrix, char *file_name ) { FILE *fp; HYPRE_Complex *matrix_data; HYPRE_Int *matrix_i; HYPRE_Int *matrix_j; HYPRE_Int num_rows; HYPRE_Int file_base = 1; HYPRE_Int j; HYPRE_Int ierr = 0; /*---------------------------------------------------------- * Print the matrix data *----------------------------------------------------------*/ matrix_data = hypre_CSRMatrixData(matrix); matrix_i = hypre_CSRMatrixI(matrix); matrix_j = hypre_CSRMatrixJ(matrix); num_rows = hypre_CSRMatrixNumRows(matrix); fp = fopen(file_name, "w"); hypre_fprintf(fp, "%d\n", num_rows); for (j = 0; j <= num_rows; j++) { hypre_fprintf(fp, "%d\n", matrix_i[j] + file_base); } for (j = 0; j < matrix_i[num_rows]; j++) { hypre_fprintf(fp, "%d\n", matrix_j[j] + file_base); } if (matrix_data) { for (j = 0; j < matrix_i[num_rows]; j++) { #ifdef HYPRE_COMPLEX hypre_fprintf(fp, "%.14e , %.14e\n", hypre_creal(matrix_data[j]), hypre_cimag(matrix_data[j])); #else hypre_fprintf(fp, "%.14e\n", matrix_data[j]); #endif } } else { hypre_fprintf(fp, "Warning: No matrix data!\n"); } fclose(fp); return ierr; } /*-------------------------------------------------------------------------- * hypre_CSRMatrixPrintHB: print a CSRMatrix in Harwell-Boeing format *--------------------------------------------------------------------------*/ HYPRE_Int hypre_CSRMatrixPrintHB( hypre_CSRMatrix *matrix_input, char *file_name ) { FILE *fp; hypre_CSRMatrix *matrix; HYPRE_Complex *matrix_data; HYPRE_Int *matrix_i; HYPRE_Int *matrix_j; HYPRE_Int num_rows; HYPRE_Int file_base = 1; HYPRE_Int j, totcrd, ptrcrd, indcrd, valcrd, rhscrd; HYPRE_Int ierr = 0; /*---------------------------------------------------------- * Print the matrix data *----------------------------------------------------------*/ /* First transpose the input matrix, since HB is in CSC format */ hypre_CSRMatrixTranspose(matrix_input, &matrix, 1); matrix_data = hypre_CSRMatrixData(matrix); matrix_i = hypre_CSRMatrixI(matrix); matrix_j = hypre_CSRMatrixJ(matrix); num_rows = hypre_CSRMatrixNumRows(matrix); fp = fopen(file_name, "w"); hypre_fprintf(fp, "%-70s Key \n", "Title"); ptrcrd = num_rows; indcrd = matrix_i[num_rows]; valcrd = matrix_i[num_rows]; rhscrd = 0; totcrd = ptrcrd + indcrd + valcrd + rhscrd; hypre_fprintf (fp, "%14d%14d%14d%14d%14d\n", totcrd, ptrcrd, indcrd, valcrd, rhscrd); hypre_fprintf (fp, "%-14s%14i%14i%14i%14i\n", "RUA", num_rows, num_rows, valcrd, 0); hypre_fprintf (fp, "%-16s%-16s%-16s%26s\n", "(1I8)", "(1I8)", "(1E16.8)", ""); for (j = 0; j <= num_rows; j++) { hypre_fprintf(fp, "%8d\n", matrix_i[j] + file_base); } for (j = 0; j < matrix_i[num_rows]; j++) { hypre_fprintf(fp, "%8d\n", matrix_j[j] + file_base); } if (matrix_data) { for (j = 0; j < matrix_i[num_rows]; j++) { #ifdef HYPRE_COMPLEX hypre_fprintf(fp, "%16.8e , %16.8e\n", hypre_creal(matrix_data[j]), hypre_cimag(matrix_data[j])); #else hypre_fprintf(fp, "%16.8e\n", matrix_data[j]); #endif } } else { hypre_fprintf(fp, "Warning: No matrix data!\n"); } fclose(fp); hypre_CSRMatrixDestroy(matrix); return ierr; } /*-------------------------------------------------------------------------- * hypre_CSRMatrixCopy: * copys A to B, * if copy_data = 0 only the structure of A is copied to B. * the routine does not check if the dimensions of A and B match !!! *--------------------------------------------------------------------------*/ HYPRE_Int hypre_CSRMatrixCopy( hypre_CSRMatrix *A, hypre_CSRMatrix *B, HYPRE_Int copy_data ) { HYPRE_Int ierr=0; HYPRE_Int num_rows = hypre_CSRMatrixNumRows(A); HYPRE_Int *A_i = hypre_CSRMatrixI(A); HYPRE_Int *A_j = hypre_CSRMatrixJ(A); HYPRE_Complex *A_data; HYPRE_Int *B_i = hypre_CSRMatrixI(B); HYPRE_Int *B_j = hypre_CSRMatrixJ(B); HYPRE_Complex *B_data; HYPRE_Int num_nonzeros = hypre_CSRMatrixNumNonzeros(A); HYPRE_Int i, j; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for HYPRE_SMP_SCHEDULE #endif for (i=0; i <= num_rows; i++) { B_i[i] = A_i[i]; } #ifdef HYPRE_USING_OPENMP #pragma omp parallel for HYPRE_SMP_SCHEDULE #endif for (j = 0; j < num_nonzeros; ++j) { B_j[j] = A_j[j]; } if (copy_data) { A_data = hypre_CSRMatrixData(A); B_data = hypre_CSRMatrixData(B); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for HYPRE_SMP_SCHEDULE #endif for (j=0; j < num_nonzeros; j++) { B_data[j] = A_data[j]; } } return ierr; } /*-------------------------------------------------------------------------- * hypre_CSRMatrixClone * Creates and returns a new copy of the argument, A. * Data is not copied, only structural information is reproduced. * Copying is a deep copy in that no pointers are copied; new arrays are * created where necessary. *--------------------------------------------------------------------------*/ hypre_CSRMatrix * hypre_CSRMatrixClone( hypre_CSRMatrix * A ) { HYPRE_Int num_rows = hypre_CSRMatrixNumRows( A ); HYPRE_Int num_cols = hypre_CSRMatrixNumCols( A ); HYPRE_Int num_nonzeros = hypre_CSRMatrixNumNonzeros( A ); hypre_CSRMatrix * B = hypre_CSRMatrixCreate( num_rows, num_cols, num_nonzeros ); HYPRE_Int * A_i; HYPRE_Int * A_j; HYPRE_Int * B_i; HYPRE_Int * B_j; HYPRE_Int i, j; hypre_CSRMatrixInitialize( B ); A_i = hypre_CSRMatrixI(A); A_j = hypre_CSRMatrixJ(A); B_i = hypre_CSRMatrixI(B); B_j = hypre_CSRMatrixJ(B); for ( i=0; i<num_rows+1; ++i ) B_i[i] = A_i[i]; for ( j=0; j<num_nonzeros; ++j ) B_j[j] = A_j[j]; hypre_CSRMatrixNumRownnz(B) = hypre_CSRMatrixNumRownnz(A); if ( hypre_CSRMatrixRownnz(A) ) hypre_CSRMatrixSetRownnz( B ); return B; } /*-------------------------------------------------------------------------- * hypre_CSRMatrixUnion * Creates and returns a matrix whose elements are the union of those of A and B. * Data is not computed, only structural information is created. * A and B must have the same numbers of rows. * Nothing is done about Rownnz. * * If col_map_offd_A and col_map_offd_B are zero, A and B are expected to have * the same column indexing. Otherwise, col_map_offd_A, col_map_offd_B should * be the arrays of that name from two ParCSRMatrices of which A and B are the * offd blocks. * * The algorithm can be expected to have reasonable efficiency only for very * sparse matrices (many rows, few nonzeros per row). * The nonzeros of a computed row are NOT necessarily in any particular order. *--------------------------------------------------------------------------*/ hypre_CSRMatrix * hypre_CSRMatrixUnion( hypre_CSRMatrix * A, hypre_CSRMatrix * B, HYPRE_Int * col_map_offd_A, HYPRE_Int * col_map_offd_B, HYPRE_Int ** col_map_offd_C ) { HYPRE_Int num_rows = hypre_CSRMatrixNumRows( A ); HYPRE_Int num_cols_A = hypre_CSRMatrixNumCols( A ); HYPRE_Int num_cols_B = hypre_CSRMatrixNumCols( B ); HYPRE_Int num_cols; HYPRE_Int num_nonzeros; HYPRE_Int * A_i = hypre_CSRMatrixI(A); HYPRE_Int * A_j = hypre_CSRMatrixJ(A); HYPRE_Int * B_i = hypre_CSRMatrixI(B); HYPRE_Int * B_j = hypre_CSRMatrixJ(B); HYPRE_Int * C_i; HYPRE_Int * C_j; HYPRE_Int * jC = NULL; HYPRE_Int i, jA, jB, jBg; HYPRE_Int ma, mb, mc, ma_min, ma_max, match; hypre_CSRMatrix * C; hypre_assert( num_rows == hypre_CSRMatrixNumRows(B) ); if ( col_map_offd_B ) hypre_assert( col_map_offd_A ); if ( col_map_offd_A ) hypre_assert( col_map_offd_B ); /* ==== First, go through the columns of A and B to count the columns of C. */ if ( col_map_offd_A==0 ) { /* The matrices are diagonal blocks. Normally num_cols_A==num_cols_B, col_starts is the same, etc. */ num_cols = hypre_max( num_cols_A, num_cols_B ); } else { /* The matrices are offdiagonal blocks. */ jC = hypre_CTAlloc( HYPRE_Int, num_cols_B ); num_cols = num_cols_A; /* initialization; we'll compute the actual value */ for ( jB=0; jB<num_cols_B; ++jB ) { match = 0; jBg = col_map_offd_B[jB]; for ( ma=0; ma<num_cols_A; ++ma ) { if ( col_map_offd_A[ma]==jBg ) match = 1; } if ( match==0 ) { jC[jB] = num_cols; ++num_cols; } } } /* ==== If we're working on a ParCSRMatrix's offd block, make and load col_map_offd_C */ if ( col_map_offd_A ) { *col_map_offd_C = hypre_CTAlloc( HYPRE_Int, num_cols ); for ( jA=0; jA<num_cols_A; ++jA ) (*col_map_offd_C)[jA] = col_map_offd_A[jA]; for ( jB=0; jB<num_cols_B; ++jB ) { match = 0; jBg = col_map_offd_B[jB]; for ( ma=0; ma<num_cols_A; ++ma ) { if ( col_map_offd_A[ma]==jBg ) match = 1; } if ( match==0 ) (*col_map_offd_C)[ jC[jB] ] = jBg; } } /* ==== The first run through A and B is to count the number of nonzero elements, without HYPRE_Complex-counting duplicates. Then we can create C. */ num_nonzeros = hypre_CSRMatrixNumNonzeros(A); for ( i=0; i<num_rows; ++i ) { ma_min = A_i[i]; ma_max = A_i[i+1]; for ( mb=B_i[i]; mb<B_i[i+1]; ++mb ) { jB = B_j[mb]; if ( col_map_offd_B ) jB = col_map_offd_B[jB]; match = 0; for ( ma=ma_min; ma<ma_max; ++ma ) { jA = A_j[ma]; if ( col_map_offd_A ) jA = col_map_offd_A[jA]; if ( jB == jA ) { match = 1; if( ma==ma_min ) ++ma_min; break; } } if ( match==0 ) ++num_nonzeros; } } C = hypre_CSRMatrixCreate( num_rows, num_cols, num_nonzeros ); hypre_CSRMatrixInitialize( C ); /* ==== The second run through A and B is to pick out the column numbers for each row, and put them in C. */ C_i = hypre_CSRMatrixI(C); C_i[0] = 0; C_j = hypre_CSRMatrixJ(C); mc = 0; for ( i=0; i<num_rows; ++i ) { ma_min = A_i[i]; ma_max = A_i[i+1]; for ( ma=ma_min; ma<ma_max; ++ma ) { C_j[mc] = A_j[ma]; ++mc; } for ( mb=B_i[i]; mb<B_i[i+1]; ++mb ) { jB = B_j[mb]; if ( col_map_offd_B ) jB = col_map_offd_B[jB]; match = 0; for ( ma=ma_min; ma<ma_max; ++ma ) { jA = A_j[ma]; if ( col_map_offd_A ) jA = col_map_offd_A[jA]; if ( jB == jA ) { match = 1; if( ma==ma_min ) ++ma_min; break; } } if ( match==0 ) { if ( col_map_offd_A ) C_j[mc] = jC[ B_j[mb] ]; else C_j[mc] = B_j[mb]; /* ... I don't know whether column indices are required to be in any particular order. If so, we'll need to sort. */ ++mc; } } C_i[i+1] = mc; } hypre_assert( mc == num_nonzeros ); if (jC) hypre_TFree( jC ); return C; } static HYPRE_Int hypre_CSRMatrixGetLoadBalancedPartitionBoundary(hypre_CSRMatrix *A, HYPRE_Int idx) { HYPRE_Int num_nonzerosA = hypre_CSRMatrixNumNonzeros(A); HYPRE_Int num_rowsA = hypre_CSRMatrixNumRows(A); HYPRE_Int *A_i = hypre_CSRMatrixI(A); HYPRE_Int num_threads = hypre_NumActiveThreads(); HYPRE_Int nonzeros_per_thread = (num_nonzerosA + num_threads - 1)/num_threads; if (idx <= 0) { return 0; } else if (idx >= num_threads) { return num_rowsA; } else { return (HYPRE_Int)(hypre_LowerBound(A_i, A_i + num_rowsA, nonzeros_per_thread*idx) - A_i); } } HYPRE_Int hypre_CSRMatrixGetLoadBalancedPartitionBegin(hypre_CSRMatrix *A) { return hypre_CSRMatrixGetLoadBalancedPartitionBoundary(A, hypre_GetThreadNum()); } HYPRE_Int hypre_CSRMatrixGetLoadBalancedPartitionEnd(hypre_CSRMatrix *A) { return hypre_CSRMatrixGetLoadBalancedPartitionBoundary(A, hypre_GetThreadNum() + 1); }
20,095
28.727811
99
c
AMG
AMG-master/seq_mv/csr_matrix.h
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /****************************************************************************** * * Header info for CSR Matrix data structures * * Note: this matrix currently uses 0-based indexing. * *****************************************************************************/ #ifndef hypre_CSR_MATRIX_HEADER #define hypre_CSR_MATRIX_HEADER /*-------------------------------------------------------------------------- * CSR Matrix *--------------------------------------------------------------------------*/ typedef struct { HYPRE_Int *i; HYPRE_Int *j; HYPRE_Int num_rows; HYPRE_Int num_cols; HYPRE_Int num_nonzeros; /* Does the CSRMatrix create/destroy `data', `i', `j'? */ HYPRE_Int owns_data; HYPRE_Complex *data; /* for compressing rows in matrix multiplication */ HYPRE_Int *rownnz; HYPRE_Int num_rownnz; } hypre_CSRMatrix; /*-------------------------------------------------------------------------- * Accessor functions for the CSR Matrix structure *--------------------------------------------------------------------------*/ #define hypre_CSRMatrixData(matrix) ((matrix) -> data) #define hypre_CSRMatrixI(matrix) ((matrix) -> i) #define hypre_CSRMatrixJ(matrix) ((matrix) -> j) #define hypre_CSRMatrixNumRows(matrix) ((matrix) -> num_rows) #define hypre_CSRMatrixNumCols(matrix) ((matrix) -> num_cols) #define hypre_CSRMatrixNumNonzeros(matrix) ((matrix) -> num_nonzeros) #define hypre_CSRMatrixRownnz(matrix) ((matrix) -> rownnz) #define hypre_CSRMatrixNumRownnz(matrix) ((matrix) -> num_rownnz) #define hypre_CSRMatrixOwnsData(matrix) ((matrix) -> owns_data) HYPRE_Int hypre_CSRMatrixGetLoadBalancedPartitionBegin( hypre_CSRMatrix *A ); HYPRE_Int hypre_CSRMatrixGetLoadBalancedPartitionEnd( hypre_CSRMatrix *A ); /*-------------------------------------------------------------------------- * CSR Boolean Matrix *--------------------------------------------------------------------------*/ typedef struct { HYPRE_Int *i; HYPRE_Int *j; HYPRE_Int num_rows; HYPRE_Int num_cols; HYPRE_Int num_nonzeros; HYPRE_Int owns_data; } hypre_CSRBooleanMatrix; /*-------------------------------------------------------------------------- * Accessor functions for the CSR Boolean Matrix structure *--------------------------------------------------------------------------*/ #define hypre_CSRBooleanMatrix_Get_I(matrix) ((matrix)->i) #define hypre_CSRBooleanMatrix_Get_J(matrix) ((matrix)->j) #define hypre_CSRBooleanMatrix_Get_NRows(matrix) ((matrix)->num_rows) #define hypre_CSRBooleanMatrix_Get_NCols(matrix) ((matrix)->num_cols) #define hypre_CSRBooleanMatrix_Get_NNZ(matrix) ((matrix)->num_nonzeros) #define hypre_CSRBooleanMatrix_Get_OwnsData(matrix) ((matrix)->owns_data) #endif
3,814
38.329897
81
h
AMG
AMG-master/seq_mv/csr_matvec.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /****************************************************************************** * * Matvec functions for hypre_CSRMatrix class. * *****************************************************************************/ #include "seq_mv.h" #include <assert.h> /*-------------------------------------------------------------------------- * hypre_CSRMatrixMatvec *--------------------------------------------------------------------------*/ /* y[offset:end] = alpha*A[offset:end,:]*x + beta*b[offset:end] */ HYPRE_Int hypre_CSRMatrixMatvecOutOfPlace( HYPRE_Complex alpha, hypre_CSRMatrix *A, hypre_Vector *x, HYPRE_Complex beta, hypre_Vector *b, hypre_Vector *y, HYPRE_Int offset ) { #ifdef HYPRE_PROFILE HYPRE_Real time_begin = hypre_MPI_Wtime(); #endif #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_MATVEC] += hypre_MPI_Wtime() - time_begin; #endif HYPRE_Complex *A_data = hypre_CSRMatrixData(A); HYPRE_Int *A_i = hypre_CSRMatrixI(A) + offset; HYPRE_Int *A_j = hypre_CSRMatrixJ(A); HYPRE_Int num_rows = hypre_CSRMatrixNumRows(A) - offset; HYPRE_Int num_cols = hypre_CSRMatrixNumCols(A); /*HYPRE_Int num_nnz = hypre_CSRMatrixNumNonzeros(A);*/ HYPRE_Int *A_rownnz = hypre_CSRMatrixRownnz(A); HYPRE_Int num_rownnz = hypre_CSRMatrixNumRownnz(A); HYPRE_Complex *x_data = hypre_VectorData(x); HYPRE_Complex *b_data = hypre_VectorData(b) + offset; HYPRE_Complex *y_data = hypre_VectorData(y) + offset; HYPRE_Int x_size = hypre_VectorSize(x); HYPRE_Int b_size = hypre_VectorSize(b) - offset; HYPRE_Int y_size = hypre_VectorSize(y) - offset; HYPRE_Int num_vectors = hypre_VectorNumVectors(x); HYPRE_Int idxstride_y = hypre_VectorIndexStride(y); HYPRE_Int vecstride_y = hypre_VectorVectorStride(y); /*HYPRE_Int idxstride_b = hypre_VectorIndexStride(b); HYPRE_Int vecstride_b = hypre_VectorVectorStride(b);*/ HYPRE_Int idxstride_x = hypre_VectorIndexStride(x); HYPRE_Int vecstride_x = hypre_VectorVectorStride(x); HYPRE_Complex temp, tempx; HYPRE_Int i, j, jj; HYPRE_Int m; HYPRE_Real xpar=0.7; HYPRE_Int ierr = 0; hypre_Vector *x_tmp = NULL; /*--------------------------------------------------------------------- * Check for size compatibility. Matvec returns ierr = 1 if * length of X doesn't equal the number of columns of A, * ierr = 2 if the length of Y doesn't equal the number of rows * of A, and ierr = 3 if both are true. * * Because temporary vectors are often used in Matvec, none of * these conditions terminates processing, and the ierr flag * is informational only. *--------------------------------------------------------------------*/ hypre_assert( num_vectors == hypre_VectorNumVectors(y) ); hypre_assert( num_vectors == hypre_VectorNumVectors(b) ); if (num_cols != x_size) ierr = 1; if (num_rows != y_size || num_rows != b_size) ierr = 2; if (num_cols != x_size && (num_rows != y_size || num_rows != b_size)) ierr = 3; /*----------------------------------------------------------------------- * Do (alpha == 0.0) computation - RDF: USE MACHINE EPS *-----------------------------------------------------------------------*/ if (alpha == 0.0) { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_rows*num_vectors; i++) y_data[i] = beta*b_data[i]; #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_MATVEC] += hypre_MPI_Wtime() - time_begin; #endif return ierr; } if (x == y) { x_tmp = hypre_SeqVectorCloneDeep(x); x_data = hypre_VectorData(x_tmp); } /*----------------------------------------------------------------------- * y = (beta/alpha)*y *-----------------------------------------------------------------------*/ temp = beta / alpha; /* use rownnz pointer to do the A*x multiplication when num_rownnz is smaller than num_rows */ if (num_rownnz < xpar*(num_rows) || num_vectors > 1) { /*----------------------------------------------------------------------- * y = (beta/alpha)*y *-----------------------------------------------------------------------*/ if (temp != 1.0) { if (temp == 0.0) { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_rows*num_vectors; i++) y_data[i] = 0.0; } else { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_rows*num_vectors; i++) y_data[i] = b_data[i]*temp; } } else { for (i = 0; i < num_rows*num_vectors; i++) y_data[i] = b_data[i]; } /*----------------------------------------------------------------- * y += A*x *-----------------------------------------------------------------*/ if (num_rownnz < xpar*(num_rows)) { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,j,jj,m,tempx) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_rownnz; i++) { m = A_rownnz[i]; /* * for (jj = A_i[m]; jj < A_i[m+1]; jj++) * { * j = A_j[jj]; * y_data[m] += A_data[jj] * x_data[j]; * } */ if ( num_vectors==1 ) { tempx = 0; for (jj = A_i[m]; jj < A_i[m+1]; jj++) tempx += A_data[jj] * x_data[A_j[jj]]; y_data[m] += tempx; } else for ( j=0; j<num_vectors; ++j ) { tempx = 0; for (jj = A_i[m]; jj < A_i[m+1]; jj++) tempx += A_data[jj] * x_data[ j*vecstride_x + A_j[jj]*idxstride_x ]; y_data[ j*vecstride_y + m*idxstride_y] += tempx; } } } else // num_vectors > 1 { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,j,jj,tempx) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_rows; i++) { for (j = 0; j < num_vectors; ++j) { tempx = 0; for (jj = A_i[i]; jj < A_i[i+1]; jj++) { tempx += A_data[jj] * x_data[ j*vecstride_x + A_j[jj]*idxstride_x ]; } y_data[ j*vecstride_y + i*idxstride_y ] += tempx; } } } /*----------------------------------------------------------------- * y = alpha*y *-----------------------------------------------------------------*/ if (alpha != 1.0) { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_rows*num_vectors; i++) y_data[i] *= alpha; } } else { // JSP: this is currently the only path optimized #ifdef HYPRE_USING_OPENMP #pragma omp parallel private(i,jj,tempx) #endif { HYPRE_Int iBegin = hypre_CSRMatrixGetLoadBalancedPartitionBegin(A); HYPRE_Int iEnd = hypre_CSRMatrixGetLoadBalancedPartitionEnd(A); hypre_assert(iBegin <= iEnd); hypre_assert(iBegin >= 0 && iBegin <= num_rows); hypre_assert(iEnd >= 0 && iEnd <= num_rows); if (0 == temp) { if (1 == alpha) // JSP: a common path { for (i = iBegin; i < iEnd; i++) { tempx = 0.0; for (jj = A_i[i]; jj < A_i[i+1]; jj++) { tempx += A_data[jj] * x_data[A_j[jj]]; } y_data[i] = tempx; } } // y = A*x else if (-1 == alpha) { for (i = iBegin; i < iEnd; i++) { tempx = 0.0; for (jj = A_i[i]; jj < A_i[i+1]; jj++) { tempx -= A_data[jj] * x_data[A_j[jj]]; } y_data[i] = tempx; } } // y = -A*x else { for (i = iBegin; i < iEnd; i++) { tempx = 0.0; for (jj = A_i[i]; jj < A_i[i+1]; jj++) { tempx += A_data[jj] * x_data[A_j[jj]]; } y_data[i] = alpha*tempx; } } // y = alpha*A*x } // temp == 0 else if (-1 == temp) // beta == -alpha { if (1 == alpha) // JSP: a common path { for (i = iBegin; i < iEnd; i++) { tempx = -b_data[i]; for (jj = A_i[i]; jj < A_i[i+1]; jj++) { tempx += A_data[jj] * x_data[A_j[jj]]; } y_data[i] = tempx; } } // y = A*x - y else if (-1 == alpha) // JSP: a common path { for (i = iBegin; i < iEnd; i++) { tempx = b_data[i]; for (jj = A_i[i]; jj < A_i[i+1]; jj++) { tempx -= A_data[jj] * x_data[A_j[jj]]; } y_data[i] = tempx; } } // y = -A*x + y else { for (i = iBegin; i < iEnd; i++) { tempx = -b_data[i]; for (jj = A_i[i]; jj < A_i[i+1]; jj++) { tempx += A_data[jj] * x_data[A_j[jj]]; } y_data[i] = alpha*tempx; } } // y = alpha*(A*x - y) } // temp == -1 else if (1 == temp) { if (1 == alpha) // JSP: a common path { for (i = iBegin; i < iEnd; i++) { tempx = b_data[i]; for (jj = A_i[i]; jj < A_i[i+1]; jj++) { tempx += A_data[jj] * x_data[A_j[jj]]; } y_data[i] = tempx; } } // y = A*x + y else if (-1 == alpha) { for (i = iBegin; i < iEnd; i++) { tempx = -b_data[i]; for (jj = A_i[i]; jj < A_i[i+1]; jj++) { tempx -= A_data[jj] * x_data[A_j[jj]]; } y_data[i] = tempx; } } // y = -A*x - y else { for (i = iBegin; i < iEnd; i++) { tempx = b_data[i]; for (jj = A_i[i]; jj < A_i[i+1]; jj++) { tempx += A_data[jj] * x_data[A_j[jj]]; } y_data[i] = alpha*tempx; } } // y = alpha*(A*x + y) } else { if (1 == alpha) // JSP: a common path { for (i = iBegin; i < iEnd; i++) { tempx = b_data[i]*temp; for (jj = A_i[i]; jj < A_i[i+1]; jj++) { tempx += A_data[jj] * x_data[A_j[jj]]; } y_data[i] = tempx; } } // y = A*x + temp*y else if (-1 == alpha) { for (i = iBegin; i < iEnd; i++) { tempx = -b_data[i]*temp; for (jj = A_i[i]; jj < A_i[i+1]; jj++) { tempx -= A_data[jj] * x_data[A_j[jj]]; } y_data[i] = tempx; } } // y = -A*x - temp*y else { for (i = iBegin; i < iEnd; i++) { tempx = b_data[i]*temp; for (jj = A_i[i]; jj < A_i[i+1]; jj++) { tempx += A_data[jj] * x_data[A_j[jj]]; } y_data[i] = alpha*tempx; } } // y = alpha*(A*x + temp*y) } // temp != 0 && temp != -1 && temp != 1 } // omp parallel } if (x == y) hypre_SeqVectorDestroy(x_tmp); #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_MATVEC] += hypre_MPI_Wtime() - time_begin; #endif return ierr; } HYPRE_Int hypre_CSRMatrixMatvec( HYPRE_Complex alpha, hypre_CSRMatrix *A, hypre_Vector *x, HYPRE_Complex beta, hypre_Vector *y ) { return hypre_CSRMatrixMatvecOutOfPlace(alpha, A, x, beta, y, y, 0); } /*-------------------------------------------------------------------------- * hypre_CSRMatrixMatvecT * * This version is using a different (more efficient) threading scheme * Performs y <- alpha * A^T * x + beta * y * * From Van Henson's modification of hypre_CSRMatrixMatvec. *--------------------------------------------------------------------------*/ HYPRE_Int hypre_CSRMatrixMatvecT( HYPRE_Complex alpha, hypre_CSRMatrix *A, hypre_Vector *x, HYPRE_Complex beta, hypre_Vector *y ) { HYPRE_Complex *A_data = hypre_CSRMatrixData(A); HYPRE_Int *A_i = hypre_CSRMatrixI(A); HYPRE_Int *A_j = hypre_CSRMatrixJ(A); HYPRE_Int num_rows = hypre_CSRMatrixNumRows(A); HYPRE_Int num_cols = hypre_CSRMatrixNumCols(A); HYPRE_Complex *x_data = hypre_VectorData(x); HYPRE_Complex *y_data = hypre_VectorData(y); HYPRE_Int x_size = hypre_VectorSize(x); HYPRE_Int y_size = hypre_VectorSize(y); HYPRE_Int num_vectors = hypre_VectorNumVectors(x); HYPRE_Int idxstride_y = hypre_VectorIndexStride(y); HYPRE_Int vecstride_y = hypre_VectorVectorStride(y); HYPRE_Int idxstride_x = hypre_VectorIndexStride(x); HYPRE_Int vecstride_x = hypre_VectorVectorStride(x); HYPRE_Complex temp; HYPRE_Complex *y_data_expand; HYPRE_Int my_thread_num = 0, offset = 0; HYPRE_Int i, j, jv, jj; HYPRE_Int num_threads; HYPRE_Int ierr = 0; hypre_Vector *x_tmp = NULL; /*--------------------------------------------------------------------- * Check for size compatibility. MatvecT returns ierr = 1 if * length of X doesn't equal the number of rows of A, * ierr = 2 if the length of Y doesn't equal the number of * columns of A, and ierr = 3 if both are true. * * Because temporary vectors are often used in MatvecT, none of * these conditions terminates processing, and the ierr flag * is informational only. *--------------------------------------------------------------------*/ hypre_assert( num_vectors == hypre_VectorNumVectors(y) ); if (num_rows != x_size) ierr = 1; if (num_cols != y_size) ierr = 2; if (num_rows != x_size && num_cols != y_size) ierr = 3; /*----------------------------------------------------------------------- * Do (alpha == 0.0) computation - RDF: USE MACHINE EPS *-----------------------------------------------------------------------*/ if (alpha == 0.0) { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_cols*num_vectors; i++) y_data[i] *= beta; return ierr; } if (x == y) { x_tmp = hypre_SeqVectorCloneDeep(x); x_data = hypre_VectorData(x_tmp); } /*----------------------------------------------------------------------- * y = (beta/alpha)*y *-----------------------------------------------------------------------*/ temp = beta / alpha; if (temp != 1.0) { if (temp == 0.0) { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_cols*num_vectors; i++) y_data[i] = 0.0; } else { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_cols*num_vectors; i++) y_data[i] *= temp; } } /*----------------------------------------------------------------- * y += A^T*x *-----------------------------------------------------------------*/ num_threads = hypre_NumThreads(); if (num_threads > 1) { y_data_expand = hypre_CTAlloc(HYPRE_Complex, num_threads*y_size); if ( num_vectors==1 ) { #ifdef HYPRE_USING_OPENMP #pragma omp parallel private(i,jj,j,my_thread_num,offset) #endif { my_thread_num = hypre_GetThreadNum(); offset = y_size*my_thread_num; #ifdef HYPRE_USING_OPENMP #pragma omp for HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_rows; i++) { for (jj = A_i[i]; jj < A_i[i+1]; jj++) { j = A_j[jj]; y_data_expand[offset + j] += A_data[jj] * x_data[i]; } } /* implied barrier (for threads)*/ #ifdef HYPRE_USING_OPENMP #pragma omp for HYPRE_SMP_SCHEDULE #endif for (i = 0; i < y_size; i++) { for (j = 0; j < num_threads; j++) { y_data[i] += y_data_expand[j*y_size + i]; } } } /* end parallel threaded region */ } else { /* multiple vector case is not threaded */ for (i = 0; i < num_rows; i++) { for ( jv=0; jv<num_vectors; ++jv ) { for (jj = A_i[i]; jj < A_i[i+1]; jj++) { j = A_j[jj]; y_data[ j*idxstride_y + jv*vecstride_y ] += A_data[jj] * x_data[ i*idxstride_x + jv*vecstride_x]; } } } } hypre_TFree(y_data_expand); } else { for (i = 0; i < num_rows; i++) { if ( num_vectors==1 ) { for (jj = A_i[i]; jj < A_i[i+1]; jj++) { j = A_j[jj]; y_data[j] += A_data[jj] * x_data[i]; } } else { for ( jv=0; jv<num_vectors; ++jv ) { for (jj = A_i[i]; jj < A_i[i+1]; jj++) { j = A_j[jj]; y_data[ j*idxstride_y + jv*vecstride_y ] += A_data[jj] * x_data[ i*idxstride_x + jv*vecstride_x ]; } } } } } /*----------------------------------------------------------------- * y = alpha*y *-----------------------------------------------------------------*/ if (alpha != 1.0) { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_cols*num_vectors; i++) y_data[i] *= alpha; } if (x == y) hypre_SeqVectorDestroy(x_tmp); return ierr; } /*-------------------------------------------------------------------------- * hypre_CSRMatrixMatvec_FF *--------------------------------------------------------------------------*/ HYPRE_Int hypre_CSRMatrixMatvec_FF( HYPRE_Complex alpha, hypre_CSRMatrix *A, hypre_Vector *x, HYPRE_Complex beta, hypre_Vector *y, HYPRE_Int *CF_marker_x, HYPRE_Int *CF_marker_y, HYPRE_Int fpt ) { HYPRE_Complex *A_data = hypre_CSRMatrixData(A); HYPRE_Int *A_i = hypre_CSRMatrixI(A); HYPRE_Int *A_j = hypre_CSRMatrixJ(A); HYPRE_Int num_rows = hypre_CSRMatrixNumRows(A); HYPRE_Int num_cols = hypre_CSRMatrixNumCols(A); HYPRE_Complex *x_data = hypre_VectorData(x); HYPRE_Complex *y_data = hypre_VectorData(y); HYPRE_Int x_size = hypre_VectorSize(x); HYPRE_Int y_size = hypre_VectorSize(y); HYPRE_Complex temp; HYPRE_Int i, jj; HYPRE_Int ierr = 0; /*--------------------------------------------------------------------- * Check for size compatibility. Matvec returns ierr = 1 if * length of X doesn't equal the number of columns of A, * ierr = 2 if the length of Y doesn't equal the number of rows * of A, and ierr = 3 if both are true. * * Because temporary vectors are often used in Matvec, none of * these conditions terminates processing, and the ierr flag * is informational only. *--------------------------------------------------------------------*/ if (num_cols != x_size) ierr = 1; if (num_rows != y_size) ierr = 2; if (num_cols != x_size && num_rows != y_size) ierr = 3; /*----------------------------------------------------------------------- * Do (alpha == 0.0) computation - RDF: USE MACHINE EPS *-----------------------------------------------------------------------*/ if (alpha == 0.0) { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_rows; i++) if (CF_marker_x[i] == fpt) y_data[i] *= beta; return ierr; } /*----------------------------------------------------------------------- * y = (beta/alpha)*y *-----------------------------------------------------------------------*/ temp = beta / alpha; if (temp != 1.0) { if (temp == 0.0) { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_rows; i++) if (CF_marker_x[i] == fpt) y_data[i] = 0.0; } else { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_rows; i++) if (CF_marker_x[i] == fpt) y_data[i] *= temp; } } /*----------------------------------------------------------------- * y += A*x *-----------------------------------------------------------------*/ #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,jj) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_rows; i++) { if (CF_marker_x[i] == fpt) { temp = y_data[i]; for (jj = A_i[i]; jj < A_i[i+1]; jj++) if (CF_marker_y[A_j[jj]] == fpt) temp += A_data[jj] * x_data[A_j[jj]]; y_data[i] = temp; } } /*----------------------------------------------------------------- * y = alpha*y *-----------------------------------------------------------------*/ if (alpha != 1.0) { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_rows; i++) if (CF_marker_x[i] == fpt) y_data[i] *= alpha; } return ierr; }
24,315
30.335052
95
c
AMG
AMG-master/seq_mv/genpart.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ #include "seq_mv.h" /*-------------------------------------------------------------------------- * hypre_GeneratePartitioning: * generates load balanced partitioning of a 1-d array *--------------------------------------------------------------------------*/ /* for multivectors, length should be the (global) length of a single vector. Thus each of the vectors of the multivector will get the same data distribution. */ HYPRE_Int hypre_GeneratePartitioning(HYPRE_Int length, HYPRE_Int num_procs, HYPRE_Int **part_ptr) { HYPRE_Int ierr = 0; HYPRE_Int *part; HYPRE_Int size, rest; HYPRE_Int i; part = hypre_CTAlloc(HYPRE_Int, num_procs+1); size = length / num_procs; rest = length - size*num_procs; part[0] = 0; for (i=0; i < num_procs; i++) { part[i+1] = part[i]+size; if (i < rest) part[i+1]++; } *part_ptr = part; return ierr; } /* This function differs from the above in that it only returns the portion of the partition belonging to the individual process - to do this it requires the processor id as well AHB 6/05*/ HYPRE_Int hypre_GenerateLocalPartitioning(HYPRE_Int length, HYPRE_Int num_procs, HYPRE_Int myid, HYPRE_Int **part_ptr) { HYPRE_Int ierr = 0; HYPRE_Int *part; HYPRE_Int size, rest; part = hypre_CTAlloc(HYPRE_Int, 2); size = length /num_procs; rest = length - size*num_procs; /* first row I own */ part[0] = size*myid; part[0] += hypre_min(myid, rest); /* last row I own */ part[1] = size*(myid+1); part[1] += hypre_min(myid+1, rest); part[1] = part[1] - 1; /* add 1 to last row since this is for "starts" vector */ part[1] = part[1] + 1; *part_ptr = part; return ierr; }
2,649
28.775281
108
c
AMG
AMG-master/seq_mv/headers.h
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ #include <stdlib.h> #include <stdio.h> #include <math.h> #include "seq_mv.h"
1,007
36.333333
81
h
AMG
AMG-master/seq_mv/seq_mv.h
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ #ifndef hypre_MV_HEADER #define hypre_MV_HEADER #include <stdlib.h> #include <stdio.h> #include <math.h> #include "HYPRE_seq_mv.h" #include "../utilities/_hypre_utilities.h" #ifdef __cplusplus extern "C" { #endif /****************************************************************************** * * Header info for CSR Matrix data structures * * Note: this matrix currently uses 0-based indexing. * *****************************************************************************/ #ifndef hypre_CSR_MATRIX_HEADER #define hypre_CSR_MATRIX_HEADER /*-------------------------------------------------------------------------- * CSR Matrix *--------------------------------------------------------------------------*/ typedef struct { HYPRE_Int *i; HYPRE_Int *j; HYPRE_Int num_rows; HYPRE_Int num_cols; HYPRE_Int num_nonzeros; /* Does the CSRMatrix create/destroy `data', `i', `j'? */ HYPRE_Int owns_data; HYPRE_Complex *data; /* for compressing rows in matrix multiplication */ HYPRE_Int *rownnz; HYPRE_Int num_rownnz; } hypre_CSRMatrix; /*-------------------------------------------------------------------------- * Accessor functions for the CSR Matrix structure *--------------------------------------------------------------------------*/ #define hypre_CSRMatrixData(matrix) ((matrix) -> data) #define hypre_CSRMatrixI(matrix) ((matrix) -> i) #define hypre_CSRMatrixJ(matrix) ((matrix) -> j) #define hypre_CSRMatrixNumRows(matrix) ((matrix) -> num_rows) #define hypre_CSRMatrixNumCols(matrix) ((matrix) -> num_cols) #define hypre_CSRMatrixNumNonzeros(matrix) ((matrix) -> num_nonzeros) #define hypre_CSRMatrixRownnz(matrix) ((matrix) -> rownnz) #define hypre_CSRMatrixNumRownnz(matrix) ((matrix) -> num_rownnz) #define hypre_CSRMatrixOwnsData(matrix) ((matrix) -> owns_data) HYPRE_Int hypre_CSRMatrixGetLoadBalancedPartitionBegin( hypre_CSRMatrix *A ); HYPRE_Int hypre_CSRMatrixGetLoadBalancedPartitionEnd( hypre_CSRMatrix *A ); #endif /****************************************************************************** * * Header info for Vector data structure * *****************************************************************************/ #ifndef hypre_VECTOR_HEADER #define hypre_VECTOR_HEADER /*-------------------------------------------------------------------------- * hypre_Vector *--------------------------------------------------------------------------*/ typedef struct { HYPRE_Complex *data; HYPRE_Int size; /* Does the Vector create/destroy `data'? */ HYPRE_Int owns_data; /* For multivectors...*/ HYPRE_Int num_vectors; /* the above "size" is size of one vector */ HYPRE_Int multivec_storage_method; /* ...if 0, store colwise v0[0], v0[1], ..., v1[0], v1[1], ... v2[0]... */ /* ...if 1, store rowwise v0[0], v1[0], ..., v0[1], v1[1], ... */ /* With colwise storage, vj[i] = data[ j*size + i] With rowwise storage, vj[i] = data[ j + num_vectors*i] */ HYPRE_Int vecstride, idxstride; /* ... so vj[i] = data[ j*vecstride + i*idxstride ] regardless of row_storage.*/ } hypre_Vector; /*-------------------------------------------------------------------------- * Accessor functions for the Vector structure *--------------------------------------------------------------------------*/ #define hypre_VectorData(vector) ((vector) -> data) #define hypre_VectorSize(vector) ((vector) -> size) #define hypre_VectorOwnsData(vector) ((vector) -> owns_data) #define hypre_VectorNumVectors(vector) ((vector) -> num_vectors) #define hypre_VectorMultiVecStorageMethod(vector) ((vector) -> multivec_storage_method) #define hypre_VectorVectorStride(vector) ((vector) -> vecstride ) #define hypre_VectorIndexStride(vector) ((vector) -> idxstride ) #endif /* csr_matop.c */ hypre_CSRMatrix *hypre_CSRMatrixAdd ( hypre_CSRMatrix *A , hypre_CSRMatrix *B ); hypre_CSRMatrix *hypre_CSRMatrixMultiply ( hypre_CSRMatrix *A , hypre_CSRMatrix *B ); hypre_CSRMatrix *hypre_CSRMatrixDeleteZeros ( hypre_CSRMatrix *A , HYPRE_Real tol ); HYPRE_Int hypre_CSRMatrixTranspose ( hypre_CSRMatrix *A , hypre_CSRMatrix **AT , HYPRE_Int data ); HYPRE_Int hypre_CSRMatrixReorder ( hypre_CSRMatrix *A ); HYPRE_Complex hypre_CSRMatrixSumElts ( hypre_CSRMatrix *A ); /* csr_matrix.c */ hypre_CSRMatrix *hypre_CSRMatrixCreate ( HYPRE_Int num_rows , HYPRE_Int num_cols , HYPRE_Int num_nonzeros ); HYPRE_Int hypre_CSRMatrixDestroy ( hypre_CSRMatrix *matrix ); HYPRE_Int hypre_CSRMatrixInitialize ( hypre_CSRMatrix *matrix ); HYPRE_Int hypre_CSRMatrixSetDataOwner ( hypre_CSRMatrix *matrix , HYPRE_Int owns_data ); HYPRE_Int hypre_CSRMatrixSetRownnz ( hypre_CSRMatrix *matrix ); hypre_CSRMatrix *hypre_CSRMatrixRead ( char *file_name ); HYPRE_Int hypre_CSRMatrixPrint ( hypre_CSRMatrix *matrix , char *file_name ); HYPRE_Int hypre_CSRMatrixPrintHB ( hypre_CSRMatrix *matrix_input , char *file_name ); HYPRE_Int hypre_CSRMatrixCopy ( hypre_CSRMatrix *A , hypre_CSRMatrix *B , HYPRE_Int copy_data ); hypre_CSRMatrix *hypre_CSRMatrixClone ( hypre_CSRMatrix *A ); hypre_CSRMatrix *hypre_CSRMatrixUnion ( hypre_CSRMatrix *A , hypre_CSRMatrix *B , HYPRE_Int *col_map_offd_A , HYPRE_Int *col_map_offd_B , HYPRE_Int **col_map_offd_C ); /* csr_matvec.c */ // y[offset:end] = alpha*A[offset:end,:]*x + beta*b[offset:end] HYPRE_Int hypre_CSRMatrixMatvecOutOfPlace ( HYPRE_Complex alpha , hypre_CSRMatrix *A , hypre_Vector *x , HYPRE_Complex beta , hypre_Vector *b, hypre_Vector *y, HYPRE_Int offset ); // y = alpha*A + beta*y HYPRE_Int hypre_CSRMatrixMatvec ( HYPRE_Complex alpha , hypre_CSRMatrix *A , hypre_Vector *x , HYPRE_Complex beta , hypre_Vector *y ); HYPRE_Int hypre_CSRMatrixMatvecT ( HYPRE_Complex alpha , hypre_CSRMatrix *A , hypre_Vector *x , HYPRE_Complex beta , hypre_Vector *y ); HYPRE_Int hypre_CSRMatrixMatvec_FF ( HYPRE_Complex alpha , hypre_CSRMatrix *A , hypre_Vector *x , HYPRE_Complex beta , hypre_Vector *y , HYPRE_Int *CF_marker_x , HYPRE_Int *CF_marker_y , HYPRE_Int fpt ); /* genpart.c */ HYPRE_Int hypre_GeneratePartitioning ( HYPRE_Int length , HYPRE_Int num_procs , HYPRE_Int **part_ptr ); HYPRE_Int hypre_GenerateLocalPartitioning ( HYPRE_Int length , HYPRE_Int num_procs , HYPRE_Int myid , HYPRE_Int **part_ptr ); /* HYPRE_csr_matrix.c */ HYPRE_CSRMatrix HYPRE_CSRMatrixCreate ( HYPRE_Int num_rows , HYPRE_Int num_cols , HYPRE_Int *row_sizes ); HYPRE_Int HYPRE_CSRMatrixDestroy ( HYPRE_CSRMatrix matrix ); HYPRE_Int HYPRE_CSRMatrixInitialize ( HYPRE_CSRMatrix matrix ); HYPRE_CSRMatrix HYPRE_CSRMatrixRead ( char *file_name ); void HYPRE_CSRMatrixPrint ( HYPRE_CSRMatrix matrix , char *file_name ); HYPRE_Int HYPRE_CSRMatrixGetNumRows ( HYPRE_CSRMatrix matrix , HYPRE_Int *num_rows ); /* vector.c */ hypre_Vector *hypre_SeqVectorCreate ( HYPRE_Int size ); hypre_Vector *hypre_SeqMultiVectorCreate ( HYPRE_Int size , HYPRE_Int num_vectors ); HYPRE_Int hypre_SeqVectorDestroy ( hypre_Vector *vector ); HYPRE_Int hypre_SeqVectorInitialize ( hypre_Vector *vector ); HYPRE_Int hypre_SeqVectorSetDataOwner ( hypre_Vector *vector , HYPRE_Int owns_data ); hypre_Vector *hypre_SeqVectorRead ( char *file_name ); HYPRE_Int hypre_SeqVectorPrint ( hypre_Vector *vector , char *file_name ); HYPRE_Int hypre_SeqVectorSetConstantValues ( hypre_Vector *v , HYPRE_Complex value ); HYPRE_Int hypre_SeqVectorSetRandomValues ( hypre_Vector *v , HYPRE_Int seed ); HYPRE_Int hypre_SeqVectorCopy ( hypre_Vector *x , hypre_Vector *y ); hypre_Vector *hypre_SeqVectorCloneDeep ( hypre_Vector *x ); hypre_Vector *hypre_SeqVectorCloneShallow ( hypre_Vector *x ); HYPRE_Int hypre_SeqVectorScale ( HYPRE_Complex alpha , hypre_Vector *y ); HYPRE_Int hypre_SeqVectorAxpy ( HYPRE_Complex alpha , hypre_Vector *x , hypre_Vector *y ); HYPRE_Real hypre_SeqVectorInnerProd ( hypre_Vector *x , hypre_Vector *y ); HYPRE_Complex hypre_VectorSumElts ( hypre_Vector *vector ); #ifdef __cplusplus } #endif #endif
8,927
43.864322
203
h
AMG
AMG-master/seq_mv/vector.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /****************************************************************************** * * Member functions for hypre_Vector class. * *****************************************************************************/ #include "seq_mv.h" #include <assert.h> /*-------------------------------------------------------------------------- * hypre_SeqVectorCreate *--------------------------------------------------------------------------*/ hypre_Vector * hypre_SeqVectorCreate( HYPRE_Int size ) { hypre_Vector *vector; vector = hypre_CTAlloc(hypre_Vector, 1); hypre_VectorData(vector) = NULL; hypre_VectorSize(vector) = size; hypre_VectorNumVectors(vector) = 1; hypre_VectorMultiVecStorageMethod(vector) = 0; /* set defaults */ hypre_VectorOwnsData(vector) = 1; return vector; } /*-------------------------------------------------------------------------- * hypre_SeqMultiVectorCreate *--------------------------------------------------------------------------*/ hypre_Vector * hypre_SeqMultiVectorCreate( HYPRE_Int size, HYPRE_Int num_vectors ) { hypre_Vector *vector = hypre_SeqVectorCreate(size); hypre_VectorNumVectors(vector) = num_vectors; return vector; } /*-------------------------------------------------------------------------- * hypre_SeqVectorDestroy *--------------------------------------------------------------------------*/ HYPRE_Int hypre_SeqVectorDestroy( hypre_Vector *vector ) { HYPRE_Int ierr=0; if (vector) { if ( hypre_VectorOwnsData(vector) ) { hypre_TFree(hypre_VectorData(vector)); } hypre_TFree(vector); } return ierr; } /*-------------------------------------------------------------------------- * hypre_SeqVectorInitialize *--------------------------------------------------------------------------*/ HYPRE_Int hypre_SeqVectorInitialize( hypre_Vector *vector ) { HYPRE_Int size = hypre_VectorSize(vector); HYPRE_Int ierr = 0; HYPRE_Int num_vectors = hypre_VectorNumVectors(vector); HYPRE_Int multivec_storage_method = hypre_VectorMultiVecStorageMethod(vector); if ( ! hypre_VectorData(vector) ) hypre_VectorData(vector) = hypre_CTAlloc(HYPRE_Complex, num_vectors*size); if ( multivec_storage_method == 0 ) { hypre_VectorVectorStride(vector) = size; hypre_VectorIndexStride(vector) = 1; } else if ( multivec_storage_method == 1 ) { hypre_VectorVectorStride(vector) = 1; hypre_VectorIndexStride(vector) = num_vectors; } else ++ierr; return ierr; } /*-------------------------------------------------------------------------- * hypre_SeqVectorSetDataOwner *--------------------------------------------------------------------------*/ HYPRE_Int hypre_SeqVectorSetDataOwner( hypre_Vector *vector, HYPRE_Int owns_data ) { HYPRE_Int ierr=0; hypre_VectorOwnsData(vector) = owns_data; return ierr; } /*-------------------------------------------------------------------------- * ReadVector *--------------------------------------------------------------------------*/ hypre_Vector * hypre_SeqVectorRead( char *file_name ) { hypre_Vector *vector; FILE *fp; HYPRE_Complex *data; HYPRE_Int size; HYPRE_Int j; /*---------------------------------------------------------- * Read in the data *----------------------------------------------------------*/ fp = fopen(file_name, "r"); hypre_fscanf(fp, "%d", &size); vector = hypre_SeqVectorCreate(size); hypre_SeqVectorInitialize(vector); data = hypre_VectorData(vector); for (j = 0; j < size; j++) { hypre_fscanf(fp, "%le", &data[j]); } fclose(fp); /* multivector code not written yet >>> */ hypre_assert( hypre_VectorNumVectors(vector) == 1 ); return vector; } /*-------------------------------------------------------------------------- * hypre_SeqVectorPrint *--------------------------------------------------------------------------*/ HYPRE_Int hypre_SeqVectorPrint( hypre_Vector *vector, char *file_name ) { FILE *fp; HYPRE_Complex *data; HYPRE_Int size, num_vectors, vecstride, idxstride; HYPRE_Int i, j; HYPRE_Complex value; HYPRE_Int ierr = 0; num_vectors = hypre_VectorNumVectors(vector); vecstride = hypre_VectorVectorStride(vector); idxstride = hypre_VectorIndexStride(vector); /*---------------------------------------------------------- * Print in the data *----------------------------------------------------------*/ data = hypre_VectorData(vector); size = hypre_VectorSize(vector); fp = fopen(file_name, "w"); if ( hypre_VectorNumVectors(vector) == 1 ) { hypre_fprintf(fp, "%d\n", size); } else { hypre_fprintf(fp, "%d vectors of size %d\n", num_vectors, size ); } if ( num_vectors>1 ) { for ( j=0; j<num_vectors; ++j ) { hypre_fprintf(fp, "vector %d\n", j ); for (i = 0; i < size; i++) { value = data[ j*vecstride + i*idxstride ]; #ifdef HYPRE_COMPLEX hypre_fprintf(fp, "%.14e , %.14e\n", hypre_creal(value), hypre_cimag(value)); #else hypre_fprintf(fp, "%.14e\n", value); #endif } } } else { for (i = 0; i < size; i++) { #ifdef HYPRE_COMPLEX hypre_fprintf(fp, "%.14e , %.14e\n", hypre_creal(data[i]), hypre_cimag(data[i])); #else hypre_fprintf(fp, "%.14e\n", data[i]); #endif } } fclose(fp); return ierr; } /*-------------------------------------------------------------------------- * hypre_SeqVectorSetConstantValues *--------------------------------------------------------------------------*/ HYPRE_Int hypre_SeqVectorSetConstantValues( hypre_Vector *v, HYPRE_Complex value ) { #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_BLAS1] -= hypre_MPI_Wtime(); #endif HYPRE_Complex *vector_data = hypre_VectorData(v); HYPRE_Int size = hypre_VectorSize(v); HYPRE_Int i; HYPRE_Int ierr = 0; size *=hypre_VectorNumVectors(v); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < size; i++) vector_data[i] = value; #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_BLAS1] += hypre_MPI_Wtime(); #endif return ierr; } /*-------------------------------------------------------------------------- * hypre_SeqVectorSetRandomValues * * returns vector of values randomly distributed between -1.0 and +1.0 *--------------------------------------------------------------------------*/ HYPRE_Int hypre_SeqVectorSetRandomValues( hypre_Vector *v, HYPRE_Int seed ) { HYPRE_Complex *vector_data = hypre_VectorData(v); HYPRE_Int size = hypre_VectorSize(v); HYPRE_Int i; HYPRE_Int ierr = 0; hypre_SeedRand(seed); size *=hypre_VectorNumVectors(v); /* RDF: threading this loop may cause problems because of hypre_Rand() */ for (i = 0; i < size; i++) vector_data[i] = 2.0 * hypre_Rand() - 1.0; return ierr; } /*-------------------------------------------------------------------------- * hypre_SeqVectorCopy * copies data from x to y * if size of x is larger than y only the first size_y elements of x are * copied to y *--------------------------------------------------------------------------*/ HYPRE_Int hypre_SeqVectorCopy( hypre_Vector *x, hypre_Vector *y ) { #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_BLAS1] -= hypre_MPI_Wtime(); #endif HYPRE_Complex *x_data = hypre_VectorData(x); HYPRE_Complex *y_data = hypre_VectorData(y); HYPRE_Int size = hypre_VectorSize(x); HYPRE_Int size_y = hypre_VectorSize(y); HYPRE_Int i; HYPRE_Int ierr = 0; if (size > size_y) size = size_y; size *=hypre_VectorNumVectors(x); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < size; i++) y_data[i] = x_data[i]; #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_BLAS1] += hypre_MPI_Wtime(); #endif return ierr; } /*-------------------------------------------------------------------------- * hypre_SeqVectorCloneDeep * Returns a complete copy of x - a deep copy, with its own copy of the data. *--------------------------------------------------------------------------*/ hypre_Vector * hypre_SeqVectorCloneDeep( hypre_Vector *x ) { HYPRE_Int size = hypre_VectorSize(x); HYPRE_Int num_vectors = hypre_VectorNumVectors(x); hypre_Vector * y = hypre_SeqMultiVectorCreate( size, num_vectors ); hypre_VectorMultiVecStorageMethod(y) = hypre_VectorMultiVecStorageMethod(x); hypre_VectorVectorStride(y) = hypre_VectorVectorStride(x); hypre_VectorIndexStride(y) = hypre_VectorIndexStride(x); hypre_SeqVectorInitialize(y); hypre_SeqVectorCopy( x, y ); return y; } /*-------------------------------------------------------------------------- * hypre_SeqVectorCloneShallow * Returns a complete copy of x - a shallow copy, pointing the data of x *--------------------------------------------------------------------------*/ hypre_Vector * hypre_SeqVectorCloneShallow( hypre_Vector *x ) { HYPRE_Int size = hypre_VectorSize(x); HYPRE_Int num_vectors = hypre_VectorNumVectors(x); hypre_Vector * y = hypre_SeqMultiVectorCreate( size, num_vectors ); hypre_VectorMultiVecStorageMethod(y) = hypre_VectorMultiVecStorageMethod(x); hypre_VectorVectorStride(y) = hypre_VectorVectorStride(x); hypre_VectorIndexStride(y) = hypre_VectorIndexStride(x); hypre_VectorData(y) = hypre_VectorData(x); hypre_SeqVectorSetDataOwner( y, 0 ); hypre_SeqVectorInitialize(y); return y; } /*-------------------------------------------------------------------------- * hypre_SeqVectorScale *--------------------------------------------------------------------------*/ HYPRE_Int hypre_SeqVectorScale( HYPRE_Complex alpha, hypre_Vector *y ) { #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_BLAS1] -= hypre_MPI_Wtime(); #endif HYPRE_Complex *y_data = hypre_VectorData(y); HYPRE_Int size = hypre_VectorSize(y); HYPRE_Int i; HYPRE_Int ierr = 0; size *=hypre_VectorNumVectors(y); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < size; i++) y_data[i] *= alpha; #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_BLAS1] += hypre_MPI_Wtime(); #endif return ierr; } /*-------------------------------------------------------------------------- * hypre_SeqVectorAxpy *--------------------------------------------------------------------------*/ HYPRE_Int hypre_SeqVectorAxpy( HYPRE_Complex alpha, hypre_Vector *x, hypre_Vector *y ) { #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_BLAS1] -= hypre_MPI_Wtime(); #endif HYPRE_Complex *x_data = hypre_VectorData(x); HYPRE_Complex *y_data = hypre_VectorData(y); HYPRE_Int size = hypre_VectorSize(x); HYPRE_Int i; HYPRE_Int ierr = 0; size *=hypre_VectorNumVectors(x); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < size; i++) y_data[i] += alpha * x_data[i]; #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_BLAS1] += hypre_MPI_Wtime(); #endif return ierr; } /*-------------------------------------------------------------------------- * hypre_SeqVectorInnerProd *--------------------------------------------------------------------------*/ HYPRE_Real hypre_SeqVectorInnerProd( hypre_Vector *x, hypre_Vector *y ) { #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_BLAS1] -= hypre_MPI_Wtime(); #endif HYPRE_Complex *x_data = hypre_VectorData(x); HYPRE_Complex *y_data = hypre_VectorData(y); HYPRE_Int size = hypre_VectorSize(x); HYPRE_Int i; HYPRE_Real result = 0.0; size *=hypre_VectorNumVectors(x); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) reduction(+:result) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < size; i++) result += hypre_conj(y_data[i]) * x_data[i]; #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_BLAS1] += hypre_MPI_Wtime(); #endif return result; } /*-------------------------------------------------------------------------- * hypre_VectorSumElts: * Returns the sum of all vector elements. *--------------------------------------------------------------------------*/ HYPRE_Complex hypre_VectorSumElts( hypre_Vector *vector ) { HYPRE_Complex sum = 0; HYPRE_Complex *data = hypre_VectorData( vector ); HYPRE_Int size = hypre_VectorSize( vector ); HYPRE_Int i; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) reduction(+:sum) HYPRE_SMP_SCHEDULE #endif for ( i=0; i<size; ++i ) sum += data[i]; return sum; }
14,362
26.88932
82
c
AMG
AMG-master/seq_mv/vector.h
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /****************************************************************************** * * Header info for Vector data structure * *****************************************************************************/ #ifndef hypre_VECTOR_HEADER #define hypre_VECTOR_HEADER /*-------------------------------------------------------------------------- * hypre_Vector *--------------------------------------------------------------------------*/ typedef struct { HYPRE_Complex *data; HYPRE_Int size; /* Does the Vector create/destroy `data'? */ HYPRE_Int owns_data; /* For multivectors...*/ HYPRE_Int num_vectors; /* the above "size" is size of one vector */ HYPRE_Int multivec_storage_method; /* ...if 0, store colwise v0[0], v0[1], ..., v1[0], v1[1], ... v2[0]... */ /* ...if 1, store rowwise v0[0], v1[0], ..., v0[1], v1[1], ... */ /* With colwise storage, vj[i] = data[ j*size + i] With rowwise storage, vj[i] = data[ j + num_vectors*i] */ HYPRE_Int vecstride, idxstride; /* ... so vj[i] = data[ j*vecstride + i*idxstride ] regardless of row_storage.*/ } hypre_Vector; /*-------------------------------------------------------------------------- * Accessor functions for the Vector structure *--------------------------------------------------------------------------*/ #define hypre_VectorData(vector) ((vector) -> data) #define hypre_VectorSize(vector) ((vector) -> size) #define hypre_VectorOwnsData(vector) ((vector) -> owns_data) #define hypre_VectorNumVectors(vector) ((vector) -> num_vectors) #define hypre_VectorMultiVecStorageMethod(vector) ((vector) -> multivec_storage_method) #define hypre_VectorVectorStride(vector) ((vector) -> vecstride ) #define hypre_VectorIndexStride(vector) ((vector) -> idxstride ) #endif
2,725
41.59375
87
h
AMG
AMG-master/test/amg.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /*-------------------------------------------------------------------------- * Test driver for unstructured matrix interface (IJ_matrix interface). * Do `driver -help' for usage info. * This driver started from the driver for parcsr_linear_solvers, and it * works by first building a parcsr matrix as before and then "copying" * that matrix row-by-row into the IJMatrix interface. AJC 7/99. *--------------------------------------------------------------------------*/ #include <stdlib.h> #include <stdio.h> #include <math.h> #include "_hypre_utilities.h" #include "HYPRE.h" #include "HYPRE_parcsr_mv.h" #include "HYPRE_IJ_mv.h" #include "HYPRE_parcsr_ls.h" #include "_hypre_parcsr_mv.h" #include "HYPRE_krylov.h" #include <time.h> #ifdef __cplusplus extern "C" { #endif HYPRE_Int BuildIJLaplacian27pt (HYPRE_Int argc , char *argv [], HYPRE_Real *size , HYPRE_IJMatrix *A_ptr ); HYPRE_Int AddOrRestoreAIJ( HYPRE_IJMatrix ij_A, HYPRE_Real eps, HYPRE_Int action ); HYPRE_Int hypre_map27( HYPRE_Int ix, HYPRE_Int iy, HYPRE_Int iz, HYPRE_Int px, HYPRE_Int py, HYPRE_Int pz, HYPRE_Int Cx, HYPRE_Int Cy, HYPRE_Int Cz, HYPRE_Int nx, HYPRE_Int nxy); #ifdef __cplusplus } #endif #define SECOND_TIME 0 hypre_int main( hypre_int argc, char *argv[] ) { HYPRE_Int arg_index; HYPRE_Int print_usage; HYPRE_Int build_rhs_type; HYPRE_Int build_rhs_arg_index; HYPRE_Int build_src_type; HYPRE_Int build_src_arg_index; HYPRE_Int solver_id; HYPRE_Int problem_id; HYPRE_Int ioutdat; HYPRE_Int poutdat; HYPRE_Int debug_flag; HYPRE_Int ierr = 0; HYPRE_Int i, j; HYPRE_Int max_levels = 25; HYPRE_Int num_iterations; HYPRE_Int max_iter = 1000; HYPRE_Int mg_max_iter = 100; HYPRE_Int cum_num_its=0; HYPRE_Int nodal = 0; HYPRE_Real final_res_norm; void *object; HYPRE_IJMatrix ij_A; HYPRE_IJVector ij_b; HYPRE_IJVector ij_x; HYPRE_ParCSRMatrix parcsr_A; HYPRE_ParVector b; HYPRE_ParVector x; HYPRE_Solver amg_solver; HYPRE_Solver pcg_solver; HYPRE_Solver pcg_precond=NULL, pcg_precond_gotten; HYPRE_Int myid; HYPRE_Int *dof_func; HYPRE_Int num_functions = 1; HYPRE_Int num_paths = 1; HYPRE_Int agg_num_levels = 1; HYPRE_Int ns_coarse = 1; HYPRE_Int time_index; MPI_Comm comm = hypre_MPI_COMM_WORLD; HYPRE_Int first_local_row, last_local_row, local_num_rows; HYPRE_Int first_local_col, last_local_col, local_num_cols; HYPRE_Int time_steps = 6; /* parameters for BoomerAMG */ HYPRE_Int P_max_elmts = 8; HYPRE_Int cycle_type; HYPRE_Int coarsen_type = 8; HYPRE_Int measure_type = 0; HYPRE_Int num_sweeps = 2; HYPRE_Int relax_type = 18; HYPRE_Int rap2=1; HYPRE_Int keepTranspose = 0; HYPRE_Real tol = 1.e-8, pc_tol = 0.; HYPRE_Real atol = 0.0; HYPRE_Real wall_time; HYPRE_Real system_size; HYPRE_Real cum_nnz_AP = 0; HYPRE_Real nnz_AP; HYPRE_Real FOM1, FOM2; /* parameters for GMRES */ HYPRE_Int k_dim = 20; /* interpolation */ HYPRE_Int interp_type = 6; /* default value */ /* aggressive coarsening */ HYPRE_Int agg_interp_type = 4; /* default value */ HYPRE_Int print_system = 0; HYPRE_Int print_stats = 0; HYPRE_Int rel_change = 0; HYPRE_Real *values; /*----------------------------------------------------------- * Initialize some stuff *-----------------------------------------------------------*/ /* Initialize MPI */ hypre_MPI_Init(&argc, &argv); hypre_MPI_Comm_rank(hypre_MPI_COMM_WORLD, &myid ); /*----------------------------------------------------------- * Set defaults *-----------------------------------------------------------*/ build_rhs_type = 3; build_rhs_arg_index = argc; build_src_type = -1; build_src_arg_index = argc; debug_flag = 0; solver_id = 1; problem_id = 1; ioutdat = 0; poutdat = 0; /*----------------------------------------------------------- * Parse command line *-----------------------------------------------------------*/ print_usage = 0; arg_index = 1; while ( (arg_index < argc) && (!print_usage) ) { if ( strcmp(argv[arg_index], "-help") == 0 ) { print_usage = 1; } else { arg_index++; } } /* defaults for GMRES */ k_dim = 20; arg_index = 0; while (arg_index < argc) { if ( strcmp(argv[arg_index], "-problem") == 0 ) { arg_index++; problem_id = atoi(argv[arg_index++]); if (problem_id == 2) { solver_id = 3; } } else if ( strcmp(argv[arg_index], "-printstats") == 0 ) { arg_index++; ioutdat = 1; poutdat = 1; print_stats = 1; } else if ( strcmp(argv[arg_index], "-printallstats") == 0 ) { arg_index++; ioutdat = 3; poutdat = 1; print_stats = 1; } else if ( strcmp(argv[arg_index], "-print") == 0 ) { arg_index++; print_system = 1; } else if ( strcmp(argv[arg_index], "-keepT") == 0 ) { arg_index++; keepTranspose = 1; rap2 = 0; } else { arg_index++; } } /*----------------------------------------------------------- * Print usage info *-----------------------------------------------------------*/ if ( (print_usage) && (myid == 0) ) { hypre_printf("\n"); hypre_printf("Usage: %s [<options>]\n", argv[0]); hypre_printf("\n"); hypre_printf(" -problem <ID>: problem ID\n"); hypre_printf(" 1 = solves 1 large problem with AMG-PCG (default) \n"); hypre_printf(" 2 = simulates a time-dependent loop with AMG-GMRES\n"); hypre_printf("\n"); hypre_printf(" -n <nx> <ny> <nz>: problem size per MPI process (default: nx=ny=nz=10)\n"); hypre_printf("\n"); hypre_printf(" -P <px> <py> <pz>: processor topology (default: px=py=pz=1)\n"); hypre_printf("\n"); hypre_printf(" -print : prints the system\n"); hypre_printf(" -printstats : prints preconditioning and convergence stats\n"); hypre_printf(" -printallstats : prints preconditioning and convergence stats\n"); hypre_printf(" including residual norms for each iteration\n"); hypre_printf("\n"); exit(1); } /*----------------------------------------------------------- * Print driver parameters *-----------------------------------------------------------*/ if (myid == 0) { hypre_printf("Running with these driver parameters:\n"); hypre_printf(" solver ID = %d\n\n", solver_id); } /*----------------------------------------------------------- * Set up matrix *-----------------------------------------------------------*/ time_index = hypre_InitializeTiming("Spatial Operator"); hypre_BeginTiming(time_index); BuildIJLaplacian27pt(argc, argv, &system_size, &ij_A); HYPRE_IJMatrixGetObject(ij_A, &object); parcsr_A = (HYPRE_ParCSRMatrix) object; hypre_EndTiming(time_index); hypre_PrintTiming("Generate Matrix", &wall_time, hypre_MPI_COMM_WORLD); hypre_FinalizeTiming(time_index); hypre_ClearTiming(); /*----------------------------------------------------------- * Set up the RHS and initial guess *-----------------------------------------------------------*/ time_index = hypre_InitializeTiming("RHS and Initial Guess"); hypre_BeginTiming(time_index); ierr = HYPRE_ParCSRMatrixGetLocalRange( parcsr_A, &first_local_row, &last_local_row , &first_local_col, &last_local_col ); local_num_rows = last_local_row - first_local_row + 1; local_num_cols = last_local_col - first_local_col + 1; if (myid == 0) { hypre_printf(" RHS vector has unit components\n"); hypre_printf(" Initial guess is 0\n"); } /* RHS */ HYPRE_IJVectorCreate(hypre_MPI_COMM_WORLD, first_local_row, last_local_row, &ij_b); HYPRE_IJVectorSetObjectType(ij_b, HYPRE_PARCSR); HYPRE_IJVectorInitialize(ij_b); /* Initial guess */ HYPRE_IJVectorCreate(hypre_MPI_COMM_WORLD, first_local_col, last_local_col, &ij_x); HYPRE_IJVectorSetObjectType(ij_x, HYPRE_PARCSR); HYPRE_IJVectorInitialize(ij_x); values = hypre_CTAlloc(HYPRE_Real, local_num_rows); HYPRE_IJVectorSetValues(ij_x, local_num_rows, NULL, values); for (i = 0; i < local_num_rows; i++) values[i] = 1.0; HYPRE_IJVectorSetValues(ij_b, local_num_rows, NULL, values); hypre_TFree(values); ierr = HYPRE_IJVectorGetObject( ij_b, &object ); b = (HYPRE_ParVector) object; ierr = HYPRE_IJVectorGetObject( ij_x, &object ); x = (HYPRE_ParVector) object; hypre_EndTiming(time_index); hypre_PrintTiming("IJ Vector Setup", &wall_time, hypre_MPI_COMM_WORLD); hypre_FinalizeTiming(time_index); hypre_ClearTiming(); /*----------------------------------------------------------- * Print out the system and initial guess *-----------------------------------------------------------*/ if (print_system) { HYPRE_IJMatrixPrint(ij_A, "IJ.out.A"); HYPRE_IJVectorPrint(ij_b, "IJ.out.b"); HYPRE_IJVectorPrint(ij_x, "IJ.out.x0"); } /*----------------------------------------------------------- * Problem 1: Solve one large problem with AMG-PCG *-----------------------------------------------------------*/ if (problem_id == 1 ) { time_index = hypre_InitializeTiming("PCG Setup"); hypre_MPI_Barrier(hypre_MPI_COMM_WORLD); hypre_BeginTiming(time_index); HYPRE_ParCSRPCGCreate(hypre_MPI_COMM_WORLD, &pcg_solver); HYPRE_PCGSetMaxIter(pcg_solver, max_iter); HYPRE_PCGSetTol(pcg_solver, tol); HYPRE_PCGSetTwoNorm(pcg_solver, 1); HYPRE_PCGSetRelChange(pcg_solver, rel_change); HYPRE_PCGSetPrintLevel(pcg_solver, ioutdat); HYPRE_PCGSetAbsoluteTol(pcg_solver, atol); /* use BoomerAMG as preconditioner */ if (myid == 0 && print_stats) hypre_printf("Solver: AMG-PCG\n"); HYPRE_BoomerAMGCreate(&pcg_precond); HYPRE_BoomerAMGSetTol(pcg_precond, pc_tol); HYPRE_BoomerAMGSetCoarsenType(pcg_precond, coarsen_type); HYPRE_BoomerAMGSetPMaxElmts(pcg_precond, P_max_elmts); HYPRE_BoomerAMGSetPrintLevel(pcg_precond, poutdat); HYPRE_BoomerAMGSetMaxIter(pcg_precond, 1); HYPRE_BoomerAMGSetNumSweeps(pcg_precond, num_sweeps); if (relax_type > -1) HYPRE_BoomerAMGSetRelaxType(pcg_precond, relax_type); HYPRE_BoomerAMGSetDebugFlag(pcg_precond, debug_flag); HYPRE_BoomerAMGSetAggNumLevels(pcg_precond, agg_num_levels); HYPRE_BoomerAMGSetRAP2(pcg_precond, rap2); HYPRE_BoomerAMGSetKeepTranspose(pcg_precond, keepTranspose); HYPRE_PCGSetMaxIter(pcg_solver, mg_max_iter); HYPRE_PCGSetPrecond(pcg_solver, (HYPRE_PtrToSolverFcn) HYPRE_BoomerAMGSolve, (HYPRE_PtrToSolverFcn) HYPRE_BoomerAMGSetup, pcg_precond); HYPRE_PCGGetPrecond(pcg_solver, &pcg_precond_gotten); if (pcg_precond_gotten != pcg_precond) { hypre_printf("HYPRE_ParCSRPCGGetPrecond got bad precond\n"); return(-1); } else if (myid == 0 && print_stats) hypre_printf("HYPRE_ParCSRPCGGetPrecond got good precond\n"); HYPRE_PCGSetup(pcg_solver, (HYPRE_Matrix)parcsr_A, (HYPRE_Vector)b, (HYPRE_Vector)x); hypre_MPI_Barrier(hypre_MPI_COMM_WORLD); hypre_EndTiming(time_index); hypre_PrintTiming("Problem 1: AMG Setup Time", &wall_time, hypre_MPI_COMM_WORLD); hypre_FinalizeTiming(time_index); hypre_ClearTiming(); fflush(NULL); HYPRE_BoomerAMGGetCumNnzAP(pcg_precond, &cum_nnz_AP); FOM1 = cum_nnz_AP/ wall_time; if (myid == 0) printf ("\nFOM_Setup: nnz_AP / Setup Phase Time: %e\n\n", FOM1); time_index = hypre_InitializeTiming("PCG Solve"); hypre_MPI_Barrier(hypre_MPI_COMM_WORLD); hypre_BeginTiming(time_index); HYPRE_PCGSolve(pcg_solver, (HYPRE_Matrix)parcsr_A, (HYPRE_Vector)b, (HYPRE_Vector)x); hypre_MPI_Barrier(hypre_MPI_COMM_WORLD); hypre_EndTiming(time_index); hypre_PrintTiming("Problem 1: AMG-PCG Solve Time", &wall_time, hypre_MPI_COMM_WORLD); hypre_FinalizeTiming(time_index); hypre_ClearTiming(); fflush(NULL); HYPRE_PCGGetNumIterations(pcg_solver, &num_iterations); HYPRE_PCGGetFinalRelativeResidualNorm(pcg_solver, &final_res_norm); HYPRE_BoomerAMGDestroy(pcg_precond); HYPRE_ParCSRPCGDestroy(pcg_solver); FOM2 = cum_nnz_AP*(HYPRE_Real)num_iterations/ wall_time; if (myid == 0) { hypre_printf("\n"); hypre_printf("Iterations = %d\n", num_iterations); hypre_printf("Final Relative Residual Norm = %e\n", final_res_norm); hypre_printf("\n"); printf ("\nFOM_Solve: nnz_AP * Iterations / Solve Phase Time: %e\n\n", FOM2); FOM1 += 3.0*FOM2; FOM1 /= 4.0; printf ("\n\nFigure of Merit (FOM_1): %e\n\n", FOM1); } } /*----------------------------------------------------------- * Problem 2: simulate time-dependent problem AMG-GMRES *-----------------------------------------------------------*/ if (problem_id == 2) { HYPRE_Real eps; HYPRE_Real diagonal = 26.5; AddOrRestoreAIJ(ij_A, diagonal, 0); time_index = hypre_InitializeTiming("GMRES Solve"); hypre_MPI_Barrier(hypre_MPI_COMM_WORLD); hypre_BeginTiming(time_index); for (j=0; j < time_steps; j++) { HYPRE_ParCSRGMRESCreate(hypre_MPI_COMM_WORLD, &pcg_solver); HYPRE_GMRESSetKDim(pcg_solver, k_dim); HYPRE_GMRESSetMaxIter(pcg_solver, max_iter); HYPRE_GMRESSetTol(pcg_solver, tol); HYPRE_GMRESSetAbsoluteTol(pcg_solver, atol); HYPRE_GMRESSetLogging(pcg_solver, 1); HYPRE_GMRESSetPrintLevel(pcg_solver, ioutdat); HYPRE_GMRESSetRelChange(pcg_solver, rel_change); /* use BoomerAMG as preconditioner */ if (myid == 0 && print_stats) hypre_printf("Solver: AMG-GMRES\n"); HYPRE_BoomerAMGCreate(&pcg_precond); HYPRE_BoomerAMGSetTol(pcg_precond, pc_tol); HYPRE_BoomerAMGSetCoarsenType(pcg_precond, coarsen_type); HYPRE_BoomerAMGSetPMaxElmts(pcg_precond, P_max_elmts); HYPRE_BoomerAMGSetPrintLevel(pcg_precond, poutdat); HYPRE_BoomerAMGSetMaxIter(pcg_precond, 1); HYPRE_BoomerAMGSetNumSweeps(pcg_precond, num_sweeps); if (relax_type > -1) HYPRE_BoomerAMGSetRelaxType(pcg_precond, relax_type); HYPRE_BoomerAMGSetDebugFlag(pcg_precond, debug_flag); HYPRE_BoomerAMGSetAggNumLevels(pcg_precond, agg_num_levels); HYPRE_BoomerAMGSetRAP2(pcg_precond, rap2); HYPRE_BoomerAMGSetKeepTranspose(pcg_precond, keepTranspose); HYPRE_GMRESSetMaxIter(pcg_solver, mg_max_iter); HYPRE_GMRESSetPrecond(pcg_solver, (HYPRE_PtrToSolverFcn) HYPRE_BoomerAMGSolve, (HYPRE_PtrToSolverFcn) HYPRE_BoomerAMGSetup, pcg_precond); HYPRE_GMRESGetPrecond(pcg_solver, &pcg_precond_gotten); if (pcg_precond_gotten != pcg_precond) { hypre_printf("HYPRE_GMRESGetPrecond got bad precond\n"); return(-1); } else if (myid == 0 && print_stats) hypre_printf("HYPRE_GMRESGetPrecond got good precond\n"); HYPRE_GMRESSetup (pcg_solver, (HYPRE_Matrix)parcsr_A, (HYPRE_Vector)b, (HYPRE_Vector)x); HYPRE_BoomerAMGGetCumNnzAP(pcg_precond, &nnz_AP); cum_nnz_AP += nnz_AP; HYPRE_GMRESSolve (pcg_solver, (HYPRE_Matrix)parcsr_A, (HYPRE_Vector)b, (HYPRE_Vector)x); HYPRE_GMRESGetNumIterations(pcg_solver, &num_iterations); HYPRE_GMRESGetFinalRelativeResidualNorm(pcg_solver,&final_res_norm); if (myid == 0 && print_stats) { hypre_printf("\n"); hypre_printf("GMRES Iterations = %d\n", num_iterations); hypre_printf("Final GMRES Relative Residual Norm = %e\n", final_res_norm); hypre_printf("\n"); } cum_num_its += num_iterations; for (i=0; i < 4; i++) { HYPRE_Int gmres_iter = 6-i; eps = 0.01; AddOrRestoreAIJ(ij_A, eps, 1); HYPRE_ParVectorAxpy(eps,x,b); HYPRE_GMRESSetMaxIter(pcg_solver, gmres_iter); HYPRE_GMRESSetTol(pcg_solver, 0.0); HYPRE_GMRESSolve(pcg_solver, (HYPRE_Matrix)parcsr_A, (HYPRE_Vector)b, (HYPRE_Vector)x); HYPRE_GMRESGetNumIterations(pcg_solver, &num_iterations); HYPRE_GMRESGetFinalRelativeResidualNorm(pcg_solver,&final_res_norm); if (myid == 0 && print_stats) { hypre_printf("\n"); hypre_printf("GMRES Iterations = %d\n", num_iterations); hypre_printf("Final GMRES Relative Residual Norm = %e\n", final_res_norm); hypre_printf("\n"); } cum_num_its += num_iterations; } HYPRE_BoomerAMGDestroy(pcg_precond); HYPRE_ParCSRGMRESDestroy(pcg_solver); if (j < time_steps) { diagonal -= 0.1 ; AddOrRestoreAIJ(ij_A, diagonal, 0); HYPRE_ParVectorSetConstantValues(x,0.0); HYPRE_ParVectorSetConstantValues(b,1.0); } } hypre_MPI_Barrier(hypre_MPI_COMM_WORLD); hypre_EndTiming(time_index); hypre_PrintTiming("Problem 2: Cumulative AMG-GMRES Solve Time", &wall_time, hypre_MPI_COMM_WORLD); hypre_FinalizeTiming(time_index); hypre_ClearTiming(); if (myid == 0) { hypre_printf("\n"); hypre_printf("No. of Time Steps = %d\n", time_steps); hypre_printf("Cum. No. of Iterations = %d\n", cum_num_its); hypre_printf("Final Relative Residual Norm = %e\n", final_res_norm); hypre_printf("\n"); cum_nnz_AP /= (HYPRE_Real)time_steps; printf ("\nnnz AP * (Iterations + time_steps) / Total Time: \n"); printf ("\nFigure of Merit (FOM_2): %e\n\n", (cum_nnz_AP*(HYPRE_Real)(cum_num_its +time_steps)/ wall_time)); hypre_printf("\n"); } } /*----------------------------------------------------------- * Print the solution *-----------------------------------------------------------*/ if (print_system) { HYPRE_IJVectorPrint(ij_x, "IJ.out.x"); } /*----------------------------------------------------------- * Finalize things *-----------------------------------------------------------*/ HYPRE_IJMatrixDestroy(ij_A); HYPRE_IJVectorDestroy(ij_b); HYPRE_IJVectorDestroy(ij_x); /* hypre_FinalizeMemoryDebug(); */ hypre_MPI_Finalize(); return (0); } /*---------------------------------------------------------------------- * Build 27-point laplacian in 3D, * Parameters given in command line. *----------------------------------------------------------------------*/ HYPRE_Int BuildIJLaplacian27pt( HYPRE_Int argc, char *argv[], HYPRE_Real *system_size_ptr, HYPRE_IJMatrix *ij_A_ptr ) { MPI_Comm comm = hypre_MPI_COMM_WORLD; HYPRE_Int nx, ny, nz; HYPRE_Int P, Q, R; HYPRE_IJMatrix ij_A; HYPRE_Int num_procs, myid; HYPRE_Int px, py, pz; HYPRE_Real *value; HYPRE_Int *diag_i; HYPRE_Int *offd_i; HYPRE_Int *row_nums; HYPRE_Int *col_nums; HYPRE_Int *num_cols; HYPRE_Real *data; HYPRE_Int row_index; HYPRE_Int i; HYPRE_Int local_size; HYPRE_Real global_size; HYPRE_Int first_local_row; HYPRE_Int last_local_row; HYPRE_Int first_local_col; HYPRE_Int last_local_col; HYPRE_Int nxy; HYPRE_Int nx_global, ny_global, nz_global; HYPRE_Int all_threads; HYPRE_Int *nnz; HYPRE_Int Cx, Cy, Cz; HYPRE_Int arg_index; /*----------------------------------------------------------- * Initialize some stuff *-----------------------------------------------------------*/ hypre_MPI_Comm_size(comm, &num_procs ); hypre_MPI_Comm_rank(comm, &myid ); all_threads = hypre_NumThreads(); nnz = hypre_CTAlloc(HYPRE_Int, all_threads); /*----------------------------------------------------------- * Set defaults *-----------------------------------------------------------*/ nx = 10; ny = 10; nz = 10; P = 1; Q = num_procs; R = 1; /*----------------------------------------------------------- * Parse command line *-----------------------------------------------------------*/ arg_index = 0; while (arg_index < argc) { if ( strcmp(argv[arg_index], "-n") == 0 ) { arg_index++; nx = atoi(argv[arg_index++]); ny = atoi(argv[arg_index++]); nz = atoi(argv[arg_index++]); } else if ( strcmp(argv[arg_index], "-P") == 0 ) { arg_index++; P = atoi(argv[arg_index++]); Q = atoi(argv[arg_index++]); R = atoi(argv[arg_index++]); } else { arg_index++; } } /*----------------------------------------------------------- * Check a few things *-----------------------------------------------------------*/ if ((P*Q*R) != num_procs) { hypre_printf("Error: Invalid number of processors or processor topology \n"); exit(1); } /*----------------------------------------------------------- * Print driver parameters *-----------------------------------------------------------*/ nx_global = P*nx; ny_global = Q*ny; nz_global = R*nz; global_size = (HYPRE_Real)(nx_global*ny_global*nz_global); if (myid == 0) { hypre_printf(" Laplacian_27pt:\n"); hypre_printf(" (Nx, Ny, Nz) = (%d, %d, %d)\n", nx_global, ny_global, nz_global); hypre_printf(" (Px, Py, Pz) = (%d, %d, %d)\n\n", P, Q, R); } /*----------------------------------------------------------- * Set up the grid structure *-----------------------------------------------------------*/ /* compute px,py,pz from P,Q,R and myid */ px = myid % P; py = (( myid - px)/P) % Q; pz = ( myid - px - P*py)/( P*Q ); /*----------------------------------------------------------- * Generate the matrix *-----------------------------------------------------------*/ value = hypre_CTAlloc(HYPRE_Real, 2); value[0] = 26.0; if (nx == 1 || ny == 1 || nz == 1) value[0] = 8.0; if (nx*ny == 1 || nx*nz == 1 || ny*nz == 1) value[0] = 2.0; value[1] = -1.; local_size = nx*ny*nz; row_nums = hypre_CTAlloc(HYPRE_Int, local_size); num_cols = hypre_CTAlloc(HYPRE_Int, local_size); row_index = myid*local_size; HYPRE_IJMatrixCreate( comm, row_index, row_index+local_size-1, row_index, row_index+local_size-1, &ij_A ); HYPRE_IJMatrixSetObjectType( ij_A, HYPRE_PARCSR ); nxy = nx*ny; diag_i = hypre_CTAlloc(HYPRE_Int, local_size); offd_i = hypre_CTAlloc(HYPRE_Int, local_size); Cx = nx*(ny*nz-1); Cy = nxy*(P*nz-1); Cz = local_size*(P*Q-1); #ifdef HYPRE_USING_OPENMP #pragma omp parallel #endif { HYPRE_Int ix, iy, iz; HYPRE_Int cnt, o_cnt; HYPRE_Int ix_start, ix_end; HYPRE_Int iy_start, iy_end; HYPRE_Int iz_start, iz_end; HYPRE_Int num_threads, my_thread; HYPRE_Int all_nnz=0; HYPRE_Int size, rest; HYPRE_Int new_row_index; num_threads = hypre_NumActiveThreads(); my_thread = hypre_GetThreadNum(); size = nz/num_threads; rest = nz - size*num_threads; ix_start = nx*px; ix_end = ix_start+nx; iy_start = ny*py; iy_end = iy_start+ny; if (my_thread < rest) { iz_start = nz*pz + my_thread*size+my_thread; iz_end = nz*pz + (my_thread+1)*size+my_thread+1; cnt = (my_thread*size+my_thread)*nxy-1; } else { iz_start = nz*pz + my_thread*size+rest; iz_end = nz*pz + (my_thread+1)*size+rest; cnt = (my_thread*size+rest)*nxy-1; } o_cnt = cnt; for (iz = iz_start; iz < iz_end; iz++) { for (iy = iy_start; iy < iy_end; iy++) { for (ix = ix_start; ix < ix_end; ix++) { cnt++; o_cnt++; diag_i[cnt]++; if (iz > nz*pz) { diag_i[cnt]++; if (iy > ny*py) { diag_i[cnt]++; if (ix > nx*px) { diag_i[cnt]++; } else { if (ix) offd_i[o_cnt]++; } if (ix < nx*(px+1)-1) { diag_i[cnt]++; } else { if (ix+1 < nx_global) offd_i[o_cnt]++; } } else { if (iy) { offd_i[o_cnt]++; if (ix > nx*px) { offd_i[o_cnt]++; } else if (ix) { offd_i[o_cnt]++; } if (ix < nx*(px+1)-1) { offd_i[o_cnt]++; } else if (ix < nx_global-1) { offd_i[o_cnt]++; } } } if (ix > nx*px) diag_i[cnt]++; else { if (ix) { offd_i[o_cnt]++; } } if (ix+1 < nx*(px+1)) diag_i[cnt]++; else { if (ix+1 < nx_global) { offd_i[o_cnt]++; } } if (iy+1 < ny*(py+1)) { diag_i[cnt]++; if (ix > nx*px) { diag_i[cnt]++; } else { if (ix) offd_i[o_cnt]++; } if (ix < nx*(px+1)-1) { diag_i[cnt]++; } else { if (ix+1 < nx_global) offd_i[o_cnt]++; } } else { if (iy+1 < ny_global) { offd_i[o_cnt]++; if (ix > nx*px) { offd_i[o_cnt]++; } else if (ix) { offd_i[o_cnt]++; } if (ix < nx*(px+1)-1) { offd_i[o_cnt]++; } else if (ix < nx_global-1) { offd_i[o_cnt]++; } } } } else { if (iz) { offd_i[o_cnt]++; if (iy > ny*py) { offd_i[o_cnt]++; if (ix > nx*px) { offd_i[o_cnt]++; } else { if (ix) offd_i[o_cnt]++; } if (ix < nx*(px+1)-1) { offd_i[o_cnt]++; } else { if (ix+1 < nx_global) offd_i[o_cnt]++; } } else { if (iy) { offd_i[o_cnt]++; if (ix > nx*px) { offd_i[o_cnt]++; } else if (ix) { offd_i[o_cnt]++; } if (ix < nx*(px+1)-1) { offd_i[o_cnt]++; } else if (ix < nx_global-1) { offd_i[o_cnt]++; } } } if (ix > nx*px) offd_i[o_cnt]++; else { if (ix) { offd_i[o_cnt]++; } } if (ix+1 < nx*(px+1)) offd_i[o_cnt]++; else { if (ix+1 < nx_global) { offd_i[o_cnt]++; } } if (iy+1 < ny*(py+1)) { offd_i[o_cnt]++; if (ix > nx*px) { offd_i[o_cnt]++; } else { if (ix) offd_i[o_cnt]++; } if (ix < nx*(px+1)-1) { offd_i[o_cnt]++; } else { if (ix+1 < nx_global) offd_i[o_cnt]++; } } else { if (iy+1 < ny_global) { offd_i[o_cnt]++; if (ix > nx*px) { offd_i[o_cnt]++; } else if (ix) { offd_i[o_cnt]++; } if (ix < nx*(px+1)-1) { offd_i[o_cnt]++; } else if (ix < nx_global-1) { offd_i[o_cnt]++; } } } } } if (iy > ny*py) { diag_i[cnt]++; if (ix > nx*px) { diag_i[cnt]++; } else { if (ix) offd_i[o_cnt]++; } if (ix < nx*(px+1)-1) { diag_i[cnt]++; } else { if (ix+1 < nx_global) offd_i[o_cnt]++; } } else { if (iy) { offd_i[o_cnt]++; if (ix > nx*px) { offd_i[o_cnt]++; } else if (ix) { offd_i[o_cnt]++; } if (ix < nx*(px+1)-1) { offd_i[o_cnt]++; } else if (ix < nx_global-1) { offd_i[o_cnt]++; } } } if (ix > nx*px) diag_i[cnt]++; else { if (ix) { offd_i[o_cnt]++; } } if (ix+1 < nx*(px+1)) diag_i[cnt]++; else { if (ix+1 < nx_global) { offd_i[o_cnt]++; } } if (iy+1 < ny*(py+1)) { diag_i[cnt]++; if (ix > nx*px) { diag_i[cnt]++; } else { if (ix) offd_i[o_cnt]++; } if (ix < nx*(px+1)-1) { diag_i[cnt]++; } else { if (ix+1 < nx_global) offd_i[o_cnt]++; } } else { if (iy+1 < ny_global) { offd_i[o_cnt]++; if (ix > nx*px) { offd_i[o_cnt]++; } else if (ix) { offd_i[o_cnt]++; } if (ix < nx*(px+1)-1) { offd_i[o_cnt]++; } else if (ix < nx_global-1) { offd_i[o_cnt]++; } } } if (iz+1 < nz*(pz+1)) { diag_i[cnt]++; if (iy > ny*py) { diag_i[cnt]++; if (ix > nx*px) { diag_i[cnt]++; } else { if (ix) offd_i[o_cnt]++; } if (ix < nx*(px+1)-1) { diag_i[cnt]++; } else { if (ix+1 < nx_global) offd_i[o_cnt]++; } } else { if (iy) { offd_i[o_cnt]++; if (ix > nx*px) { offd_i[o_cnt]++; } else if (ix) { offd_i[o_cnt]++; } if (ix < nx*(px+1)-1) { offd_i[o_cnt]++; } else if (ix < nx_global-1) { offd_i[o_cnt]++; } } } if (ix > nx*px) diag_i[cnt]++; else { if (ix) { offd_i[o_cnt]++; } } if (ix+1 < nx*(px+1)) diag_i[cnt]++; else { if (ix+1 < nx_global) { offd_i[o_cnt]++; } } if (iy+1 < ny*(py+1)) { diag_i[cnt]++; if (ix > nx*px) { diag_i[cnt]++; } else { if (ix) offd_i[o_cnt]++; } if (ix < nx*(px+1)-1) { diag_i[cnt]++; } else { if (ix+1 < nx_global) offd_i[o_cnt]++; } } else { if (iy+1 < ny_global) { offd_i[o_cnt]++; if (ix > nx*px) { offd_i[o_cnt]++; } else if (ix) { offd_i[o_cnt]++; } if (ix < nx*(px+1)-1) { offd_i[o_cnt]++; } else if (ix < nx_global-1) { offd_i[o_cnt]++; } } } } else { if (iz+1 < nz_global) { offd_i[o_cnt]++; if (iy > ny*py) { offd_i[o_cnt]++; if (ix > nx*px) { offd_i[o_cnt]++; } else { if (ix) offd_i[o_cnt]++; } if (ix < nx*(px+1)-1) { offd_i[o_cnt]++; } else { if (ix+1 < nx_global) offd_i[o_cnt]++; } } else { if (iy) { offd_i[o_cnt]++; if (ix > nx*px) { offd_i[o_cnt]++; } else if (ix) { offd_i[o_cnt]++; } if (ix < nx*(px+1)-1) { offd_i[o_cnt]++; } else if (ix < nx_global-1) { offd_i[o_cnt]++; } } } if (ix > nx*px) offd_i[o_cnt]++; else { if (ix) { offd_i[o_cnt]++; } } if (ix+1 < nx*(px+1)) offd_i[o_cnt]++; else { if (ix+1 < nx_global) { offd_i[o_cnt]++; } } if (iy+1 < ny*(py+1)) { offd_i[o_cnt]++; if (ix > nx*px) { offd_i[o_cnt]++; } else { if (ix) offd_i[o_cnt]++; } if (ix < nx*(px+1)-1) { offd_i[o_cnt]++; } else { if (ix+1 < nx_global) offd_i[o_cnt]++; } } else { if (iy+1 < ny_global) { offd_i[o_cnt]++; if (ix > nx*px) { offd_i[o_cnt]++; } else if (ix) { offd_i[o_cnt]++; } if (ix < nx*(px+1)-1) { offd_i[o_cnt]++; } else if (ix < nx_global-1) { offd_i[o_cnt]++; } } } } } nnz[my_thread] += diag_i[cnt]+offd_i[o_cnt]; row_nums[cnt] = row_index+cnt; num_cols[cnt] = diag_i[cnt]+offd_i[o_cnt]; } } } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif if (my_thread == 0) { for (i=1; i< num_threads; i++) nnz[i]+= nnz[i-1]; all_nnz = nnz[num_threads-1]; col_nums = hypre_CTAlloc(HYPRE_Int, all_nnz); data = hypre_CTAlloc(HYPRE_Real, all_nnz); HYPRE_IJMatrixSetDiagOffdSizes( ij_A, diag_i, offd_i); } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif if (my_thread) { cnt = nnz[my_thread-1]; new_row_index = row_index+(iz_start-nz*pz)*nxy; } else { cnt = 0; new_row_index = row_index; } for (iz = iz_start; iz < iz_end; iz++) { for (iy = iy_start; iy < iy_end; iy++) { for (ix = ix_start; ix < ix_end; ix++) { col_nums[cnt] = new_row_index; data[cnt++] = value[0]; if (iz > nz*pz) { if (iy > ny*py) { if (ix > nx*px) { col_nums[cnt] = new_row_index-nxy-nx-1; data[cnt++] = value[1]; } else { if (ix) { col_nums[cnt] = hypre_map27(ix-1,iy-1,iz-1,px-1,py,pz, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } } col_nums[cnt] = new_row_index-nxy-nx; data[cnt++] = value[1]; if (ix < nx*(px+1)-1) { col_nums[cnt] = new_row_index-nxy-nx+1; data[cnt++] = value[1]; } else { if (ix+1 < nx_global) { col_nums[cnt] = hypre_map27(ix+1,iy-1,iz-1,px+1,py,pz, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } } } else { if (iy) { if (ix > nx*px) { col_nums[cnt] = hypre_map27(ix-1,iy-1,iz-1,px,py-1,pz, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } else if (ix) { col_nums[cnt] = hypre_map27(ix-1,iy-1,iz-1,px-1,py-1,pz, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } col_nums[cnt] = hypre_map27(ix,iy-1,iz-1,px,py-1,pz, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; if (ix < nx*(px+1)-1) { col_nums[cnt] = hypre_map27(ix+1,iy-1,iz-1,px,py-1,pz, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } else if (ix < nx_global-1) { col_nums[cnt] = hypre_map27(ix+1,iy-1,iz-1,px+1,py-1,pz, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } } } if (ix > nx*px) { col_nums[cnt] = new_row_index-nxy-1; data[cnt++] = value[1]; } else { if (ix) { col_nums[cnt] = hypre_map27(ix-1,iy,iz-1,px-1,py,pz, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } } col_nums[cnt] = new_row_index-nxy; data[cnt++] = value[1]; if (ix+1 < nx*(px+1)) { col_nums[cnt] = new_row_index-nxy+1; data[cnt++] = value[1]; } else { if (ix+1 < nx_global) { col_nums[cnt] = hypre_map27(ix+1,iy,iz-1,px+1,py,pz, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } } if (iy+1 < ny*(py+1)) { if (ix > nx*px) { col_nums[cnt] = new_row_index-nxy+nx-1; data[cnt++] = value[1]; } else { if (ix) { col_nums[cnt] = hypre_map27(ix-1,iy+1,iz-1,px-1,py,pz, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } } col_nums[cnt] = new_row_index-nxy+nx; data[cnt++] = value[1]; if (ix < nx*(px+1)-1) { col_nums[cnt] = new_row_index-nxy+nx+1; data[cnt++] = value[1]; } else { if (ix+1 < nx_global) { col_nums[cnt] = hypre_map27(ix+1,iy+1,iz-1,px+1,py,pz, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } } } else { if (iy+1 < ny_global) { if (ix > nx*px) { col_nums[cnt] = hypre_map27(ix-1,iy+1,iz-1,px,py+1,pz, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } else if (ix) { col_nums[cnt] = hypre_map27(ix-1,iy+1,iz-1,px-1,py+1,pz, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } col_nums[cnt] = hypre_map27(ix,iy+1,iz-1,px,py+1,pz, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; if (ix < nx*(px+1)-1) { col_nums[cnt] = hypre_map27(ix+1,iy+1,iz-1,px,py+1,pz, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } else if (ix < nx_global-1) { col_nums[cnt] = hypre_map27(ix+1,iy+1,iz-1,px+1,py+1,pz, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } } } } else { if (iz) { if (iy > ny*py) { if (ix > nx*px) { col_nums[cnt] = hypre_map27(ix-1,iy-1,iz-1,px,py,pz-1, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } else { if (ix) { col_nums[cnt] = hypre_map27(ix-1,iy-1,iz-1,px-1,py,pz-1, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } } col_nums[cnt] = hypre_map27(ix,iy-1,iz-1,px,py,pz-1, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; if (ix < nx*(px+1)-1) { col_nums[cnt] = hypre_map27(ix+1,iy-1,iz-1,px,py,pz-1, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } else { if (ix+1 < nx_global) { col_nums[cnt] = hypre_map27(ix+1,iy-1,iz-1,px+1,py,pz-1, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } } } else { if (iy) { if (ix > nx*px) { col_nums[cnt] = hypre_map27(ix-1,iy-1,iz-1,px,py-1,pz-1, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } else if (ix) { col_nums[cnt] =hypre_map27(ix-1,iy-1,iz-1,px-1,py-1,pz-1, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } col_nums[cnt] = hypre_map27(ix,iy-1,iz-1,px,py-1,pz-1, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; if (ix < nx*(px+1)-1) { col_nums[cnt] = hypre_map27(ix+1,iy-1,iz-1,px,py-1,pz-1, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } else if (ix < nx_global-1) { col_nums[cnt] =hypre_map27(ix+1,iy-1,iz-1,px+1,py-1,pz-1, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } } } if (ix > nx*px) { col_nums[cnt] =hypre_map27(ix-1,iy,iz-1,px,py,pz-1, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } else { if (ix) { col_nums[cnt] =hypre_map27(ix-1,iy,iz-1,px-1,py,pz-1, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } } col_nums[cnt] =hypre_map27(ix,iy,iz-1,px,py,pz-1, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; if (ix+1 < nx*(px+1)) { col_nums[cnt] =hypre_map27(ix+1,iy,iz-1,px,py,pz-1, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } else { if (ix+1 < nx_global) { col_nums[cnt] =hypre_map27(ix+1,iy,iz-1,px+1,py,pz-1, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } } if (iy+1 < ny*(py+1)) { if (ix > nx*px) { col_nums[cnt] =hypre_map27(ix-1,iy+1,iz-1,px,py,pz-1, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } else { if (ix) { col_nums[cnt] =hypre_map27(ix-1,iy+1,iz-1,px-1,py,pz-1, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } } col_nums[cnt] =hypre_map27(ix,iy+1,iz-1,px,py,pz-1, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; if (ix < nx*(px+1)-1) { col_nums[cnt] =hypre_map27(ix+1,iy+1,iz-1,px,py,pz-1, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } else { if (ix+1 < nx_global) { col_nums[cnt] =hypre_map27(ix+1,iy+1,iz-1,px+1,py,pz-1, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } } } else { if (iy+1 < ny_global) { if (ix > nx*px) { col_nums[cnt] =hypre_map27(ix-1,iy+1,iz-1,px,py+1,pz-1, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } else if (ix) { col_nums[cnt] =hypre_map27(ix-1,iy+1,iz-1,px-1,py+1,pz-1, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } col_nums[cnt] =hypre_map27(ix,iy+1,iz-1,px,py+1,pz-1, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; if (ix < nx*(px+1)-1) { col_nums[cnt] =hypre_map27(ix+1,iy+1,iz-1,px,py+1,pz-1, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } else if (ix < nx_global-1) { col_nums[cnt] =hypre_map27(ix+1,iy+1,iz-1,px+1,py+1,pz-1, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } } } } } if (iy > ny*py) { if (ix > nx*px) { col_nums[cnt] = new_row_index-nx-1; data[cnt++] = value[1]; } else { if (ix) { col_nums[cnt] =hypre_map27(ix-1,iy-1,iz,px-1,py,pz, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } } col_nums[cnt] = new_row_index-nx; data[cnt++] = value[1]; if (ix < nx*(px+1)-1) { col_nums[cnt] = new_row_index-nx+1; data[cnt++] = value[1]; } else { if (ix+1 < nx_global) { col_nums[cnt] =hypre_map27(ix+1,iy-1,iz,px+1,py,pz, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } } } else { if (iy) { if (ix > nx*px) { col_nums[cnt] =hypre_map27(ix-1,iy-1,iz,px,py-1,pz, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } else if (ix) { col_nums[cnt] =hypre_map27(ix-1,iy-1,iz,px-1,py-1,pz, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } col_nums[cnt] =hypre_map27(ix,iy-1,iz,px,py-1,pz, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; if (ix < nx*(px+1)-1) { col_nums[cnt] =hypre_map27(ix+1,iy-1,iz,px,py-1,pz, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } else if (ix < nx_global-1) { col_nums[cnt] =hypre_map27(ix+1,iy-1,iz,px+1,py-1,pz, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } } } if (ix > nx*px) { col_nums[cnt] = new_row_index-1; data[cnt++] = value[1]; } else { if (ix) { col_nums[cnt] =hypre_map27(ix-1,iy,iz,px-1,py,pz, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } } if (ix+1 < nx*(px+1)) { col_nums[cnt] = new_row_index+1; data[cnt++] = value[1]; } else { if (ix+1 < nx_global) { col_nums[cnt] =hypre_map27(ix+1,iy,iz,px+1,py,pz, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } } if (iy+1 < ny*(py+1)) { if (ix > nx*px) { col_nums[cnt] = new_row_index+nx-1; data[cnt++] = value[1]; } else { if (ix) { col_nums[cnt] =hypre_map27(ix-1,iy+1,iz,px-1,py,pz, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } } col_nums[cnt] = new_row_index+nx; data[cnt++] = value[1]; if (ix < nx*(px+1)-1) { col_nums[cnt] = new_row_index+nx+1; data[cnt++] = value[1]; } else { if (ix+1 < nx_global) { col_nums[cnt] =hypre_map27(ix+1,iy+1,iz,px+1,py,pz, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } } } else { if (iy+1 < ny_global) { if (ix > nx*px) { col_nums[cnt] =hypre_map27(ix-1,iy+1,iz,px,py+1,pz, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } else if (ix) { col_nums[cnt] =hypre_map27(ix-1,iy+1,iz,px-1,py+1,pz, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } col_nums[cnt] =hypre_map27(ix,iy+1,iz,px,py+1,pz, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; if (ix < nx*(px+1)-1) { col_nums[cnt] =hypre_map27(ix+1,iy+1,iz,px,py+1,pz, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } else if (ix < nx_global-1) { col_nums[cnt] =hypre_map27(ix+1,iy+1,iz,px+1,py+1,pz, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } } } if (iz+1 < nz*(pz+1)) { if (iy > ny*py) { if (ix > nx*px) { col_nums[cnt] = new_row_index+nxy-nx-1; data[cnt++] = value[1]; } else { if (ix) { col_nums[cnt] =hypre_map27(ix-1,iy-1,iz+1,px-1,py,pz, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } } col_nums[cnt] = new_row_index+nxy-nx; data[cnt++] = value[1]; if (ix < nx*(px+1)-1) { col_nums[cnt] = new_row_index+nxy-nx+1; data[cnt++] = value[1]; } else { if (ix+1 < nx_global) { col_nums[cnt] =hypre_map27(ix+1,iy-1,iz+1,px+1,py,pz, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } } } else { if (iy) { if (ix > nx*px) { col_nums[cnt] =hypre_map27(ix-1,iy-1,iz+1,px,py-1,pz, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } else if (ix) { col_nums[cnt] =hypre_map27(ix-1,iy-1,iz+1,px-1,py-1,pz, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } col_nums[cnt] =hypre_map27(ix,iy-1,iz+1,px,py-1,pz, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; if (ix < nx*(px+1)-1) { col_nums[cnt] =hypre_map27(ix+1,iy-1,iz+1,px,py-1,pz, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } else if (ix < nx_global-1) { col_nums[cnt] =hypre_map27(ix+1,iy-1,iz+1,px+1,py-1,pz, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } } } if (ix > nx*px) { col_nums[cnt] = new_row_index+nxy-1; data[cnt++] = value[1]; } else { if (ix) { col_nums[cnt] =hypre_map27(ix-1,iy,iz+1,px-1,py,pz, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } } col_nums[cnt] = new_row_index+nxy; data[cnt++] = value[1]; if (ix+1 < nx*(px+1)) { col_nums[cnt] = new_row_index+nxy+1; data[cnt++] = value[1]; } else { if (ix+1 < nx_global) { col_nums[cnt] =hypre_map27(ix+1,iy,iz+1,px+1,py,pz, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } } if (iy+1 < ny*(py+1)) { if (ix > nx*px) { col_nums[cnt] = new_row_index+nxy+nx-1; data[cnt++] = value[1]; } else { if (ix) { col_nums[cnt] =hypre_map27(ix-1,iy+1,iz+1,px-1,py,pz, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } } col_nums[cnt] = new_row_index+nxy+nx; data[cnt++] = value[1]; if (ix < nx*(px+1)-1) { col_nums[cnt] = new_row_index+nxy+nx+1; data[cnt++] = value[1]; } else { if (ix+1 < nx_global) { col_nums[cnt] =hypre_map27(ix+1,iy+1,iz+1,px+1,py,pz, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } } } else { if (iy+1 < ny_global) { if (ix > nx*px) { col_nums[cnt] =hypre_map27(ix-1,iy+1,iz+1,px,py+1,pz, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } else if (ix) { col_nums[cnt] =hypre_map27(ix-1,iy+1,iz+1,px-1,py+1,pz, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } col_nums[cnt] =hypre_map27(ix,iy+1,iz+1,px,py+1,pz, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; if (ix < nx*(px+1)-1) { col_nums[cnt] =hypre_map27(ix+1,iy+1,iz+1,px,py+1,pz, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } else if (ix < nx_global-1) { col_nums[cnt] =hypre_map27(ix+1,iy+1,iz+1,px+1,py+1,pz, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } } } } else { if (iz+1 < nz_global) { if (iy > ny*py) { if (ix > nx*px) { col_nums[cnt] =hypre_map27(ix-1,iy-1,iz+1,px,py,pz+1, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } else { if (ix) { col_nums[cnt] =hypre_map27(ix-1,iy-1,iz+1,px-1,py,pz+1, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } } col_nums[cnt] =hypre_map27(ix,iy-1,iz+1,px,py,pz+1, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; if (ix < nx*(px+1)-1) { col_nums[cnt] =hypre_map27(ix+1,iy-1,iz+1,px,py,pz+1, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } else { if (ix+1 < nx_global) { col_nums[cnt] =hypre_map27(ix+1,iy-1,iz+1,px+1,py,pz+1, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } } } else { if (iy) { if (ix > nx*px) { col_nums[cnt] =hypre_map27(ix-1,iy-1,iz+1,px,py-1,pz+1, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } else if (ix) { col_nums[cnt] =hypre_map27(ix-1,iy-1,iz+1,px-1,py-1,pz+1, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } col_nums[cnt] =hypre_map27(ix,iy-1,iz+1,px,py-1,pz+1, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; if (ix < nx*(px+1)-1) { col_nums[cnt] =hypre_map27(ix+1,iy-1,iz+1,px,py-1,pz+1, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } else if (ix < nx_global-1) { col_nums[cnt] =hypre_map27(ix+1,iy-1,iz+1,px+1,py-1,pz+1, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } } } if (ix > nx*px) { col_nums[cnt] =hypre_map27(ix-1,iy,iz+1,px,py,pz+1, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } else { if (ix) { col_nums[cnt] =hypre_map27(ix-1,iy,iz+1,px-1,py,pz+1, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } } col_nums[cnt] =hypre_map27(ix,iy,iz+1,px,py,pz+1, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; if (ix+1 < nx*(px+1)) { col_nums[cnt] =hypre_map27(ix+1,iy,iz+1,px,py,pz+1, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } else { if (ix+1 < nx_global) { col_nums[cnt] =hypre_map27(ix+1,iy,iz+1,px+1,py,pz+1, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } } if (iy+1 < ny*(py+1)) { if (ix > nx*px) { col_nums[cnt] =hypre_map27(ix-1,iy+1,iz+1,px,py,pz+1, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } else { if (ix) { col_nums[cnt] =hypre_map27(ix-1,iy+1,iz+1,px-1,py,pz+1, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } } col_nums[cnt] =hypre_map27(ix,iy+1,iz+1,px,py,pz+1, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; if (ix < nx*(px+1)-1) { col_nums[cnt] =hypre_map27(ix+1,iy+1,iz+1,px,py,pz+1, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } else { if (ix+1 < nx_global) { col_nums[cnt] =hypre_map27(ix+1,iy+1,iz+1,px+1,py,pz+1, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } } } else { if (iy+1 < ny_global) { if (ix > nx*px) { col_nums[cnt] =hypre_map27(ix-1,iy+1,iz+1,px,py+1,pz+1, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } else if (ix) { col_nums[cnt] =hypre_map27(ix-1,iy+1,iz+1,px-1,py+1,pz+1, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } col_nums[cnt] =hypre_map27(ix,iy+1,iz+1,px,py+1,pz+1, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; if (ix < nx*(px+1)-1) { col_nums[cnt] =hypre_map27(ix+1,iy+1,iz+1,px,py+1,pz+1, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } else if (ix < nx_global-1) { col_nums[cnt] =hypre_map27(ix+1,iy+1,iz+1,px+1,py+1,pz+1, Cx,Cy,Cz,nx,nxy); data[cnt++] = value[1]; } } } } } new_row_index++; } } } } /*end parallel loop */ HYPRE_IJMatrixInitialize(ij_A); HYPRE_IJMatrixSetOMPFlag(ij_A, 1); HYPRE_IJMatrixSetValues(ij_A, local_size, num_cols, row_nums, col_nums, data); HYPRE_IJMatrixAssemble(ij_A); /*A = (HYPRE_ParCSRMatrix) GenerateLaplacian27pt(hypre_MPI_COMM_WORLD, nx, ny, nz, P, Q, R, px, py, r, values);*/ hypre_TFree(diag_i); hypre_TFree(offd_i); hypre_TFree(num_cols); hypre_TFree(col_nums); hypre_TFree(row_nums); hypre_TFree(data); hypre_TFree(value); hypre_TFree(nnz); *system_size_ptr = global_size; *ij_A_ptr = ij_A; return (0); } /*---------------------------------------------------------------------- * Add epsilon to diagonal of A *----------------------------------------------------------------------*/ HYPRE_Int AddOrRestoreAIJ( HYPRE_IJMatrix ij_A, HYPRE_Real eps, HYPRE_Int action ) { HYPRE_Int first_row, last_row, i; HYPRE_Int first_col, last_col, local_size; HYPRE_Int *num_cols; HYPRE_Int *row_nums; HYPRE_Int *col_nums; HYPRE_Real *data; HYPRE_IJMatrixGetLocalRange(ij_A, &first_row, &last_row, &first_col, &last_col); local_size = last_row-first_row+1; num_cols = hypre_CTAlloc(HYPRE_Int, local_size); row_nums = hypre_CTAlloc(HYPRE_Int, local_size); col_nums = hypre_CTAlloc(HYPRE_Int, local_size); data = hypre_CTAlloc(HYPRE_Real, local_size); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i=0; i < local_size; i++) { num_cols[i] = 1; row_nums[i] = first_row+i; col_nums[i] = first_row+i; data[i] = eps; } if (action) HYPRE_IJMatrixAddToValues(ij_A, local_size, num_cols, row_nums, col_nums, data); else HYPRE_IJMatrixSetValues(ij_A, local_size, num_cols, row_nums, col_nums, data); HYPRE_IJMatrixAssemble(ij_A); return(0); } HYPRE_Int hypre_map27( HYPRE_Int ix, HYPRE_Int iy, HYPRE_Int iz, HYPRE_Int px, HYPRE_Int py, HYPRE_Int pz, HYPRE_Int Cx, HYPRE_Int Cy, HYPRE_Int Cz, HYPRE_Int nx, HYPRE_Int nxy) { HYPRE_Int global_index = pz*Cz + py*Cy +px*Cx + iz*nxy + iy*nx + ix; return global_index; }
72,432
29.848807
117
c
AMG
AMG-master/utilities/HYPRE_error_f.h
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ c Copyright (c) 2008, Lawrence Livermore National Security, LLC. c Produced at the Lawrence Livermore National Laboratory. c This file is part of HYPRE. See file COPYRIGHT for details. c c HYPRE is free software; you can redistribute it and/or modify it under the c terms of the GNU Lesser General Public License (as published by the Free c Software Foundation) version 2.1 dated February 1999. c c $Revision$ integer HYPRE_ERROR_GENERIC integer HYPRE_ERROR_MEMORY integer HYPRE_ERROR_ARG integer HYPRE_ERROR_CONV parameter (HYPRE_ERROR_GENERIC = 1) parameter (HYPRE_ERROR_MEMORY = 2) parameter (HYPRE_ERROR_ARG = 4) parameter (HYPRE_ERROR_CONV = 256)
1,635
45.742857
81
h
AMG
AMG-master/utilities/HYPRE_utilities.h
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /****************************************************************************** * * Header file for HYPRE_utilities library * *****************************************************************************/ #include "HYPRE.h" #ifndef HYPRE_UTILITIES_HEADER #define HYPRE_UTILITIES_HEADER #ifndef HYPRE_SEQUENTIAL #include "mpi.h" #endif #ifdef HYPRE_USING_OPENMP #include <omp.h> #endif #ifdef __cplusplus extern "C" { #endif /* * Before a version of HYPRE goes out the door, increment the version * number and check in this file (for CVS to substitute the Date). */ #define HYPRE_Version() "HYPRE_RELEASE_NAME Date Compiled: " __DATE__ " " __TIME__ /*-------------------------------------------------------------------------- * Real and Complex types *--------------------------------------------------------------------------*/ #include <float.h> #if defined(HYPRE_SINGLE) typedef float HYPRE_Real; #define HYPRE_REAL_MAX FLT_MAX #define HYPRE_REAL_MIN FLT_MIN #define HYPRE_REAL_EPSILON FLT_EPSILON #define HYPRE_REAL_MIN_EXP FLT_MIN_EXP #define HYPRE_MPI_REAL MPI_FLOAT #elif defined(HYPRE_LONG_DOUBLE) typedef long double HYPRE_Real; #define HYPRE_REAL_MAX LDBL_MAX #define HYPRE_REAL_MIN LDBL_MIN #define HYPRE_REAL_EPSILON LDBL_EPSILON #define HYPRE_REAL_MIN_EXP DBL_MIN_EXP #define HYPRE_MPI_REAL MPI_LONG_DOUBLE #else /* default */ typedef double HYPRE_Real; #define HYPRE_REAL_MAX DBL_MAX #define HYPRE_REAL_MIN DBL_MIN #define HYPRE_REAL_EPSILON DBL_EPSILON #define HYPRE_REAL_MIN_EXP DBL_MIN_EXP #define HYPRE_MPI_REAL MPI_DOUBLE #endif #if defined(HYPRE_COMPLEX) typedef double _Complex HYPRE_Complex; #define HYPRE_MPI_COMPLEX MPI_C_DOUBLE_COMPLEX /* or MPI_LONG_DOUBLE ? */ #else /* default */ typedef HYPRE_Real HYPRE_Complex; #define HYPRE_MPI_COMPLEX HYPRE_MPI_REAL #endif /*-------------------------------------------------------------------------- * Sequential MPI stuff *--------------------------------------------------------------------------*/ #ifdef HYPRE_SEQUENTIAL typedef HYPRE_Int MPI_Comm; #endif /*-------------------------------------------------------------------------- * HYPRE error codes *--------------------------------------------------------------------------*/ #define HYPRE_ERROR_GENERIC 1 /* generic error */ #define HYPRE_ERROR_MEMORY 2 /* unable to allocate memory */ #define HYPRE_ERROR_ARG 4 /* argument error */ /* bits 4-8 are reserved for the index of the argument error */ #define HYPRE_ERROR_CONV 256 /* method did not converge as expected */ /*-------------------------------------------------------------------------- * HYPRE error user functions *--------------------------------------------------------------------------*/ /* Return the current hypre error flag */ HYPRE_Int HYPRE_GetError(); /* Check if the given error flag contains the given error code */ HYPRE_Int HYPRE_CheckError(HYPRE_Int hypre_ierr, HYPRE_Int hypre_error_code); /* Return the index of the argument (counting from 1) where argument error (HYPRE_ERROR_ARG) has occured */ HYPRE_Int HYPRE_GetErrorArg(); /* Describe the given error flag in the given string */ void HYPRE_DescribeError(HYPRE_Int hypre_ierr, char *descr); /* Clears the hypre error flag */ HYPRE_Int HYPRE_ClearAllErrors(); /* Clears the given error code from the hypre error flag */ HYPRE_Int HYPRE_ClearError(HYPRE_Int hypre_error_code); /*-------------------------------------------------------------------------- * HYPRE AP user functions *--------------------------------------------------------------------------*/ /*Checks whether the AP is on */ HYPRE_Int HYPRE_AssumedPartitionCheck(); #ifdef __cplusplus } #endif #endif
4,644
32.178571
82
h
AMG
AMG-master/utilities/_hypre_utilities.h
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ #ifndef hypre_UTILITIES_HEADER #define hypre_UTILITIES_HEADER #include "HYPRE_utilities.h" #ifdef HYPRE_USING_OPENMP #include <omp.h> #endif /* This allows us to consistently avoid 'int' throughout hypre */ typedef int hypre_int; typedef long int hypre_longint; typedef unsigned int hypre_uint; typedef unsigned long int hypre_ulongint; /* This allows us to consistently avoid 'double' throughout hypre */ typedef double hypre_double; #ifdef __cplusplus extern "C" { #endif /****************************************************************************** * * General structures and values * *****************************************************************************/ #ifndef hypre_GENERAL_HEADER #define hypre_GENERAL_HEADER /*-------------------------------------------------------------------------- * Define various functions *--------------------------------------------------------------------------*/ #ifndef hypre_max #define hypre_max(a,b) (((a)<(b)) ? (b) : (a)) #endif #ifndef hypre_min #define hypre_min(a,b) (((a)<(b)) ? (a) : (b)) #endif #ifndef hypre_abs #define hypre_abs(a) (((a)>0) ? (a) : -(a)) #endif #ifndef hypre_round #define hypre_round(x) ( ((x) < 0.0) ? ((HYPRE_Int)(x - 0.5)) : ((HYPRE_Int)(x + 0.5)) ) #endif #ifndef hypre_pow2 #define hypre_pow2(i) ( 1 << (i) ) #endif #endif /****************************************************************************** * * Fake mpi stubs to generate serial codes without mpi * *****************************************************************************/ #ifndef hypre_MPISTUBS #define hypre_MPISTUBS #ifdef __cplusplus extern "C" { #endif #ifdef HYPRE_SEQUENTIAL /****************************************************************************** * MPI stubs to generate serial codes without mpi *****************************************************************************/ /*-------------------------------------------------------------------------- * Change all MPI names to hypre_MPI names to avoid link conflicts. * * NOTE: MPI_Comm is the only MPI symbol in the HYPRE user interface, * and is defined in `HYPRE_utilities.h'. *--------------------------------------------------------------------------*/ #define MPI_Comm hypre_MPI_Comm #define MPI_Group hypre_MPI_Group #define MPI_Request hypre_MPI_Request #define MPI_Datatype hypre_MPI_Datatype #define MPI_Status hypre_MPI_Status #define MPI_Op hypre_MPI_Op #define MPI_Aint hypre_MPI_Aint #define MPI_COMM_WORLD hypre_MPI_COMM_WORLD #define MPI_COMM_NULL hypre_MPI_COMM_NULL #define MPI_COMM_SELF hypre_MPI_COMM_SELF #define MPI_BOTTOM hypre_MPI_BOTTOM #define MPI_FLOAT hypre_MPI_FLOAT #define MPI_DOUBLE hypre_MPI_DOUBLE #define MPI_LONG_DOUBLE hypre_MPI_LONG_DOUBLE #define MPI_INT hypre_MPI_INT #define MPI_LONG_LONG_INT hypre_MPI_INT #define MPI_CHAR hypre_MPI_CHAR #define MPI_LONG hypre_MPI_LONG #define MPI_BYTE hypre_MPI_BYTE #define MPI_C_DOUBLE_COMPLEX hypre_MPI_COMPLEX #define MPI_SUM hypre_MPI_SUM #define MPI_MIN hypre_MPI_MIN #define MPI_MAX hypre_MPI_MAX #define MPI_LOR hypre_MPI_LOR #define MPI_SUCCESS hypre_MPI_SUCCESS #define MPI_STATUSES_IGNORE hypre_MPI_STATUSES_IGNORE #define MPI_UNDEFINED hypre_MPI_UNDEFINED #define MPI_REQUEST_NULL hypre_MPI_REQUEST_NULL #define MPI_ANY_SOURCE hypre_MPI_ANY_SOURCE #define MPI_ANY_TAG hypre_MPI_ANY_TAG #define MPI_SOURCE hypre_MPI_SOURCE #define MPI_TAG hypre_MPI_TAG #define MPI_Init hypre_MPI_Init #define MPI_Finalize hypre_MPI_Finalize #define MPI_Abort hypre_MPI_Abort #define MPI_Wtime hypre_MPI_Wtime #define MPI_Wtick hypre_MPI_Wtick #define MPI_Barrier hypre_MPI_Barrier #define MPI_Comm_create hypre_MPI_Comm_create #define MPI_Comm_dup hypre_MPI_Comm_dup #define MPI_Comm_f2c hypre_MPI_Comm_f2c #define MPI_Comm_group hypre_MPI_Comm_group #define MPI_Comm_size hypre_MPI_Comm_size #define MPI_Comm_rank hypre_MPI_Comm_rank #define MPI_Comm_free hypre_MPI_Comm_free #define MPI_Comm_split hypre_MPI_Comm_split #define MPI_Group_incl hypre_MPI_Group_incl #define MPI_Group_free hypre_MPI_Group_free #define MPI_Address hypre_MPI_Address #define MPI_Get_count hypre_MPI_Get_count #define MPI_Alltoall hypre_MPI_Alltoall #define MPI_Allgather hypre_MPI_Allgather #define MPI_Allgatherv hypre_MPI_Allgatherv #define MPI_Gather hypre_MPI_Gather #define MPI_Gatherv hypre_MPI_Gatherv #define MPI_Scatter hypre_MPI_Scatter #define MPI_Scatterv hypre_MPI_Scatterv #define MPI_Bcast hypre_MPI_Bcast #define MPI_Send hypre_MPI_Send #define MPI_Recv hypre_MPI_Recv #define MPI_Isend hypre_MPI_Isend #define MPI_Irecv hypre_MPI_Irecv #define MPI_Send_init hypre_MPI_Send_init #define MPI_Recv_init hypre_MPI_Recv_init #define MPI_Irsend hypre_MPI_Irsend #define MPI_Startall hypre_MPI_Startall #define MPI_Probe hypre_MPI_Probe #define MPI_Iprobe hypre_MPI_Iprobe #define MPI_Test hypre_MPI_Test #define MPI_Testall hypre_MPI_Testall #define MPI_Wait hypre_MPI_Wait #define MPI_Waitall hypre_MPI_Waitall #define MPI_Waitany hypre_MPI_Waitany #define MPI_Allreduce hypre_MPI_Allreduce #define MPI_Reduce hypre_MPI_Reduce #define MPI_Scan hypre_MPI_Scan #define MPI_Request_free hypre_MPI_Request_free #define MPI_Type_contiguous hypre_MPI_Type_contiguous #define MPI_Type_vector hypre_MPI_Type_vector #define MPI_Type_hvector hypre_MPI_Type_hvector #define MPI_Type_struct hypre_MPI_Type_struct #define MPI_Type_commit hypre_MPI_Type_commit #define MPI_Type_free hypre_MPI_Type_free #define MPI_Op_free hypre_MPI_Op_free #define MPI_Op_create hypre_MPI_Op_create #define MPI_User_function hypre_MPI_User_function /*-------------------------------------------------------------------------- * Types, etc. *--------------------------------------------------------------------------*/ /* These types have associated creation and destruction routines */ typedef HYPRE_Int hypre_MPI_Comm; typedef HYPRE_Int hypre_MPI_Group; typedef HYPRE_Int hypre_MPI_Request; typedef HYPRE_Int hypre_MPI_Datatype; typedef void (hypre_MPI_User_function) (); typedef struct { HYPRE_Int hypre_MPI_SOURCE; HYPRE_Int hypre_MPI_TAG; } hypre_MPI_Status; typedef HYPRE_Int hypre_MPI_Op; typedef HYPRE_Int hypre_MPI_Aint; #define hypre_MPI_COMM_SELF 1 #define hypre_MPI_COMM_WORLD 0 #define hypre_MPI_COMM_NULL -1 #define hypre_MPI_BOTTOM 0x0 #define hypre_MPI_FLOAT 0 #define hypre_MPI_DOUBLE 1 #define hypre_MPI_LONG_DOUBLE 2 #define hypre_MPI_INT 3 #define hypre_MPI_CHAR 4 #define hypre_MPI_LONG 5 #define hypre_MPI_BYTE 6 #define hypre_MPI_REAL 7 #define hypre_MPI_COMPLEX 8 #define hypre_MPI_SUM 0 #define hypre_MPI_MIN 1 #define hypre_MPI_MAX 2 #define hypre_MPI_LOR 3 #define hypre_MPI_SUCCESS 0 #define hypre_MPI_STATUSES_IGNORE 0 #define hypre_MPI_UNDEFINED -9999 #define hypre_MPI_REQUEST_NULL 0 #define hypre_MPI_ANY_SOURCE 1 #define hypre_MPI_ANY_TAG 1 #else /****************************************************************************** * MPI stubs to do casting of HYPRE_Int and hypre_int correctly *****************************************************************************/ typedef MPI_Comm hypre_MPI_Comm; typedef MPI_Group hypre_MPI_Group; typedef MPI_Request hypre_MPI_Request; typedef MPI_Datatype hypre_MPI_Datatype; typedef MPI_Status hypre_MPI_Status; typedef MPI_Op hypre_MPI_Op; typedef MPI_Aint hypre_MPI_Aint; typedef MPI_User_function hypre_MPI_User_function; #define hypre_MPI_COMM_WORLD MPI_COMM_WORLD #define hypre_MPI_COMM_NULL MPI_COMM_NULL #define hypre_MPI_BOTTOM MPI_BOTTOM #define hypre_MPI_COMM_SELF MPI_COMM_SELF #define hypre_MPI_FLOAT MPI_FLOAT #define hypre_MPI_DOUBLE MPI_DOUBLE #define hypre_MPI_LONG_DOUBLE MPI_LONG_DOUBLE /* HYPRE_MPI_INT is defined in HYPRE_utilities.h */ #define hypre_MPI_INT HYPRE_MPI_INT #define hypre_MPI_CHAR MPI_CHAR #define hypre_MPI_LONG MPI_LONG #define hypre_MPI_BYTE MPI_BYTE /* HYPRE_MPI_REAL is defined in HYPRE_utilities.h */ #define hypre_MPI_REAL HYPRE_MPI_REAL /* HYPRE_MPI_COMPLEX is defined in HYPRE_utilities.h */ #define hypre_MPI_COMPLEX HYPRE_MPI_COMPLEX #define hypre_MPI_SUM MPI_SUM #define hypre_MPI_MIN MPI_MIN #define hypre_MPI_MAX MPI_MAX #define hypre_MPI_LOR MPI_LOR #define hypre_MPI_SUCCESS MPI_SUCCESS #define hypre_MPI_STATUSES_IGNORE MPI_STATUSES_IGNORE #define hypre_MPI_UNDEFINED MPI_UNDEFINED #define hypre_MPI_REQUEST_NULL MPI_REQUEST_NULL #define hypre_MPI_ANY_SOURCE MPI_ANY_SOURCE #define hypre_MPI_ANY_TAG MPI_ANY_TAG #define hypre_MPI_SOURCE MPI_SOURCE #define hypre_MPI_TAG MPI_TAG #define hypre_MPI_LAND MPI_LAND #endif /****************************************************************************** * Everything below this applies to both ifdef cases above *****************************************************************************/ /*-------------------------------------------------------------------------- * Prototypes *--------------------------------------------------------------------------*/ /* mpistubs.c */ HYPRE_Int hypre_MPI_Init( hypre_int *argc , char ***argv ); HYPRE_Int hypre_MPI_Finalize( void ); HYPRE_Int hypre_MPI_Abort( hypre_MPI_Comm comm , HYPRE_Int errorcode ); HYPRE_Real hypre_MPI_Wtime( void ); HYPRE_Real hypre_MPI_Wtick( void ); HYPRE_Int hypre_MPI_Barrier( hypre_MPI_Comm comm ); HYPRE_Int hypre_MPI_Comm_create( hypre_MPI_Comm comm , hypre_MPI_Group group , hypre_MPI_Comm *newcomm ); HYPRE_Int hypre_MPI_Comm_dup( hypre_MPI_Comm comm , hypre_MPI_Comm *newcomm ); hypre_MPI_Comm hypre_MPI_Comm_f2c( hypre_int comm ); HYPRE_Int hypre_MPI_Comm_size( hypre_MPI_Comm comm , HYPRE_Int *size ); HYPRE_Int hypre_MPI_Comm_rank( hypre_MPI_Comm comm , HYPRE_Int *rank ); HYPRE_Int hypre_MPI_Comm_free( hypre_MPI_Comm *comm ); HYPRE_Int hypre_MPI_Comm_group( hypre_MPI_Comm comm , hypre_MPI_Group *group ); HYPRE_Int hypre_MPI_Comm_split( hypre_MPI_Comm comm, HYPRE_Int n, HYPRE_Int m, hypre_MPI_Comm * comms ); HYPRE_Int hypre_MPI_Group_incl( hypre_MPI_Group group , HYPRE_Int n , HYPRE_Int *ranks , hypre_MPI_Group *newgroup ); HYPRE_Int hypre_MPI_Group_free( hypre_MPI_Group *group ); HYPRE_Int hypre_MPI_Address( void *location , hypre_MPI_Aint *address ); HYPRE_Int hypre_MPI_Get_count( hypre_MPI_Status *status , hypre_MPI_Datatype datatype , HYPRE_Int *count ); HYPRE_Int hypre_MPI_Alltoall( void *sendbuf , HYPRE_Int sendcount , hypre_MPI_Datatype sendtype , void *recvbuf , HYPRE_Int recvcount , hypre_MPI_Datatype recvtype , hypre_MPI_Comm comm ); HYPRE_Int hypre_MPI_Allgather( void *sendbuf , HYPRE_Int sendcount , hypre_MPI_Datatype sendtype , void *recvbuf , HYPRE_Int recvcount , hypre_MPI_Datatype recvtype , hypre_MPI_Comm comm ); HYPRE_Int hypre_MPI_Allgatherv( void *sendbuf , HYPRE_Int sendcount , hypre_MPI_Datatype sendtype , void *recvbuf , HYPRE_Int *recvcounts , HYPRE_Int *displs , hypre_MPI_Datatype recvtype , hypre_MPI_Comm comm ); HYPRE_Int hypre_MPI_Gather( void *sendbuf , HYPRE_Int sendcount , hypre_MPI_Datatype sendtype , void *recvbuf , HYPRE_Int recvcount , hypre_MPI_Datatype recvtype , HYPRE_Int root , hypre_MPI_Comm comm ); HYPRE_Int hypre_MPI_Gatherv( void *sendbuf , HYPRE_Int sendcount , hypre_MPI_Datatype sendtype , void *recvbuf , HYPRE_Int *recvcounts , HYPRE_Int *displs , hypre_MPI_Datatype recvtype , HYPRE_Int root , hypre_MPI_Comm comm ); HYPRE_Int hypre_MPI_Scatter( void *sendbuf , HYPRE_Int sendcount , hypre_MPI_Datatype sendtype , void *recvbuf , HYPRE_Int recvcount , hypre_MPI_Datatype recvtype , HYPRE_Int root , hypre_MPI_Comm comm ); HYPRE_Int hypre_MPI_Scatterv( void *sendbuf , HYPRE_Int *sendcounts , HYPRE_Int *displs, hypre_MPI_Datatype sendtype , void *recvbuf , HYPRE_Int recvcount , hypre_MPI_Datatype recvtype , HYPRE_Int root , hypre_MPI_Comm comm ); HYPRE_Int hypre_MPI_Bcast( void *buffer , HYPRE_Int count , hypre_MPI_Datatype datatype , HYPRE_Int root , hypre_MPI_Comm comm ); HYPRE_Int hypre_MPI_Send( void *buf , HYPRE_Int count , hypre_MPI_Datatype datatype , HYPRE_Int dest , HYPRE_Int tag , hypre_MPI_Comm comm ); HYPRE_Int hypre_MPI_Recv( void *buf , HYPRE_Int count , hypre_MPI_Datatype datatype , HYPRE_Int source , HYPRE_Int tag , hypre_MPI_Comm comm , hypre_MPI_Status *status ); HYPRE_Int hypre_MPI_Isend( void *buf , HYPRE_Int count , hypre_MPI_Datatype datatype , HYPRE_Int dest , HYPRE_Int tag , hypre_MPI_Comm comm , hypre_MPI_Request *request ); HYPRE_Int hypre_MPI_Irecv( void *buf , HYPRE_Int count , hypre_MPI_Datatype datatype , HYPRE_Int source , HYPRE_Int tag , hypre_MPI_Comm comm , hypre_MPI_Request *request ); HYPRE_Int hypre_MPI_Send_init( void *buf , HYPRE_Int count , hypre_MPI_Datatype datatype , HYPRE_Int dest , HYPRE_Int tag , hypre_MPI_Comm comm , hypre_MPI_Request *request ); HYPRE_Int hypre_MPI_Recv_init( void *buf , HYPRE_Int count , hypre_MPI_Datatype datatype , HYPRE_Int dest , HYPRE_Int tag , hypre_MPI_Comm comm , hypre_MPI_Request *request ); HYPRE_Int hypre_MPI_Irsend( void *buf , HYPRE_Int count , hypre_MPI_Datatype datatype , HYPRE_Int dest , HYPRE_Int tag , hypre_MPI_Comm comm , hypre_MPI_Request *request ); HYPRE_Int hypre_MPI_Startall( HYPRE_Int count , hypre_MPI_Request *array_of_requests ); HYPRE_Int hypre_MPI_Probe( HYPRE_Int source , HYPRE_Int tag , hypre_MPI_Comm comm , hypre_MPI_Status *status ); HYPRE_Int hypre_MPI_Iprobe( HYPRE_Int source , HYPRE_Int tag , hypre_MPI_Comm comm , HYPRE_Int *flag , hypre_MPI_Status *status ); HYPRE_Int hypre_MPI_Test( hypre_MPI_Request *request , HYPRE_Int *flag , hypre_MPI_Status *status ); HYPRE_Int hypre_MPI_Testall( HYPRE_Int count , hypre_MPI_Request *array_of_requests , HYPRE_Int *flag , hypre_MPI_Status *array_of_statuses ); HYPRE_Int hypre_MPI_Wait( hypre_MPI_Request *request , hypre_MPI_Status *status ); HYPRE_Int hypre_MPI_Waitall( HYPRE_Int count , hypre_MPI_Request *array_of_requests , hypre_MPI_Status *array_of_statuses ); HYPRE_Int hypre_MPI_Waitany( HYPRE_Int count , hypre_MPI_Request *array_of_requests , HYPRE_Int *index , hypre_MPI_Status *status ); HYPRE_Int hypre_MPI_Allreduce( void *sendbuf , void *recvbuf , HYPRE_Int count , hypre_MPI_Datatype datatype , hypre_MPI_Op op , hypre_MPI_Comm comm ); HYPRE_Int hypre_MPI_Reduce( void *sendbuf , void *recvbuf , HYPRE_Int count , hypre_MPI_Datatype datatype , hypre_MPI_Op op , HYPRE_Int root , hypre_MPI_Comm comm ); HYPRE_Int hypre_MPI_Scan( void *sendbuf , void *recvbuf , HYPRE_Int count , hypre_MPI_Datatype datatype , hypre_MPI_Op op , hypre_MPI_Comm comm ); HYPRE_Int hypre_MPI_Request_free( hypre_MPI_Request *request ); HYPRE_Int hypre_MPI_Type_contiguous( HYPRE_Int count , hypre_MPI_Datatype oldtype , hypre_MPI_Datatype *newtype ); HYPRE_Int hypre_MPI_Type_vector( HYPRE_Int count , HYPRE_Int blocklength , HYPRE_Int stride , hypre_MPI_Datatype oldtype , hypre_MPI_Datatype *newtype ); HYPRE_Int hypre_MPI_Type_hvector( HYPRE_Int count , HYPRE_Int blocklength , hypre_MPI_Aint stride , hypre_MPI_Datatype oldtype , hypre_MPI_Datatype *newtype ); HYPRE_Int hypre_MPI_Type_struct( HYPRE_Int count , HYPRE_Int *array_of_blocklengths , hypre_MPI_Aint *array_of_displacements , hypre_MPI_Datatype *array_of_types , hypre_MPI_Datatype *newtype ); HYPRE_Int hypre_MPI_Type_commit( hypre_MPI_Datatype *datatype ); HYPRE_Int hypre_MPI_Type_free( hypre_MPI_Datatype *datatype ); HYPRE_Int hypre_MPI_Op_free( hypre_MPI_Op *op ); HYPRE_Int hypre_MPI_Op_create( hypre_MPI_User_function *function , hypre_int commute , hypre_MPI_Op *op ); #ifdef __cplusplus } #endif #endif #ifndef HYPRE_SMP_HEADER #define HYPRE_SMP_HEADER #endif #define HYPRE_SMP_SCHEDULE schedule(static) /****************************************************************************** * * Header file for memory management utilities * *****************************************************************************/ #ifndef hypre_MEMORY_HEADER #define hypre_MEMORY_HEADER #include <stdio.h> #include <stdlib.h> #ifdef __cplusplus extern "C" { #endif /*-------------------------------------------------------------------------- * Use "Debug Malloc Library", dmalloc *--------------------------------------------------------------------------*/ #ifdef HYPRE_MEMORY_DMALLOC #define hypre_InitMemoryDebug(id) hypre_InitMemoryDebugDML(id) #define hypre_FinalizeMemoryDebug() hypre_FinalizeMemoryDebugDML() #define hypre_TAlloc(type, count) \ ( (type *)hypre_MAllocDML((size_t)(sizeof(type) * (count)),\ __FILE__, __LINE__) ) #define hypre_CTAlloc(type, count) \ ( (type *)hypre_CAllocDML((size_t)(count), (size_t)sizeof(type),\ __FILE__, __LINE__) ) #define hypre_TReAlloc(ptr, type, count) \ ( (type *)hypre_ReAllocDML((char *)ptr,\ (size_t)(sizeof(type) * (count)),\ __FILE__, __LINE__) ) #define hypre_TFree(ptr) \ ( hypre_FreeDML((char *)ptr, __FILE__, __LINE__), ptr = NULL ) /*-------------------------------------------------------------------------- * Use standard memory routines *--------------------------------------------------------------------------*/ #else #define hypre_InitMemoryDebug(id) #define hypre_FinalizeMemoryDebug() #define hypre_TAlloc(type, count) \ ( (type *)hypre_MAlloc((size_t)(sizeof(type) * (count))) ) #define hypre_CTAlloc(type, count) \ ( (type *)hypre_CAlloc((size_t)(count), (size_t)sizeof(type)) ) #define hypre_TReAlloc(ptr, type, count) \ ( (type *)hypre_ReAlloc((char *)ptr, (size_t)(sizeof(type) * (count))) ) #define hypre_TFree(ptr) \ ( hypre_Free((char *)ptr), ptr = NULL ) #endif #define hypre_SharedTAlloc(type, count) hypre_TAlloc(type, (count)) #define hypre_SharedCTAlloc(type, count) hypre_CTAlloc(type, (count)) #define hypre_SharedTReAlloc(type, count) hypre_TReAlloc(type, (count)) #define hypre_SharedTFree(ptr) hypre_TFree(ptr) /*-------------------------------------------------------------------------- * Prototypes *--------------------------------------------------------------------------*/ /* hypre_memory.c */ HYPRE_Int hypre_OutOfMemory ( size_t size ); char *hypre_MAlloc ( size_t size ); char *hypre_CAlloc ( size_t count , size_t elt_size ); char *hypre_ReAlloc ( char *ptr , size_t size ); void hypre_Free ( char *ptr ); char *hypre_SharedMAlloc ( size_t size ); char *hypre_SharedCAlloc ( size_t count , size_t elt_size ); char *hypre_SharedReAlloc ( char *ptr , size_t size ); void hypre_SharedFree ( char *ptr ); HYPRE_Real *hypre_IncrementSharedDataPtr ( HYPRE_Real *ptr , size_t size ); /* memory_dmalloc.c */ HYPRE_Int hypre_InitMemoryDebugDML( HYPRE_Int id ); HYPRE_Int hypre_FinalizeMemoryDebugDML( void ); char *hypre_MAllocDML( HYPRE_Int size , char *file , HYPRE_Int line ); char *hypre_CAllocDML( HYPRE_Int count , HYPRE_Int elt_size , char *file , HYPRE_Int line ); char *hypre_ReAllocDML( char *ptr , HYPRE_Int size , char *file , HYPRE_Int line ); void hypre_FreeDML( char *ptr , char *file , HYPRE_Int line ); #ifdef __cplusplus } #endif #endif #ifndef hypre_THREADING_HEADER #define hypre_THREADING_HEADER #ifdef HYPRE_USING_OPENMP HYPRE_Int hypre_NumThreads( void ); HYPRE_Int hypre_NumActiveThreads( void ); HYPRE_Int hypre_GetThreadNum( void ); #else #define hypre_NumThreads() 1 #define hypre_NumActiveThreads() 1 #define hypre_GetThreadNum() 0 #endif void hypre_GetSimpleThreadPartition( HYPRE_Int *begin, HYPRE_Int *end, HYPRE_Int n ); #endif /****************************************************************************** * * Header file for doing timing * *****************************************************************************/ #ifndef HYPRE_TIMING_HEADER #define HYPRE_TIMING_HEADER #include <stdlib.h> #include <stdio.h> #include <string.h> #ifdef __cplusplus extern "C" { #endif /*-------------------------------------------------------------------------- * Prototypes for low-level timing routines *--------------------------------------------------------------------------*/ /* timer.c */ HYPRE_Real time_getWallclockSeconds( void ); HYPRE_Real time_getCPUSeconds( void ); HYPRE_Real time_get_wallclock_seconds_( void ); HYPRE_Real time_get_cpu_seconds_( void ); /*-------------------------------------------------------------------------- * With timing off *--------------------------------------------------------------------------*/ #ifndef HYPRE_TIMING #define hypre_InitializeTiming(name) 0 #define hypre_FinalizeTiming(index) #define hypre_IncFLOPCount(inc) #define hypre_BeginTiming(i) #define hypre_EndTiming(i) #define hypre_PrintTiming(heading, wall_time, comm) #define hypre_ClearTiming() /*-------------------------------------------------------------------------- * With timing on *--------------------------------------------------------------------------*/ #else /*------------------------------------------------------- * Global timing structure *-------------------------------------------------------*/ typedef struct { HYPRE_Real *wall_time; HYPRE_Real *cpu_time; HYPRE_Real *flops; char **name; HYPRE_Int *state; /* boolean flag to allow for recursive timing */ HYPRE_Int *num_regs; /* count of how many times a name is registered */ HYPRE_Int num_names; HYPRE_Int size; HYPRE_Real wall_count; HYPRE_Real CPU_count; HYPRE_Real FLOP_count; } hypre_TimingType; #ifdef HYPRE_TIMING_GLOBALS hypre_TimingType *hypre_global_timing = NULL; #else extern hypre_TimingType *hypre_global_timing; #endif /*------------------------------------------------------- * Accessor functions *-------------------------------------------------------*/ #define hypre_TimingWallTime(i) (hypre_global_timing -> wall_time[(i)]) #define hypre_TimingCPUTime(i) (hypre_global_timing -> cpu_time[(i)]) #define hypre_TimingFLOPS(i) (hypre_global_timing -> flops[(i)]) #define hypre_TimingName(i) (hypre_global_timing -> name[(i)]) #define hypre_TimingState(i) (hypre_global_timing -> state[(i)]) #define hypre_TimingNumRegs(i) (hypre_global_timing -> num_regs[(i)]) #define hypre_TimingWallCount (hypre_global_timing -> wall_count) #define hypre_TimingCPUCount (hypre_global_timing -> CPU_count) #define hypre_TimingFLOPCount (hypre_global_timing -> FLOP_count) /*------------------------------------------------------- * Prototypes *-------------------------------------------------------*/ /* timing.c */ HYPRE_Int hypre_InitializeTiming( const char *name ); HYPRE_Int hypre_FinalizeTiming( HYPRE_Int time_index ); HYPRE_Int hypre_IncFLOPCount( HYPRE_Int inc ); HYPRE_Int hypre_BeginTiming( HYPRE_Int time_index ); HYPRE_Int hypre_EndTiming( HYPRE_Int time_index ); HYPRE_Int hypre_ClearTiming( void ); HYPRE_Int hypre_PrintTiming( const char *heading , HYPRE_Real *wall_time , MPI_Comm comm ); #endif #ifdef __cplusplus } #endif #endif /****************************************************************************** * * Header file link lists * *****************************************************************************/ #ifndef HYPRE_LINKLIST_HEADER #define HYPRE_LINKLIST_HEADER #include <stdlib.h> #include <stdio.h> #include <string.h> #ifdef __cplusplus extern "C" { #endif #define LIST_HEAD -1 #define LIST_TAIL -2 struct double_linked_list { HYPRE_Int data; struct double_linked_list *next_elt; struct double_linked_list *prev_elt; HYPRE_Int head; HYPRE_Int tail; }; typedef struct double_linked_list hypre_ListElement; typedef hypre_ListElement *hypre_LinkList; #ifdef __cplusplus } #endif #endif #ifndef hypre_EXCHANGE_DATA_HEADER #define hypre_EXCHANGE_DATA_HEADER #define hypre_BinaryTreeParentId(tree) (tree->parent_id) #define hypre_BinaryTreeNumChild(tree) (tree->num_child) #define hypre_BinaryTreeChildIds(tree) (tree->child_id) #define hypre_BinaryTreeChildId(tree, i) (tree->child_id[i]) typedef struct { HYPRE_Int parent_id; HYPRE_Int num_child; HYPRE_Int *child_id; } hypre_BinaryTree; /* In the fill_response() function the user needs to set the recv__buf and the response_message_size. Memory of size send_response_storage has been alllocated for the send_buf (in exchange_data) - if more is needed, then realloc and adjust the send_response_storage. The realloc amount should be storage+overhead. If the response is an empty "confirmation" message, then set response_message_size =0 (and do not modify the send_buf) */ typedef struct { HYPRE_Int (*fill_response)(void* recv_buf, HYPRE_Int contact_size, HYPRE_Int contact_proc, void* response_obj, MPI_Comm comm, void** response_buf, HYPRE_Int* response_message_size); HYPRE_Int send_response_overhead; /*set by exchange data */ HYPRE_Int send_response_storage; /*storage allocated for send_response_buf*/ void *data1; /*data fields user may want to access in fill_response */ void *data2; } hypre_DataExchangeResponse; HYPRE_Int hypre_CreateBinaryTree(HYPRE_Int, HYPRE_Int, hypre_BinaryTree*); HYPRE_Int hypre_DestroyBinaryTree(hypre_BinaryTree*); HYPRE_Int hypre_DataExchangeList(HYPRE_Int num_contacts, HYPRE_Int *contact_proc_list, void *contact_send_buf, HYPRE_Int *contact_send_buf_starts, HYPRE_Int contact_obj_size, HYPRE_Int response_obj_size, hypre_DataExchangeResponse *response_obj, HYPRE_Int max_response_size, HYPRE_Int rnum, MPI_Comm comm, void **p_response_recv_buf, HYPRE_Int **p_response_recv_buf_starts); #endif /* end of header */ #ifndef hypre_ERROR_HEADER #define hypre_ERROR_HEADER /*-------------------------------------------------------------------------- * Global variable used in hypre error checking *--------------------------------------------------------------------------*/ extern HYPRE_Int hypre__global_error; #define hypre_error_flag hypre__global_error /*-------------------------------------------------------------------------- * HYPRE error macros *--------------------------------------------------------------------------*/ void hypre_error_handler(const char *filename, HYPRE_Int line, HYPRE_Int ierr, const char *msg); #define hypre_error(IERR) hypre_error_handler(__FILE__, __LINE__, IERR, NULL) #define hypre_error_w_msg(IERR, msg) hypre_error_handler(__FILE__, __LINE__, IERR, msg) #define hypre_error_in_arg(IARG) hypre_error(HYPRE_ERROR_ARG | IARG<<3) #ifdef NDEBUG #define hypre_assert(EX) #else #define hypre_assert(EX) if (!(EX)) {hypre_fprintf(stderr,"hypre_assert failed: %s\n", #EX); hypre_error(1);} #endif #endif /****************************************************************************** * * Header file for Caliper instrumentation macros * *****************************************************************************/ /* #ifndef CALIPER_INSTRUMENTATION_HEADER #define CALIPER_INSTRUMENTATION_HEADER #include "HYPRE_config.h" #ifdef HYPRE_USING_CALIPER #include <caliper/cali.h> #define HYPRE_ANNOTATION_BEGIN( str ) cali_begin_string_byname("hypre.kernel", str) #define HYPRE_ANNOTATION_END( str ) cali_end_byname("hypre.kernel") #else #define HYPRE_ANNOTATION_BEGIN( str ) #define HYPRE_ANNOTATION_END( str ) #endif #endif *//* CALIPER_INSTRUMENTATION_HEADER */ /* amg_linklist.c */ void hypre_dispose_elt ( hypre_LinkList element_ptr ); void hypre_remove_point ( hypre_LinkList *LoL_head_ptr , hypre_LinkList *LoL_tail_ptr , HYPRE_Int measure , HYPRE_Int index , HYPRE_Int *lists , HYPRE_Int *where ); hypre_LinkList hypre_create_elt ( HYPRE_Int Item ); void hypre_enter_on_lists ( hypre_LinkList *LoL_head_ptr , hypre_LinkList *LoL_tail_ptr , HYPRE_Int measure , HYPRE_Int index , HYPRE_Int *lists , HYPRE_Int *where ); HYPRE_Int hypre_BinarySearch ( HYPRE_Int *list , HYPRE_Int value , HYPRE_Int list_length ); HYPRE_Int hypre_BinarySearch2 ( HYPRE_Int *list , HYPRE_Int value , HYPRE_Int low , HYPRE_Int high , HYPRE_Int *spot ); HYPRE_Int *hypre_LowerBound( HYPRE_Int *first, HYPRE_Int *last, HYPRE_Int value ); /* hypre_complex.c */ #ifdef HYPRE_COMPLEX HYPRE_Complex hypre_conj( HYPRE_Complex value ); HYPRE_Real hypre_cabs( HYPRE_Complex value ); HYPRE_Real hypre_creal( HYPRE_Complex value ); HYPRE_Real hypre_cimag( HYPRE_Complex value ); #else #define hypre_conj(value) value #define hypre_cabs(value) fabs(value) #define hypre_creal(value) value #define hypre_cimag(value) 0.0 #endif /* hypre_printf.c */ // #ifdef HYPRE_BIGINT HYPRE_Int hypre_printf( const char *format , ... ); HYPRE_Int hypre_fprintf( FILE *stream , const char *format, ... ); HYPRE_Int hypre_sprintf( char *s , const char *format, ... ); HYPRE_Int hypre_scanf( const char *format , ... ); HYPRE_Int hypre_fscanf( FILE *stream , const char *format, ... ); HYPRE_Int hypre_sscanf( char *s , const char *format, ... ); // #else // #define hypre_printf printf // #define hypre_fprintf fprintf // #define hypre_sprintf sprintf // #define hypre_scanf scanf // #define hypre_fscanf fscanf // #define hypre_sscanf sscanf // #endif /* hypre_qsort.c */ void hypre_swap ( HYPRE_Int *v , HYPRE_Int i , HYPRE_Int j ); void hypre_swap2 ( HYPRE_Int *v , HYPRE_Real *w , HYPRE_Int i , HYPRE_Int j ); void hypre_swap2i ( HYPRE_Int *v , HYPRE_Int *w , HYPRE_Int i , HYPRE_Int j ); void hypre_swap3i ( HYPRE_Int *v , HYPRE_Int *w , HYPRE_Int *z , HYPRE_Int i , HYPRE_Int j ); void hypre_swap3_d ( HYPRE_Real *v , HYPRE_Int *w , HYPRE_Int *z , HYPRE_Int i , HYPRE_Int j ); void hypre_swap4_d ( HYPRE_Real *v , HYPRE_Int *w , HYPRE_Int *z , HYPRE_Int *y , HYPRE_Int i , HYPRE_Int j ); void hypre_swap_d ( HYPRE_Real *v , HYPRE_Int i , HYPRE_Int j ); void hypre_qsort0 ( HYPRE_Int *v , HYPRE_Int left , HYPRE_Int right ); void hypre_qsort1 ( HYPRE_Int *v , HYPRE_Real *w , HYPRE_Int left , HYPRE_Int right ); void hypre_qsort2i ( HYPRE_Int *v , HYPRE_Int *w , HYPRE_Int left , HYPRE_Int right ); void hypre_qsort2 ( HYPRE_Int *v , HYPRE_Real *w , HYPRE_Int left , HYPRE_Int right ); void hypre_qsort3i ( HYPRE_Int *v , HYPRE_Int *w , HYPRE_Int *z , HYPRE_Int left , HYPRE_Int right ); void hypre_qsort3_abs ( HYPRE_Real *v , HYPRE_Int *w , HYPRE_Int *z , HYPRE_Int left , HYPRE_Int right ); void hypre_qsort4_abs ( HYPRE_Real *v , HYPRE_Int *w , HYPRE_Int *z , HYPRE_Int *y , HYPRE_Int left , HYPRE_Int right ); void hypre_qsort_abs ( HYPRE_Real *w , HYPRE_Int left , HYPRE_Int right ); /* qsplit.c */ HYPRE_Int hypre_DoubleQuickSplit ( HYPRE_Real *values , HYPRE_Int *indices , HYPRE_Int list_length , HYPRE_Int NumberKept ); /* random.c */ void hypre_SeedRand ( HYPRE_Int seed ); HYPRE_Int hypre_RandI ( void ); HYPRE_Real hypre_Rand ( void ); /* hypre_prefix_sum.c */ /** * Assumed to be called within an omp region. * Let x_i be the input of ith thread. * The output of ith thread y_i = x_0 + x_1 + ... + x_{i-1} * Additionally, sum = x_0 + x_1 + ... + x_{nthreads - 1} * Note that always y_0 = 0 * * @param workspace at least with length (nthreads+1) * workspace[tid] will contain result for tid * workspace[nthreads] will contain sum */ void hypre_prefix_sum(HYPRE_Int *in_out, HYPRE_Int *sum, HYPRE_Int *workspace); /** * This version does prefix sum in pair. * Useful when we prefix sum of diag and offd in tandem. * * @param worksapce at least with length 2*(nthreads+1) * workspace[2*tid] and workspace[2*tid+1] will contain results for tid * workspace[3*nthreads] and workspace[3*nthreads + 1] will contain sums */ void hypre_prefix_sum_pair(HYPRE_Int *in_out1, HYPRE_Int *sum1, HYPRE_Int *in_out2, HYPRE_Int *sum2, HYPRE_Int *workspace); /** * @param workspace at least with length 3*(nthreads+1) * workspace[3*tid:3*tid+3) will contain results for tid */ void hypre_prefix_sum_triple(HYPRE_Int *in_out1, HYPRE_Int *sum1, HYPRE_Int *in_out2, HYPRE_Int *sum2, HYPRE_Int *in_out3, HYPRE_Int *sum3, HYPRE_Int *workspace); /** * n prefix-sums together. * workspace[n*tid:n*(tid+1)) will contain results for tid * workspace[nthreads*tid:nthreads*(tid+1)) will contain sums * * @param workspace at least with length n*(nthreads+1) */ void hypre_prefix_sum_multiple(HYPRE_Int *in_out, HYPRE_Int *sum, HYPRE_Int n, HYPRE_Int *workspace); /* hypre_merge_sort.c */ /** * Why merge sort? * 1) Merge sort can take advantage of eliminating duplicates. * 2) Merge sort is more efficiently parallelizable than qsort */ /** * Out of place merge sort with duplicate elimination * @ret number of unique elements */ HYPRE_Int hypre_merge_sort_unique(HYPRE_Int *in, HYPRE_Int *out, HYPRE_Int len); /** * Out of place merge sort with duplicate elimination * * @param out pointer to output can be in or temp * @ret number of unique elements */ HYPRE_Int hypre_merge_sort_unique2(HYPRE_Int *in, HYPRE_Int *temp, HYPRE_Int len, HYPRE_Int **out); void hypre_merge_sort(HYPRE_Int *in, HYPRE_Int *temp, HYPRE_Int len, HYPRE_Int **sorted); /* hypre_hopscotch_hash.c */ #ifdef HYPRE_USING_OPENMP /* Check if atomic operations are available to use concurrent hopscotch hash table */ #if defined(__GNUC__) && defined(__GNUC_MINOR__) && defined(__GNUC_PATCHLEVEL__) && (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) > 40100 #define HYPRE_USING_ATOMIC //#elif defined _MSC_VER // JSP: haven't tested, so comment out for now //#define HYPRE_USING_ATOMIC //#elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L && !defined(__STDC_NO_ATOMICS__) // JSP: not many compilers have implemented this, so comment out for now //#define HYPRE_USING_ATOMIC //#include <stdatomic.h> #endif #endif // HYPRE_USING_OPENMP #ifdef HYPRE_HOPSCOTCH #ifdef HYPRE_USING_ATOMIC // concurrent hopscotch hashing is possible only with atomic supports #define HYPRE_CONCURRENT_HOPSCOTCH #endif #endif #ifdef HYPRE_CONCURRENT_HOPSCOTCH typedef struct { HYPRE_Int volatile timestamp; omp_lock_t lock; } hypre_HopscotchSegment; #endif /** * The current typical use case of unordered set is putting input sequence * with lots of duplication (putting all colidx received from other ranks), * followed by one sweep of enumeration. * Since the capacity is set to the number of inputs, which is much larger * than the number of unique elements, we optimize for initialization and * enumeration whose time is proportional to the capacity. * For initialization and enumeration, structure of array (SoA) is better * for vectorization, cache line utilization, and so on. */ typedef struct { HYPRE_Int volatile segmentMask; HYPRE_Int volatile bucketMask; #ifdef HYPRE_CONCURRENT_HOPSCOTCH hypre_HopscotchSegment* volatile segments; #endif HYPRE_Int *volatile key; hypre_uint *volatile hopInfo; HYPRE_Int *volatile hash; } hypre_UnorderedIntSet; typedef struct { hypre_uint volatile hopInfo; HYPRE_Int volatile hash; HYPRE_Int volatile key; HYPRE_Int volatile data; } hypre_HopscotchBucket; /** * The current typical use case of unoredered map is putting input sequence * with no duplication (inverse map of a bijective mapping) followed by * lots of lookups. * For lookup, array of structure (AoS) gives better cache line utilization. */ typedef struct { HYPRE_Int volatile segmentMask; HYPRE_Int volatile bucketMask; #ifdef HYPRE_CONCURRENT_HOPSCOTCH hypre_HopscotchSegment* volatile segments; #endif hypre_HopscotchBucket* volatile table; } hypre_UnorderedIntMap; /** * Sort array "in" with length len and put result in array "out" * "in" will be deallocated unless in == *out * inverse_map is an inverse hash table s.t. inverse_map[i] = j iff (*out)[j] = i */ void hypre_sort_and_create_inverse_map( HYPRE_Int *in, HYPRE_Int len, HYPRE_Int **out, hypre_UnorderedIntMap *inverse_map); #ifdef __cplusplus } #endif #endif
45,750
41.089236
226
h
AMG
AMG-master/utilities/amg_linklist.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /*************************************************************************** * * Routines for linked list for boomerAMG * ****************************************************************************/ #include "_hypre_utilities.h" #define hypre_LIST_HEAD -1 #define hypre_LIST_TAIL -2 /************************************************************** * * dispose_elt(): dispose of memory space used by the element * pointed to by element_ptr. Use the 'free()' * system call to return it to the free memory * pool. * **************************************************************/ void hypre_dispose_elt ( hypre_LinkList element_ptr ) { free( element_ptr ); } /***************************************************************** * * remove_point: removes a point from the lists * ****************************************************************/ void hypre_remove_point(hypre_LinkList *LoL_head_ptr, hypre_LinkList *LoL_tail_ptr, HYPRE_Int measure, HYPRE_Int index, HYPRE_Int *lists, HYPRE_Int *where) { hypre_LinkList LoL_head = *LoL_head_ptr; hypre_LinkList LoL_tail = *LoL_tail_ptr; hypre_LinkList list_ptr; list_ptr = LoL_head; do { if (measure == list_ptr->data) { /* point to be removed is only point on list, which must be destroyed */ if (list_ptr->head == index && list_ptr->tail == index) { /* removing only list, so num_left better be 0! */ if (list_ptr == LoL_head && list_ptr == LoL_tail) { LoL_head = NULL; LoL_tail = NULL; hypre_dispose_elt(list_ptr); *LoL_head_ptr = LoL_head; *LoL_tail_ptr = LoL_tail; return; } else if (LoL_head == list_ptr) /*removing 1st (max_measure) list */ { list_ptr -> next_elt -> prev_elt = NULL; LoL_head = list_ptr->next_elt; hypre_dispose_elt(list_ptr); *LoL_head_ptr = LoL_head; *LoL_tail_ptr = LoL_tail; return; } else if (LoL_tail == list_ptr) /* removing last list */ { list_ptr -> prev_elt -> next_elt = NULL; LoL_tail = list_ptr->prev_elt; hypre_dispose_elt(list_ptr); *LoL_head_ptr = LoL_head; *LoL_tail_ptr = LoL_tail; return; } else { list_ptr -> next_elt -> prev_elt = list_ptr -> prev_elt; list_ptr -> prev_elt -> next_elt = list_ptr -> next_elt; hypre_dispose_elt(list_ptr); *LoL_head_ptr = LoL_head; *LoL_tail_ptr = LoL_tail; return; } } else if (list_ptr->head == index) /* index is head of list */ { list_ptr->head = lists[index]; where[lists[index]] = hypre_LIST_HEAD; return; } else if (list_ptr->tail == index) /* index is tail of list */ { list_ptr->tail = where[index]; lists[where[index]] = hypre_LIST_TAIL; return; } else /* index is in middle of list */ { lists[where[index]] = lists[index]; where[lists[index]] = where[index]; return; } } list_ptr = list_ptr -> next_elt; } while (list_ptr != NULL); hypre_error_w_msg(HYPRE_ERROR_GENERIC,"No such list!\n"); return ; } /***************************************************************** * * hypre_create_elt() : Create an element using Item for its data field * *****************************************************************/ hypre_LinkList hypre_create_elt( HYPRE_Int Item ) { hypre_LinkList new_elt_ptr; /* Allocate memory space for the new node. * return with error if no space available */ if ( (new_elt_ptr = (hypre_LinkList) malloc (sizeof(hypre_ListElement))) == NULL) { hypre_error_w_msg(HYPRE_ERROR_GENERIC,"\n create_elt: malloc failed \n\n"); } else /* new_elt_ptr = hypre_CTAlloc(hypre_LinkList, 1); */ { new_elt_ptr -> data = Item; new_elt_ptr -> next_elt = NULL; new_elt_ptr -> prev_elt = NULL; new_elt_ptr -> head = hypre_LIST_TAIL; new_elt_ptr -> tail = hypre_LIST_HEAD; } return (new_elt_ptr); } /***************************************************************** * * enter_on_lists places point in new list * ****************************************************************/ void hypre_enter_on_lists(hypre_LinkList *LoL_head_ptr, hypre_LinkList *LoL_tail_ptr, HYPRE_Int measure, HYPRE_Int index, HYPRE_Int *lists, HYPRE_Int *where) { hypre_LinkList LoL_head = *LoL_head_ptr; hypre_LinkList LoL_tail = *LoL_tail_ptr; hypre_LinkList list_ptr; hypre_LinkList new_ptr; HYPRE_Int old_tail; list_ptr = LoL_head; if (LoL_head == NULL) /* no lists exist yet */ { new_ptr = hypre_create_elt(measure); new_ptr->head = index; new_ptr->tail = index; lists[index] = hypre_LIST_TAIL; where[index] = hypre_LIST_HEAD; LoL_head = new_ptr; LoL_tail = new_ptr; *LoL_head_ptr = LoL_head; *LoL_tail_ptr = LoL_tail; return; } else { do { if (measure > list_ptr->data) { new_ptr = hypre_create_elt(measure); new_ptr->head = index; new_ptr->tail = index; lists[index] = hypre_LIST_TAIL; where[index] = hypre_LIST_HEAD; if ( list_ptr->prev_elt != NULL) { new_ptr->prev_elt = list_ptr->prev_elt; list_ptr->prev_elt->next_elt = new_ptr; list_ptr->prev_elt = new_ptr; new_ptr->next_elt = list_ptr; } else { new_ptr->next_elt = list_ptr; list_ptr->prev_elt = new_ptr; new_ptr->prev_elt = NULL; LoL_head = new_ptr; } *LoL_head_ptr = LoL_head; *LoL_tail_ptr = LoL_tail; return; } else if (measure == list_ptr->data) { old_tail = list_ptr->tail; lists[old_tail] = index; where[index] = old_tail; lists[index] = hypre_LIST_TAIL; list_ptr->tail = index; return; } list_ptr = list_ptr->next_elt; } while (list_ptr != NULL); new_ptr = hypre_create_elt(measure); new_ptr->head = index; new_ptr->tail = index; lists[index] = hypre_LIST_TAIL; where[index] = hypre_LIST_HEAD; LoL_tail->next_elt = new_ptr; new_ptr->prev_elt = LoL_tail; new_ptr->next_elt = NULL; LoL_tail = new_ptr; *LoL_head_ptr = LoL_head; *LoL_tail_ptr = LoL_tail; return; } }
8,328
29.39781
85
c
AMG
AMG-master/utilities/amg_linklist.h
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /****************************************************************************** * * Header file link lists * *****************************************************************************/ #ifndef HYPRE_LINKLIST_HEADER #define HYPRE_LINKLIST_HEADER #include <stdlib.h> #include <stdio.h> #include <string.h> #ifdef __cplusplus extern "C" { #endif struct double_linked_list { HYPRE_Int data; struct double_linked_list *next_elt; struct double_linked_list *prev_elt; HYPRE_Int head; HYPRE_Int tail; }; typedef struct double_linked_list hypre_ListElement; typedef hypre_ListElement *hypre_LinkList; #ifdef __cplusplus } #endif #endif
1,674
30.603774
81
h
AMG
AMG-master/utilities/binsearch.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ #include "_hypre_utilities.h" /*-------------------------------------------------------------------------- * hypre_BinarySearch * to contain ordered nonnegative numbers * the routine returns the location of the value or -1 *--------------------------------------------------------------------------*/ HYPRE_Int hypre_BinarySearch(HYPRE_Int *list, HYPRE_Int value, HYPRE_Int list_length) { HYPRE_Int low, high, m; HYPRE_Int not_found = 1; low = 0; high = list_length-1; while (not_found && low <= high) { m = (low + high) / 2; if (value < list[m]) { high = m - 1; } else if (value > list[m]) { low = m + 1; } else { not_found = 0; return m; } } return -1; } /*-------------------------------------------------------------------------- * hypre_BinarySearch2 * this one is a bit more robust: * avoids overflow of m as can happen above when (low+high) overflows * lets user specifiy high and low bounds for array (so a subset of array can be used) * if not found, then spot returns where is should be inserted *--------------------------------------------------------------------------*/ HYPRE_Int hypre_BinarySearch2(HYPRE_Int *list, HYPRE_Int value, HYPRE_Int low, HYPRE_Int high, HYPRE_Int *spot) { HYPRE_Int m; while (low <= high) { m = low + (high - low)/2; if (value < list[m]) high = m - 1; else if (value > list[m]) low = m + 1; else { *spot = m; return m; } } /* not found (high = low-1) - so insert at low */ *spot = low; return -1; } /*-------------------------------------------------------------------------- * Equivalent to C++ std::lower_bound *--------------------------------------------------------------------------*/ HYPRE_Int *hypre_LowerBound( HYPRE_Int *first, HYPRE_Int *last, HYPRE_Int value ) { HYPRE_Int *it; size_t count = last - first, step; while (count > 0) { it = first; step = count/2; it += step; if (*it < value) { first = ++it; count -= step + 1; } else count = step; } return first; }
3,166
28.055046
112
c
AMG
AMG-master/utilities/caliper_instrumentation.h
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /****************************************************************************** * * Header file for Caliper instrumentation macros * *****************************************************************************/ #ifndef CALIPER_INSTRUMENTATION_HEADER #define CALIPER_INSTRUMENTATION_HEADER #include "HYPRE_config.h" #ifdef HYPRE_USING_CALIPER #include <caliper/cali.h> #define HYPRE_ANNOTATION_BEGIN( str ) cali_begin_string_byname("hypre.kernel", str) #define HYPRE_ANNOTATION_END( str ) cali_end_byname("hypre.kernel") #else #define HYPRE_ANNOTATION_BEGIN( str ) #define HYPRE_ANNOTATION_END( str ) #endif #endif /* CALIPER_INSTRUMENTATION_HEADER */
1,593
34.422222
83
h
AMG
AMG-master/utilities/exchange_data.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /* see exchange_data.README for additional information */ /* AHB 6/04 */ #include <stdlib.h> #include <stdio.h> #include <math.h> #include "_hypre_utilities.h" /*--------------------------------------------------- * hypre_CreateBinaryTree() * its children and parent processor ids) *----------------------------------------------------*/ HYPRE_Int hypre_CreateBinaryTree(HYPRE_Int myid, HYPRE_Int num_procs, hypre_BinaryTree *tree) { HYPRE_Int i, proc, size=0; HYPRE_Int *tmp_child_id; HYPRE_Int num=0, parent = 0; /* initialize*/ proc = myid; /*how many children can a processor have?*/ for (i = 1; i < num_procs; i *= 2) { size++; } /* allocate space */ tmp_child_id = hypre_TAlloc(HYPRE_Int, size); /* find children and parent */ for (i = 1; i < num_procs; i *= 2) { if ( (proc % 2) == 0) { if( (myid + i) < num_procs ) { tmp_child_id[num] = myid + i; num++; } proc /= 2; } else { parent = myid - i; break; } } hypre_BinaryTreeParentId(tree) = parent; hypre_BinaryTreeNumChild(tree) = num; hypre_BinaryTreeChildIds(tree) = tmp_child_id; return hypre_error_flag; } /*--------------------------------------------------- * hypre_DestroyBinaryTree() * Destroy storage created by createBinaryTree *----------------------------------------------------*/ HYPRE_Int hypre_DestroyBinaryTree(hypre_BinaryTree *tree) { hypre_TFree(hypre_BinaryTreeChildIds(tree)); return hypre_error_flag; } /*--------------------------------------------------- * hypre_DataExchangeList() * This function is for sending a list of messages ("contacts" to * a list of processors. The receiving processors * do not know how many messages they are getting. The * sending process expects a "response" (either a confirmation or * some sort of data back from the receiving processor). *----------------------------------------------------*/ /* should change to where the buffers for sending and receiving are voids instead of ints - then cast accordingly */ HYPRE_Int hypre_DataExchangeList(HYPRE_Int num_contacts, HYPRE_Int *contact_proc_list, void *contact_send_buf, HYPRE_Int *contact_send_buf_starts, HYPRE_Int contact_obj_size, HYPRE_Int response_obj_size, hypre_DataExchangeResponse *response_obj, HYPRE_Int max_response_size, HYPRE_Int rnum, MPI_Comm comm, void **p_response_recv_buf, HYPRE_Int **p_response_recv_buf_starts) { /*------------------------------------------- * parameters: * * num_contacts = how many procs to contact * contact_proc_list = list of processors to contact * contact_send_buf = array of data to send * contact_send_buf_starts = index for contact_send_buf corresponding to * contact_proc_list * contact_obj_size = sizeof() one obj in contact list * response_obj_size = sizeof() one obj in response_recv_buf * response_obj = this will give us the function we need to * fill the reponse as well as * any data we might need to accomplish that * max_response_size = max size of a single response expected (do NOT * need to be an absolute upper bound) * rnum = two consequentive exchanges should have different * rnums. Alternate rnum = 1 * and rnum=2 - these flags will be even (so odd * numbered tags could be used in calling code) * p_response_recv_buf = where to receive the reponses - will be allocated * in this function * p_response_recv_buf_starts = index of p_response_buf corresponding to * contact_buf_list - will be allocated here *-------------------------------------------*/ HYPRE_Int num_procs, myid; HYPRE_Int i; HYPRE_Int terminate, responses_complete; HYPRE_Int children_complete; HYPRE_Int contact_flag; HYPRE_Int proc; HYPRE_Int contact_size; HYPRE_Int size, post_size, copy_size; HYPRE_Int total_size, count; void *start_ptr = NULL, *index_ptr=NULL; HYPRE_Int *int_ptr=NULL; void *response_recv_buf = NULL; void *send_response_buf = NULL; HYPRE_Int *response_recv_buf_starts = NULL; void *initial_recv_buf = NULL; void *recv_contact_buf = NULL; HYPRE_Int recv_contact_buf_size = 0; HYPRE_Int response_message_size = 0; HYPRE_Int overhead; HYPRE_Int max_response_size_bytes; HYPRE_Int max_response_total_bytes; void **post_array = NULL; /*this must be set to null or realloc will crash */ HYPRE_Int post_array_storage = 0; HYPRE_Int post_array_size = 0; HYPRE_Int num_post_recvs =0; void **contact_ptrs = NULL, **response_ptrs=NULL, **post_ptrs=NULL; hypre_BinaryTree tree; hypre_MPI_Request *response_requests, *contact_requests; hypre_MPI_Status *response_statuses, *contact_statuses; hypre_MPI_Request *post_send_requests = NULL, *post_recv_requests = NULL; hypre_MPI_Status *post_send_statuses = NULL, *post_recv_statuses = NULL; hypre_MPI_Request *term_requests, term_request1, request_parent; hypre_MPI_Status *term_statuses, term_status1, status_parent; hypre_MPI_Status status, fill_status; const HYPRE_Int contact_tag = 1000*rnum; const HYPRE_Int response_tag = 1002*rnum; const HYPRE_Int term_tag = 1004*rnum; const HYPRE_Int post_tag = 1006*rnum; hypre_MPI_Comm_size(comm, &num_procs ); hypre_MPI_Comm_rank(comm, &myid ); /* ---------initializations ----------------*/ /* if the response_obj_size or contact_obj_size is 0, set to sizeof(HYPRE_Int) */ if (!response_obj_size) response_obj_size = sizeof(HYPRE_Int); if (!contact_obj_size) contact_obj_size = sizeof(HYPRE_Int); max_response_size_bytes = max_response_size*response_obj_size; /* pre-allocate the max space for responding to contacts */ overhead = ceil((HYPRE_Real) sizeof(HYPRE_Int)/response_obj_size); /*for appending an integer*/ max_response_total_bytes = (max_response_size+overhead)*response_obj_size; response_obj->send_response_overhead = overhead; response_obj->send_response_storage = max_response_size; /*send_response_buf = hypre_MAlloc(max_response_total_bytes);*/ send_response_buf = hypre_CAlloc(max_response_size+overhead, response_obj_size); /*allocate space for inital recv array for the responses - give each processor size max_response_size */ initial_recv_buf = hypre_MAlloc(max_response_total_bytes*num_contacts); response_recv_buf_starts = hypre_CTAlloc(HYPRE_Int, num_contacts+1); contact_ptrs = hypre_TAlloc( void *, num_contacts); response_ptrs = hypre_TAlloc(void *, num_contacts); /*-------------SEND CONTACTS AND POST RECVS FOR RESPONSES---*/ for (i=0; i<= num_contacts; i++) { response_recv_buf_starts[i] = i*(max_response_size+overhead); } /* Send "contact" messages to the list of processors and pre-post receives to wait for their response*/ responses_complete = 1; if (num_contacts > 0 ) { responses_complete = 0; response_requests = hypre_CTAlloc(hypre_MPI_Request, num_contacts); response_statuses = hypre_CTAlloc(hypre_MPI_Status, num_contacts); contact_requests = hypre_CTAlloc(hypre_MPI_Request, num_contacts); contact_statuses = hypre_CTAlloc(hypre_MPI_Status, num_contacts); /* post receives - could be confirmation or data*/ /* the size to post is max_response_total_bytes*/ for (i=0; i< num_contacts; i++) { /* response_ptrs[i] = initial_recv_buf + i*max_response_total_bytes ; */ response_ptrs[i] = (void *)((char *) initial_recv_buf + i*max_response_total_bytes) ; hypre_MPI_Irecv(response_ptrs[i], max_response_total_bytes, hypre_MPI_BYTE, contact_proc_list[i], response_tag, comm, &response_requests[i]); } /* send out contact messages */ start_ptr = contact_send_buf; for (i=0; i< num_contacts; i++) { contact_ptrs[i] = start_ptr; size = contact_send_buf_starts[i+1] - contact_send_buf_starts[i] ; hypre_MPI_Isend(contact_ptrs[i], size*contact_obj_size, hypre_MPI_BYTE, contact_proc_list[i], contact_tag, comm, &contact_requests[i]); /* start_ptr += (size*contact_obj_size); */ start_ptr = (void *) ((char *) start_ptr + (size*contact_obj_size)); } } /*------------BINARY TREE-----------------------*/ /*Now let's find out our binary tree information and initialize for the termination check sweep */ children_complete = 1;/*indicates whether we have recv. term messages from our children*/ if (num_procs > 1) { hypre_CreateBinaryTree(myid, num_procs, &tree); /* we will get a message from all of our children when they have received responses for all of their contacts. So post receives now */ term_requests = hypre_CTAlloc(hypre_MPI_Request, tree.num_child); term_statuses = hypre_CTAlloc(hypre_MPI_Status, tree.num_child); for (i=0; i< tree.num_child; i++) { hypre_MPI_Irecv(NULL, 0, HYPRE_MPI_INT, tree.child_id[i], term_tag, comm, &term_requests[i]); } terminate = 0; children_complete = 0; } else if (num_procs ==1 && num_contacts > 0 ) /* added 11/08 */ { terminate = 0; } /*---------PROBE LOOP-----------------------------------------*/ /*Look for incoming contact messages - don't know how many I will get!*/ while (!terminate) { /* did I receive any contact messages? */ hypre_MPI_Iprobe(hypre_MPI_ANY_SOURCE, contact_tag, comm, &contact_flag, &status); while (contact_flag) { /* received contacts - from who and what do we do ?*/ proc = status.hypre_MPI_SOURCE; hypre_MPI_Get_count(&status, hypre_MPI_BYTE, &contact_size); contact_size = contact_size/contact_obj_size; /*---------------FILL RESPONSE ------------------------*/ /*first receive the contact buffer - then call a function to determine how to populate the send buffer for the reponse*/ /* do we have enough space to recv it? */ if(contact_size > recv_contact_buf_size) { recv_contact_buf = hypre_ReAlloc((char*)recv_contact_buf, contact_obj_size*contact_size); recv_contact_buf_size = contact_size; } /* this must be blocking - can't fill recv without the buffer*/ hypre_MPI_Recv(recv_contact_buf, contact_size*contact_obj_size, hypre_MPI_BYTE, proc, contact_tag, comm, &fill_status); response_obj->fill_response(recv_contact_buf, contact_size, proc, response_obj, comm, &send_response_buf, &response_message_size ); /* we need to append the size of the send obj */ /* first we copy out any part that may be needed to send later so we don't overwrite */ post_size = response_message_size - max_response_size; if (post_size > 0) /*we will need to send the extra information later */ { /*hypre_printf("myid = %d, post_size = %d\n", myid, post_size);*/ if (post_array_size == post_array_storage) { /* allocate room for more posts - add 20*/ post_array_storage += 20; post_array = hypre_TReAlloc(post_array, void *, post_array_storage); post_send_requests = hypre_TReAlloc(post_send_requests, hypre_MPI_Request, post_array_storage); } /* allocate space for the data this post only*/ /* this should not happen often (unless a poor max_size has been chosen) - so we will allocate space for the data as needed */ size = post_size*response_obj_size; post_array[post_array_size] = hypre_MAlloc(size); /* index_ptr = send_response_buf + max_response_size_bytes */; index_ptr = (void *) ((char *) send_response_buf + max_response_size_bytes); memcpy(post_array[post_array_size], index_ptr, size); /*now post any part of the message that is too long with a non-blocking send and a different tag */ hypre_MPI_Isend(post_array[post_array_size], size, hypre_MPI_BYTE, proc, post_tag, /*hypre_MPI_COMM_WORLD, */ comm, &post_send_requests[post_array_size]); post_array_size++; } /*now append the size information into the overhead storage */ /* index_ptr = send_response_buf + max_response_size_bytes; */ index_ptr = (void *) ((char *) send_response_buf + max_response_size_bytes); memcpy(index_ptr, &response_message_size, sizeof(HYPRE_Int)); /*send the block of data that includes the overhead */ /* this is a blocking send - the recv has already been posted */ hypre_MPI_Send(send_response_buf, max_response_total_bytes, hypre_MPI_BYTE, proc, response_tag, comm); /*--------------------------------------------------------------*/ /* look for any more contact messages*/ hypre_MPI_Iprobe(hypre_MPI_ANY_SOURCE, contact_tag, comm, &contact_flag, &status); } /* no more contact messages waiting - either (1) check to see if we have received all of our response messages (2) participate in termination (check for messages from children) (3) participate in termination sweep (check for message from parent) */ if (!responses_complete) { hypre_MPI_Testall(num_contacts, response_requests, &responses_complete, response_statuses); if (responses_complete && num_procs == 1) terminate = 1; /*added 11/08 */ } else if(!children_complete) /* have all of our children received all of their response messages?*/ { hypre_MPI_Testall(tree.num_child, term_requests, &children_complete, term_statuses); /* if we have gotten term messages from all of our children, send a term message to our parent. Then post a receive to hear back from parent */ if (children_complete & (myid > 0)) /*root does not have a parent*/ { hypre_MPI_Isend(NULL, 0, HYPRE_MPI_INT, tree.parent_id, term_tag, comm, &request_parent); hypre_MPI_Irecv(NULL, 0, HYPRE_MPI_INT, tree.parent_id, term_tag, comm, &term_request1); } } else /*have we gotten a term message from our parent? */ { if (myid == 0) /* root doesn't have a parent */ { terminate = 1; } else { hypre_MPI_Test(&term_request1, &terminate, &term_status1); } if (terminate) /*tell children to terminate */ { if (myid > 0 ) hypre_MPI_Wait(&request_parent, &status_parent); for (i=0; i< tree.num_child; i++) { /*a blocking send - recv has been posted already*/ hypre_MPI_Send(NULL, 0, HYPRE_MPI_INT, tree.child_id[i], term_tag, comm); } } } } /* end of (!terminate) loop */ /* ----some clean up before post-processing ----*/ if (recv_contact_buf_size > 0) { hypre_TFree(recv_contact_buf); } hypre_Free((char*)send_response_buf); hypre_TFree(contact_ptrs); hypre_TFree(response_ptrs); /*-----------------POST PROCESSING------------------------------*/ /* more data to receive? */ /* move to recv buffer and update response_recv_buf_starts */ total_size = 0; /*total number of items in response buffer */ num_post_recvs = 0; /*num of post processing recvs to post */ start_ptr = initial_recv_buf; response_recv_buf_starts[0] = 0; /*already allocated above */ /*an extra loop to determine sizes. This is better than reallocating the array that will be used in posting the irecvs */ for (i=0; i< num_contacts; i++) { int_ptr = (HYPRE_Int *) ((char *) start_ptr + max_response_size_bytes); /*the overhead HYPRE_Int*/ response_message_size = *int_ptr; response_recv_buf_starts[i+1] = response_recv_buf_starts[i] + response_message_size; total_size += response_message_size; if (max_response_size < response_message_size) num_post_recvs++; /* start_ptr += max_response_total_bytes; */ start_ptr = (void *) ((char *) start_ptr + max_response_total_bytes); } post_recv_requests = hypre_TAlloc(hypre_MPI_Request, num_post_recvs); post_recv_statuses = hypre_TAlloc(hypre_MPI_Status, num_post_recvs); post_ptrs = hypre_TAlloc(void *, num_post_recvs); /*second loop to post any recvs and set up recv_response_buf */ response_recv_buf = hypre_MAlloc(total_size*response_obj_size); index_ptr = response_recv_buf; start_ptr = initial_recv_buf; count = 0; for (i=0; i< num_contacts; i++) { response_message_size = response_recv_buf_starts[i+1] - response_recv_buf_starts[i]; copy_size = hypre_min(response_message_size, max_response_size); memcpy(index_ptr, start_ptr, copy_size*response_obj_size); /* index_ptr += copy_size*response_obj_size; */ index_ptr = (void *) ((char *) index_ptr + copy_size*response_obj_size); if (max_response_size < response_message_size) { size = (response_message_size - max_response_size)*response_obj_size; post_ptrs[count] = index_ptr; hypre_MPI_Irecv(post_ptrs[count], size, hypre_MPI_BYTE, contact_proc_list[i], post_tag, comm, &post_recv_requests[count]); count++; /* index_ptr+=size;*/ index_ptr= (void *) ((char *) index_ptr + size); } /* start_ptr += max_response_total_bytes; */ start_ptr = (void *) ((char *) start_ptr + max_response_total_bytes); } post_send_statuses = hypre_TAlloc(hypre_MPI_Status, post_array_size); /*--------------CLEAN UP------------------- */ hypre_Free((char*)initial_recv_buf); if (num_contacts > 0 ) { /*these should be done */ hypre_MPI_Waitall(num_contacts, contact_requests, contact_statuses); hypre_TFree(response_requests); hypre_TFree(response_statuses); hypre_TFree(contact_requests); hypre_TFree(contact_statuses); } /* clean up from the post processing - the arrays, requests, etc. */ if (num_post_recvs) { hypre_MPI_Waitall(num_post_recvs, post_recv_requests, post_recv_statuses); hypre_TFree(post_recv_requests); hypre_TFree(post_recv_statuses); hypre_TFree(post_ptrs); } if (post_array_size) { hypre_MPI_Waitall(post_array_size, post_send_requests, post_send_statuses); hypre_TFree(post_send_requests); hypre_TFree(post_send_statuses); for (i=0; i< post_array_size; i++) { hypre_Free((char*)post_array[i]); } hypre_TFree(post_array); } if (num_procs > 1) { hypre_TFree(term_requests); hypre_TFree(term_statuses); hypre_DestroyBinaryTree(&tree); } /* output */ *p_response_recv_buf = response_recv_buf; *p_response_recv_buf_starts = response_recv_buf_starts; return hypre_error_flag; }
21,979
36.508532
104
c
AMG
AMG-master/utilities/exchange_data.h
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ #ifndef hypre_EXCHANGE_DATA_HEADER #define hypre_EXCHANGE_DATA_HEADER #define hypre_BinaryTreeParentId(tree) (tree->parent_id) #define hypre_BinaryTreeNumChild(tree) (tree->num_child) #define hypre_BinaryTreeChildIds(tree) (tree->child_id) #define hypre_BinaryTreeChildId(tree, i) (tree->child_id[i]) typedef struct { HYPRE_Int parent_id; HYPRE_Int num_child; HYPRE_Int *child_id; } hypre_BinaryTree; /* In the fill_response() function the user needs to set the recv__buf and the response_message_size. Memory of size send_response_storage has been alllocated for the send_buf (in exchange_data) - if more is needed, then realloc and adjust the send_response_storage. The realloc amount should be storage+overhead. If the response is an empty "confirmation" message, then set response_message_size =0 (and do not modify the send_buf) */ typedef struct { HYPRE_Int (*fill_response)(void* recv_buf, HYPRE_Int contact_size, HYPRE_Int contact_proc, void* response_obj, MPI_Comm comm, void** response_buf, HYPRE_Int* response_message_size); HYPRE_Int send_response_overhead; /*set by exchange data */ HYPRE_Int send_response_storage; /*storage allocated for send_response_buf*/ void *data1; /*data fields user may want to access in fill_response */ void *data2; } hypre_DataExchangeResponse; HYPRE_Int hypre_CreateBinaryTree(HYPRE_Int, HYPRE_Int, hypre_BinaryTree*); HYPRE_Int hypre_DestroyBinaryTree(hypre_BinaryTree*); HYPRE_Int hypre_DataExchangeList(HYPRE_Int num_contacts, HYPRE_Int *contact_proc_list, void *contact_send_buf, HYPRE_Int *contact_send_buf_starts, HYPRE_Int contact_obj_size, HYPRE_Int response_obj_size, hypre_DataExchangeResponse *response_obj, HYPRE_Int max_response_size, HYPRE_Int rnum, MPI_Comm comm, void **p_response_recv_buf, HYPRE_Int **p_response_recv_buf_starts); #endif /* end of header */
3,071
44.850746
92
h
AMG
AMG-master/utilities/general.h
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /****************************************************************************** * * General structures and values * *****************************************************************************/ #ifndef hypre_GENERAL_HEADER #define hypre_GENERAL_HEADER /* This allows us to consistently avoid 'int' throughout hypre */ typedef int hypre_int; typedef long int hypre_longint; typedef unsigned int hypre_uint; typedef unsigned long int hypre_ulongint; /* This allows us to consistently avoid 'double' throughout hypre */ typedef double hypre_double; /*-------------------------------------------------------------------------- * Define various functions *--------------------------------------------------------------------------*/ #ifndef hypre_max #define hypre_max(a,b) (((a)<(b)) ? (b) : (a)) #endif #ifndef hypre_min #define hypre_min(a,b) (((a)<(b)) ? (a) : (b)) #endif #ifndef hypre_abs #define hypre_abs(a) (((a)>0) ? (a) : -(a)) #endif #ifndef hypre_round #define hypre_round(x) ( ((x) < 0.0) ? ((HYPRE_Int)(x - 0.5)) : ((HYPRE_Int)(x + 0.5)) ) #endif #ifndef hypre_pow2 #define hypre_pow2(i) ( 1 << (i) ) #endif #endif
2,111
33.622951
89
h
AMG
AMG-master/utilities/hypre_complex.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ #include "_hypre_utilities.h" #ifdef HYPRE_COMPLEX #include <complex.h> HYPRE_Complex hypre_conj( HYPRE_Complex value ) { return conj(value); } HYPRE_Real hypre_cabs( HYPRE_Complex value ) { return cabs(value); } HYPRE_Real hypre_creal( HYPRE_Complex value ) { return creal(value); } HYPRE_Real hypre_cimag( HYPRE_Complex value ) { return cimag(value); } #endif
1,306
25.673469
81
c
AMG
AMG-master/utilities/hypre_error.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ #include "_hypre_utilities.h" HYPRE_Int hypre__global_error = 0; /* Process the error with code ierr raised in the given line of the given source file. */ void hypre_error_handler(const char *filename, HYPRE_Int line, HYPRE_Int ierr, const char *msg) { hypre_error_flag |= ierr; #ifdef HYPRE_PRINT_ERRORS if (msg) { hypre_fprintf( stderr, "hypre error in file \"%s\", line %d, error code = %d - %s\n", filename, line, ierr, msg); } else { hypre_fprintf( stderr, "hypre error in file \"%s\", line %d, error code = %d\n", filename, line, ierr); } #endif } HYPRE_Int HYPRE_GetError() { return hypre_error_flag; } HYPRE_Int HYPRE_CheckError(HYPRE_Int ierr, HYPRE_Int hypre_error_code) { return ierr & hypre_error_code; } void HYPRE_DescribeError(HYPRE_Int ierr, char *msg) { if (ierr == 0) hypre_sprintf(msg,"[No error] "); if (ierr & HYPRE_ERROR_GENERIC) hypre_sprintf(msg,"[Generic error] "); if (ierr & HYPRE_ERROR_MEMORY) hypre_sprintf(msg,"[Memory error] "); if (ierr & HYPRE_ERROR_ARG) hypre_sprintf(msg,"[Error in argument %d] ", HYPRE_GetErrorArg()); if (ierr & HYPRE_ERROR_CONV) hypre_sprintf(msg,"[Method did not converge] "); } HYPRE_Int HYPRE_GetErrorArg() { return (hypre_error_flag>>3 & 31); } HYPRE_Int HYPRE_ClearAllErrors() { hypre_error_flag = 0; return (hypre_error_flag != 0); } HYPRE_Int HYPRE_ClearError(HYPRE_Int hypre_error_code) { hypre_error_flag &= ~hypre_error_code; return (hypre_error_flag & hypre_error_code); }
2,517
26.977778
95
c
AMG
AMG-master/utilities/hypre_error.h
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ #ifndef hypre_ERROR_HEADER #define hypre_ERROR_HEADER /*-------------------------------------------------------------------------- * Global variable used in hypre error checking *--------------------------------------------------------------------------*/ extern HYPRE_Int hypre__global_error; #define hypre_error_flag hypre__global_error /*-------------------------------------------------------------------------- * HYPRE error macros *--------------------------------------------------------------------------*/ void hypre_error_handler(const char *filename, HYPRE_Int line, HYPRE_Int ierr, const char *msg); #define hypre_error(IERR) hypre_error_handler(__FILE__, __LINE__, IERR, NULL) #define hypre_error_w_msg(IERR, msg) hypre_error_handler(__FILE__, __LINE__, IERR, msg) #define hypre_error_in_arg(IARG) hypre_error(HYPRE_ERROR_ARG | IARG<<3) #ifdef NDEBUG #define hypre_assert(EX) #else #define hypre_assert(EX) if (!(EX)) {hypre_fprintf(stderr,"hypre_assert failed: %s\n", #EX); hypre_error(1);} #endif #endif
1,958
43.522727
109
h
AMG
AMG-master/utilities/hypre_hopscotch_hash.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Jongsoo Park et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ************************************************************************EHEADER*/ #include "hypre_hopscotch_hash.h" static HYPRE_Int NearestPowerOfTwo( HYPRE_Int value ) { HYPRE_Int rc = 1; while (rc < value) { rc <<= 1; } return rc; } static void InitBucket(hypre_HopscotchBucket *b) { b->hopInfo = 0; b->hash = HYPRE_HOPSCOTCH_HASH_EMPTY; } #ifdef HYPRE_CONCURRENT_HOPSCOTCH static void InitSegment(hypre_HopscotchSegment *s) { s->timestamp = 0; omp_init_lock(&s->lock); } static void DestroySegment(hypre_HopscotchSegment *s) { omp_destroy_lock(&s->lock); } #endif void hypre_UnorderedIntSetCreate( hypre_UnorderedIntSet *s, HYPRE_Int inCapacity, HYPRE_Int concurrencyLevel) { s->segmentMask = NearestPowerOfTwo(concurrencyLevel) - 1; if (inCapacity < s->segmentMask + 1) { inCapacity = s->segmentMask + 1; } //ADJUST INPUT ............................ HYPRE_Int adjInitCap = NearestPowerOfTwo(inCapacity+4096); HYPRE_Int num_buckets = adjInitCap + HYPRE_HOPSCOTCH_HASH_INSERT_RANGE + 1; s->bucketMask = adjInitCap - 1; HYPRE_Int i; //ALLOCATE THE SEGMENTS ................... #ifdef HYPRE_CONCURRENT_HOPSCOTCH s->segments = hypre_TAlloc(hypre_HopscotchSegment, s->segmentMask + 1); for (i = 0; i <= s->segmentMask; ++i) { InitSegment(&s->segments[i]); } #endif s->hopInfo = hypre_TAlloc(hypre_uint, num_buckets); s->key = hypre_TAlloc(HYPRE_Int, num_buckets); s->hash = hypre_TAlloc(HYPRE_Int, num_buckets); #ifdef HYPRE_CONCURRENT_HOPSCOTCH #pragma omp parallel for #endif for (i = 0; i < num_buckets; ++i) { s->hopInfo[i] = 0; s->hash[i] = HYPRE_HOPSCOTCH_HASH_EMPTY; } } void hypre_UnorderedIntMapCreate( hypre_UnorderedIntMap *m, HYPRE_Int inCapacity, HYPRE_Int concurrencyLevel) { m->segmentMask = NearestPowerOfTwo(concurrencyLevel) - 1; if (inCapacity < m->segmentMask + 1) { inCapacity = m->segmentMask + 1; } //ADJUST INPUT ............................ HYPRE_Int adjInitCap = NearestPowerOfTwo(inCapacity+4096); HYPRE_Int num_buckets = adjInitCap + HYPRE_HOPSCOTCH_HASH_INSERT_RANGE + 1; m->bucketMask = adjInitCap - 1; HYPRE_Int i; //ALLOCATE THE SEGMENTS ................... #ifdef HYPRE_CONCURRENT_HOPSCOTCH m->segments = hypre_TAlloc(hypre_HopscotchSegment, m->segmentMask + 1); for (i = 0; i <= m->segmentMask; i++) { InitSegment(&m->segments[i]); } #endif m->table = hypre_TAlloc(hypre_HopscotchBucket, num_buckets); #ifdef HYPRE_CONCURRENT_HOPSCOTCH #pragma omp parallel for #endif for (i = 0; i < num_buckets; i++) { InitBucket(&m->table[i]); } } void hypre_UnorderedIntSetDestroy( hypre_UnorderedIntSet *s ) { hypre_TFree(s->hopInfo); hypre_TFree(s->key); hypre_TFree(s->hash); #ifdef HYPRE_CONCURRENT_HOPSCOTCH HYPRE_Int i; for (i = 0; i <= s->segmentMask; i++) { DestroySegment(&s->segments[i]); } hypre_TFree(s->segments); #endif } void hypre_UnorderedIntMapDestroy( hypre_UnorderedIntMap *m) { hypre_TFree(m->table); #ifdef HYPRE_CONCURRENT_HOPSCOTCH HYPRE_Int i; for (i = 0; i <= m->segmentMask; i++) { DestroySegment(&m->segments[i]); } hypre_TFree(m->segments); #endif } HYPRE_Int *hypre_UnorderedIntSetCopyToArray( hypre_UnorderedIntSet *s, HYPRE_Int *len ) { /*HYPRE_Int prefix_sum_workspace[hypre_NumThreads() + 1];*/ HYPRE_Int *prefix_sum_workspace; HYPRE_Int *ret_array = NULL; prefix_sum_workspace = hypre_TAlloc(HYPRE_Int, hypre_NumThreads() + 1); #ifdef HYPRE_CONCURRENT_HOPSCOTCH #pragma omp parallel #endif { HYPRE_Int n = s->bucketMask + HYPRE_HOPSCOTCH_HASH_INSERT_RANGE; HYPRE_Int i_begin, i_end; hypre_GetSimpleThreadPartition(&i_begin, &i_end, n); HYPRE_Int cnt = 0; HYPRE_Int i; for (i = i_begin; i < i_end; i++) { if (HYPRE_HOPSCOTCH_HASH_EMPTY != s->hash[i]) cnt++; } hypre_prefix_sum(&cnt, len, prefix_sum_workspace); #ifdef HYPRE_CONCURRENT_HOPSCOTCH #pragma omp barrier #pragma omp master #endif { ret_array = hypre_TAlloc(HYPRE_Int, *len); } #ifdef HYPRE_CONCURRENT_HOPSCOTCH #pragma omp barrier #endif for (i = i_begin; i < i_end; i++) { if (HYPRE_HOPSCOTCH_HASH_EMPTY != s->hash[i]) ret_array[cnt++] = s->key[i]; } } hypre_TFree(prefix_sum_workspace); return ret_array; }
5,274
25.243781
87
c
AMG
AMG-master/utilities/hypre_hopscotch_hash.h
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /** * Hopscotch hash is modified from the code downloaded from * https://sites.google.com/site/cconcurrencypackage/hopscotch-hashing * with the following terms of usage */ //////////////////////////////////////////////////////////////////////////////// //TERMS OF USAGE //------------------------------------------------------------------------------ // // Permission to use, copy, modify and distribute this software and // its documentation for any purpose is hereby granted without fee, // provided that due acknowledgments to the authors are provided and // this permission notice appears in all copies of the software. // The software is provided "as is". There is no warranty of any kind. // //Authors: // Maurice Herlihy // Brown University // and // Nir Shavit // Tel-Aviv University // and // Moran Tzafrir // Tel-Aviv University // // Date: July 15, 2008. // //////////////////////////////////////////////////////////////////////////////// // Programmer : Moran Tzafrir (MoranTza@gmail.com) // Modified : Jongsoo Park (jongsoo.park@intel.com) // Oct 1, 2015. // //////////////////////////////////////////////////////////////////////////////// #ifndef hypre_HOPSCOTCH_HASH_HEADER #define hypre_HOPSCOTCH_HASH_HEADER #include <stdio.h> #include <limits.h> #include <assert.h> #include <math.h> #ifdef HYPRE_USING_OPENMP #include <omp.h> #endif #include "_hypre_utilities.h" // Potentially architecture specific features used here: // __builtin_ffs // __sync_val_compare_and_swap #ifdef __cplusplus extern "C" { #endif /****************************************************************************** * This next section of code is here instead of in _hypre_utilities.h to get * around some portability issues with Visual Studio. By putting it here, we * can explicitly include this '.h' file in a few files in hypre and compile * them with C++ instead of C (VS does not support C99 'inline'). ******************************************************************************/ #ifdef HYPRE_USING_ATOMIC static inline HYPRE_Int hypre_compare_and_swap(HYPRE_Int *ptr, HYPRE_Int oldval, HYPRE_Int newval) { #if defined(__GNUC__) && defined(__GNUC_MINOR__) && defined(__GNUC_PATCHLEVEL__) && (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) > 40100 return __sync_val_compare_and_swap(ptr, oldval, newval); //#elif defind _MSC_VER //return _InterlockedCompareExchange((long *)ptr, newval, oldval); //#elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L && !defined(__STDC_NO_ATOMICS__) // JSP: not many compilers have implemented this, so comment out for now //_Atomic HYPRE_Int *atomic_ptr = ptr; //atomic_compare_exchange_strong(atomic_ptr, &oldval, newval); //return oldval; #endif } static inline HYPRE_Int hypre_fetch_and_add(HYPRE_Int *ptr, HYPRE_Int value) { #if defined(__GNUC__) && defined(__GNUC_MINOR__) && defined(__GNUC_PATCHLEVEL__) && (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) > 40100 return __sync_fetch_and_add(ptr, value); //#elif defined _MSC_VER //return _InterlockedExchangeAdd((long *)ptr, value); //#elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L && !defined(__STDC_NO_ATOMICS__) // JSP: not many compilers have implemented this, so comment out for now //_Atomic HYPRE_Int *atomic_ptr = ptr; //return atomic_fetch_add(atomic_ptr, value); #endif } #else // !HYPRE_USING_ATOMIC static inline HYPRE_Int hypre_compare_and_swap(HYPRE_Int *ptr, HYPRE_Int oldval, HYPRE_Int newval) { if (*ptr == oldval) { *ptr = newval; return oldval; } else return *ptr; } static inline HYPRE_Int hypre_fetch_and_add(HYPRE_Int *ptr, HYPRE_Int value) { HYPRE_Int oldval = *ptr; *ptr += value; return oldval; } #endif // !HYPRE_USING_ATOMIC /******************************************************************************/ // Constants ................................................................ #define HYPRE_HOPSCOTCH_HASH_HOP_RANGE (32) #define HYPRE_HOPSCOTCH_HASH_INSERT_RANGE (4*1024) #define HYPRE_HOPSCOTCH_HASH_EMPTY (0) #define HYPRE_HOPSCOTCH_HASH_BUSY (1) // Small Utilities .......................................................... #ifdef HYPRE_CONCURRENT_HOPSCOTCH static inline HYPRE_Int first_lsb_bit_indx(hypre_uint x) { if (0 == x) return -1; return __builtin_ffs(x) - 1; } #endif /** * hypre_Hash is adapted from xxHash with the following license. */ /* xxHash - Extremely Fast Hash algorithm Header File Copyright (C) 2012-2015, Yann Collet. BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. You can contact the author at : - xxHash source repository : https://github.com/Cyan4973/xxHash */ /*************************************** * Constants ***************************************/ #define HYPRE_XXH_PRIME32_1 2654435761U #define HYPRE_XXH_PRIME32_2 2246822519U #define HYPRE_XXH_PRIME32_3 3266489917U #define HYPRE_XXH_PRIME32_4 668265263U #define HYPRE_XXH_PRIME32_5 374761393U #define HYPRE_XXH_PRIME64_1 11400714785074694791ULL #define HYPRE_XXH_PRIME64_2 14029467366897019727ULL #define HYPRE_XXH_PRIME64_3 1609587929392839161ULL #define HYPRE_XXH_PRIME64_4 9650029242287828579ULL #define HYPRE_XXH_PRIME64_5 2870177450012600261ULL # define HYPRE_XXH_rotl32(x,r) ((x << r) | (x >> (32 - r))) # define HYPRE_XXH_rotl64(x,r) ((x << r) | (x >> (64 - r))) #ifdef HYPRE_BIGINT static inline HYPRE_Int hypre_Hash(HYPRE_Int input) { hypre_ulongint h64 = HYPRE_XXH_PRIME64_5 + sizeof(input); hypre_ulongint k1 = input; k1 *= HYPRE_XXH_PRIME64_2; k1 = HYPRE_XXH_rotl64(k1, 31); k1 *= HYPRE_XXH_PRIME64_1; h64 ^= k1; h64 = HYPRE_XXH_rotl64(h64, 27)*HYPRE_XXH_PRIME64_1 + HYPRE_XXH_PRIME64_4; h64 ^= h64 >> 33; h64 *= HYPRE_XXH_PRIME64_2; h64 ^= h64 >> 29; h64 *= HYPRE_XXH_PRIME64_3; h64 ^= h64 >> 32; #ifndef NDEBUG if (HYPRE_HOPSCOTCH_HASH_EMPTY == h64) { hypre_printf("hash(%lld) = %d\n", h64, HYPRE_HOPSCOTCH_HASH_EMPTY); assert(HYPRE_HOPSCOTCH_HASH_EMPTY != h64); } #endif return h64; } #else static inline HYPRE_Int hypre_Hash(HYPRE_Int input) { hypre_uint h32 = HYPRE_XXH_PRIME32_5 + sizeof(input); // 1665863975 is added to input so that // only -1073741824 gives HYPRE_HOPSCOTCH_HASH_EMPTY. // Hence, we're fine as long as key is non-negative. h32 += (input + 1665863975)*HYPRE_XXH_PRIME32_3; h32 = HYPRE_XXH_rotl32(h32, 17)*HYPRE_XXH_PRIME32_4; h32 ^= h32 >> 15; h32 *= HYPRE_XXH_PRIME32_2; h32 ^= h32 >> 13; h32 *= HYPRE_XXH_PRIME32_3; h32 ^= h32 >> 16; //assert(HYPRE_HOPSCOTCH_HASH_EMPTY != h32); return h32; } #endif static inline void hypre_UnorderedIntSetFindCloserFreeBucket( hypre_UnorderedIntSet *s, #ifdef HYPRE_CONCURRENT_HOPSCOTCH hypre_HopscotchSegment* start_seg, #endif HYPRE_Int *free_bucket, HYPRE_Int *free_dist ) { HYPRE_Int move_bucket = *free_bucket - (HYPRE_HOPSCOTCH_HASH_HOP_RANGE - 1); HYPRE_Int move_free_dist; for (move_free_dist = HYPRE_HOPSCOTCH_HASH_HOP_RANGE - 1; move_free_dist > 0; --move_free_dist) { hypre_uint start_hop_info = s->hopInfo[move_bucket]; HYPRE_Int move_new_free_dist = -1; hypre_uint mask = 1; HYPRE_Int i; for (i = 0; i < move_free_dist; ++i, mask <<= 1) { if (mask & start_hop_info) { move_new_free_dist = i; break; } } if (-1 != move_new_free_dist) { #ifdef HYPRE_CONCURRENT_HOPSCOTCH hypre_HopscotchSegment* move_segment = &(s->segments[move_bucket & s->segmentMask]); if(start_seg != move_segment) omp_set_lock(&move_segment->lock); #endif if (start_hop_info == s->hopInfo[move_bucket]) { // new_free_bucket -> free_bucket and empty new_free_bucket HYPRE_Int new_free_bucket = move_bucket + move_new_free_dist; s->key[*free_bucket] = s->key[new_free_bucket]; s->hash[*free_bucket] = s->hash[new_free_bucket]; #ifdef HYPRE_CONCURRENT_HOPSCOTCH ++move_segment->timestamp; #pragma omp flush #endif s->hopInfo[move_bucket] |= (1U << move_free_dist); s->hopInfo[move_bucket] &= ~(1U << move_new_free_dist); *free_bucket = new_free_bucket; *free_dist -= move_free_dist - move_new_free_dist; #ifdef HYPRE_CONCURRENT_HOPSCOTCH if(start_seg != move_segment) omp_unset_lock(&move_segment->lock); #endif return; } #ifdef HYPRE_CONCURRENT_HOPSCOTCH if(start_seg != move_segment) omp_unset_lock(&move_segment->lock); #endif } ++move_bucket; } *free_bucket = -1; *free_dist = 0; } static inline void hypre_UnorderedIntMapFindCloserFreeBucket( hypre_UnorderedIntMap *m, #ifdef HYPRE_CONCURRENT_HOPSCOTCH hypre_HopscotchSegment* start_seg, #endif hypre_HopscotchBucket** free_bucket, HYPRE_Int* free_dist) { hypre_HopscotchBucket* move_bucket = *free_bucket - (HYPRE_HOPSCOTCH_HASH_HOP_RANGE - 1); HYPRE_Int move_free_dist; for (move_free_dist = HYPRE_HOPSCOTCH_HASH_HOP_RANGE - 1; move_free_dist > 0; --move_free_dist) { hypre_uint start_hop_info = move_bucket->hopInfo; HYPRE_Int move_new_free_dist = -1; hypre_uint mask = 1; HYPRE_Int i; for (i = 0; i < move_free_dist; ++i, mask <<= 1) { if (mask & start_hop_info) { move_new_free_dist = i; break; } } if (-1 != move_new_free_dist) { #ifdef HYPRE_CONCURRENT_HOPSCOTCH hypre_HopscotchSegment* move_segment = &(m->segments[(move_bucket - m->table) & m->segmentMask]); if (start_seg != move_segment) omp_set_lock(&move_segment->lock); #endif if (start_hop_info == move_bucket->hopInfo) { // new_free_bucket -> free_bucket and empty new_free_bucket hypre_HopscotchBucket* new_free_bucket = move_bucket + move_new_free_dist; (*free_bucket)->data = new_free_bucket->data; (*free_bucket)->key = new_free_bucket->key; (*free_bucket)->hash = new_free_bucket->hash; #ifdef HYPRE_CONCURRENT_HOPSCOTCH ++move_segment->timestamp; #pragma omp flush #endif move_bucket->hopInfo |= (1U << move_free_dist); move_bucket->hopInfo &= ~(1U << move_new_free_dist); *free_bucket = new_free_bucket; *free_dist -= move_free_dist - move_new_free_dist; #ifdef HYPRE_CONCURRENT_HOPSCOTCH if(start_seg != move_segment) omp_unset_lock(&move_segment->lock); #endif return; } #ifdef HYPRE_CONCURRENT_HOPSCOTCH if(start_seg != move_segment) omp_unset_lock(&move_segment->lock); #endif } ++move_bucket; } *free_bucket = NULL; *free_dist = 0; } void hypre_UnorderedIntSetCreate( hypre_UnorderedIntSet *s, HYPRE_Int inCapacity, HYPRE_Int concurrencyLevel); void hypre_UnorderedIntMapCreate( hypre_UnorderedIntMap *m, HYPRE_Int inCapacity, HYPRE_Int concurrencyLevel); void hypre_UnorderedIntSetDestroy( hypre_UnorderedIntSet *s ); void hypre_UnorderedIntMapDestroy( hypre_UnorderedIntMap *m ); // Query Operations ......................................................... #ifdef HYPRE_CONCURRENT_HOPSCOTCH static inline HYPRE_Int hypre_UnorderedIntSetContains( hypre_UnorderedIntSet *s, HYPRE_Int key ) { //CALCULATE HASH .......................... HYPRE_Int hash = hypre_Hash(key); //CHECK IF ALREADY CONTAIN ................ hypre_HopscotchSegment *segment = &s->segments[hash & s->segmentMask]; HYPRE_Int bucket = hash & s->bucketMask; hypre_uint hopInfo = s->hopInfo[bucket]; if (0 == hopInfo) return 0; else if (1 == hopInfo ) { if (hash == s->hash[bucket] && key == s->key[bucket]) return 1; else return 0; } HYPRE_Int startTimestamp = segment->timestamp; while (0 != hopInfo) { HYPRE_Int i = first_lsb_bit_indx(hopInfo); HYPRE_Int currElm = bucket + i; if (hash == s->hash[currElm] && key == s->key[currElm]) return 1; hopInfo &= ~(1U << i); } if (segment->timestamp == startTimestamp) return 0; HYPRE_Int i; for (i = 0; i< HYPRE_HOPSCOTCH_HASH_HOP_RANGE; ++i) { if (hash == s->hash[bucket + i] && key == s->key[bucket + i]) return 1; } return 0; } /** * @ret -1 if key doesn't exist */ static inline HYPRE_Int hypre_UnorderedIntMapGet( hypre_UnorderedIntMap *m, HYPRE_Int key) { //CALCULATE HASH .......................... HYPRE_Int hash = hypre_Hash(key); //CHECK IF ALREADY CONTAIN ................ hypre_HopscotchSegment *segment = &m->segments[hash & m->segmentMask]; hypre_HopscotchBucket *elmAry = &(m->table[hash & m->bucketMask]); hypre_uint hopInfo = elmAry->hopInfo; if (0 == hopInfo) return -1; else if (1 == hopInfo ) { if (hash == elmAry->hash && key == elmAry->key) return elmAry->data; else return -1; } HYPRE_Int startTimestamp = segment->timestamp; while (0 != hopInfo) { HYPRE_Int i = first_lsb_bit_indx(hopInfo); hypre_HopscotchBucket* currElm = elmAry + i; if (hash == currElm->hash && key == currElm->key) return currElm->data; hopInfo &= ~(1U << i); } if (segment->timestamp == startTimestamp) return -1; hypre_HopscotchBucket *currBucket = &(m->table[hash & m->bucketMask]); HYPRE_Int i; for (i = 0; i< HYPRE_HOPSCOTCH_HASH_HOP_RANGE; ++i, ++currBucket) { if (hash == currBucket->hash && key == currBucket->key) return currBucket->data; } return -1; } #endif //status Operations ......................................................... static inline HYPRE_Int hypre_UnorderedIntSetSize(hypre_UnorderedIntSet *s) { HYPRE_Int counter = 0; HYPRE_Int n = s->bucketMask + HYPRE_HOPSCOTCH_HASH_INSERT_RANGE; HYPRE_Int i; for (i = 0; i < n; ++i) { if (HYPRE_HOPSCOTCH_HASH_EMPTY != s->hash[i]) { ++counter; } } return counter; } static inline HYPRE_Int hypre_UnorderedIntMapSize(hypre_UnorderedIntMap *m) { HYPRE_Int counter = 0; HYPRE_Int n = m->bucketMask + HYPRE_HOPSCOTCH_HASH_INSERT_RANGE; HYPRE_Int i; for (i = 0; i < n; ++i) { if( HYPRE_HOPSCOTCH_HASH_EMPTY != m->table[i].hash ) { ++counter; } } return counter; } HYPRE_Int *hypre_UnorderedIntSetCopyToArray( hypre_UnorderedIntSet *s, HYPRE_Int *len ); //modification Operations ................................................... #ifdef HYPRE_CONCURRENT_HOPSCOTCH static inline void hypre_UnorderedIntSetPut( hypre_UnorderedIntSet *s, HYPRE_Int key ) { //CALCULATE HASH .......................... HYPRE_Int hash = hypre_Hash(key); //LOCK KEY HASH ENTERY .................... hypre_HopscotchSegment *segment = &s->segments[hash & s->segmentMask]; omp_set_lock(&segment->lock); HYPRE_Int bucket = hash&s->bucketMask; //CHECK IF ALREADY CONTAIN ................ hypre_uint hopInfo = s->hopInfo[bucket]; while (0 != hopInfo) { HYPRE_Int i = first_lsb_bit_indx(hopInfo); HYPRE_Int currElm = bucket + i; if(hash == s->hash[currElm] && key == s->key[currElm]) { omp_unset_lock(&segment->lock); return; } hopInfo &= ~(1U << i); } //LOOK FOR FREE BUCKET .................... HYPRE_Int free_bucket = bucket; HYPRE_Int free_dist = 0; for ( ; free_dist < HYPRE_HOPSCOTCH_HASH_INSERT_RANGE; ++free_dist, ++free_bucket) { if( (HYPRE_HOPSCOTCH_HASH_EMPTY == s->hash[free_bucket]) && (HYPRE_HOPSCOTCH_HASH_EMPTY == hypre_compare_and_swap((HYPRE_Int *)&s->hash[free_bucket], (HYPRE_Int)HYPRE_HOPSCOTCH_HASH_EMPTY, (HYPRE_Int)HYPRE_HOPSCOTCH_HASH_BUSY)) ) break; } //PLACE THE NEW KEY ....................... if (free_dist < HYPRE_HOPSCOTCH_HASH_INSERT_RANGE) { do { if (free_dist < HYPRE_HOPSCOTCH_HASH_HOP_RANGE) { s->key[free_bucket] = key; s->hash[free_bucket] = hash; s->hopInfo[bucket] |= 1U << free_dist; omp_unset_lock(&segment->lock); return; } hypre_UnorderedIntSetFindCloserFreeBucket(s, segment, &free_bucket, &free_dist); } while (-1 != free_bucket); } //NEED TO RESIZE .......................... hypre_error_w_msg(HYPRE_ERROR_GENERIC,"ERROR - RESIZE is not implemented\n"); /*fprintf(stderr, "ERROR - RESIZE is not implemented\n");*/ exit(1); return; } static inline HYPRE_Int hypre_UnorderedIntMapPutIfAbsent( hypre_UnorderedIntMap *m, HYPRE_Int key, HYPRE_Int data) { //CALCULATE HASH .......................... HYPRE_Int hash = hypre_Hash(key); //LOCK KEY HASH ENTERY .................... hypre_HopscotchSegment *segment = &m->segments[hash & m->segmentMask]; omp_set_lock(&segment->lock); hypre_HopscotchBucket* startBucket = &(m->table[hash & m->bucketMask]); //CHECK IF ALREADY CONTAIN ................ hypre_uint hopInfo = startBucket->hopInfo; while (0 != hopInfo) { HYPRE_Int i = first_lsb_bit_indx(hopInfo); hypre_HopscotchBucket* currElm = startBucket + i; if (hash == currElm->hash && key == currElm->key) { HYPRE_Int rc = currElm->data; omp_unset_lock(&segment->lock); return rc; } hopInfo &= ~(1U << i); } //LOOK FOR FREE BUCKET .................... hypre_HopscotchBucket* free_bucket = startBucket; HYPRE_Int free_dist = 0; for ( ; free_dist < HYPRE_HOPSCOTCH_HASH_INSERT_RANGE; ++free_dist, ++free_bucket) { if( (HYPRE_HOPSCOTCH_HASH_EMPTY == free_bucket->hash) && (HYPRE_HOPSCOTCH_HASH_EMPTY == __sync_val_compare_and_swap((HYPRE_Int *)&free_bucket->hash, (HYPRE_Int)HYPRE_HOPSCOTCH_HASH_EMPTY, (HYPRE_Int)HYPRE_HOPSCOTCH_HASH_BUSY)) ) break; } //PLACE THE NEW KEY ....................... if (free_dist < HYPRE_HOPSCOTCH_HASH_INSERT_RANGE) { do { if (free_dist < HYPRE_HOPSCOTCH_HASH_HOP_RANGE) { free_bucket->data = data; free_bucket->key = key; free_bucket->hash = hash; startBucket->hopInfo |= 1U << free_dist; omp_unset_lock(&segment->lock); return HYPRE_HOPSCOTCH_HASH_EMPTY; } hypre_UnorderedIntMapFindCloserFreeBucket(m, segment, &free_bucket, &free_dist); } while (NULL != free_bucket); } //NEED TO RESIZE .......................... hypre_error_w_msg(HYPRE_ERROR_GENERIC,"ERROR - RESIZE is not implemented\n"); /*fprintf(stderr, "ERROR - RESIZE is not implemented\n");*/ exit(1); return HYPRE_HOPSCOTCH_HASH_EMPTY; } #endif #ifdef __cplusplus } // extern "C" #endif #endif // hypre_HOPSCOTCH_HASH_HEADER
21,351
31.798771
233
h
AMG
AMG-master/utilities/hypre_memory.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /****************************************************************************** * * Memory management utilities * *****************************************************************************/ #include "_hypre_utilities.h" #ifdef HYPRE_USE_UMALLOC #undef HYPRE_USE_UMALLOC #endif /****************************************************************************** * * Standard routines * *****************************************************************************/ /*-------------------------------------------------------------------------- * hypre_OutOfMemory *--------------------------------------------------------------------------*/ HYPRE_Int hypre_OutOfMemory( size_t size ) { hypre_printf("Out of memory trying to allocate %d bytes\n", (HYPRE_Int) size); fflush(stdout); hypre_error(HYPRE_ERROR_MEMORY); return 0; } /*-------------------------------------------------------------------------- * hypre_MAlloc *--------------------------------------------------------------------------*/ char * hypre_MAlloc( size_t size ) { void *ptr; if (size > 0) { #ifdef HYPRE_USE_UMALLOC HYPRE_Int threadid = hypre_GetThreadID(); ptr = _umalloc_(size); #else ptr = malloc(size); #endif #if 1 if (ptr == NULL) { hypre_OutOfMemory(size); } #endif } else { ptr = NULL; } return (char*)ptr; } /*-------------------------------------------------------------------------- * hypre_CAlloc *--------------------------------------------------------------------------*/ char * hypre_CAlloc( size_t count, size_t elt_size ) { void *ptr; size_t size = count*elt_size; if (size > 0) { #ifdef HYPRE_USE_UMALLOC HYPRE_Int threadid = hypre_GetThreadID(); ptr = _ucalloc_(count, elt_size); #else ptr = calloc(count, elt_size); #endif #if 1 if (ptr == NULL) { hypre_OutOfMemory(size); } #endif } else { ptr = NULL; } return(char*) ptr; } /*-------------------------------------------------------------------------- * hypre_ReAlloc *--------------------------------------------------------------------------*/ char * hypre_ReAlloc( char *ptr, size_t size ) { #ifdef HYPRE_USE_UMALLOC if (ptr == NULL) { ptr = hypre_MAlloc(size); } else if (size == 0) { hypre_Free(ptr); } else { HYPRE_Int threadid = hypre_GetThreadID(); ptr = (char*)_urealloc_(ptr, size); } #else if (ptr == NULL) { ptr = (char*)malloc(size); } else { ptr = (char*)realloc(ptr, size); } #endif #if 1 if ((ptr == NULL) && (size > 0)) { hypre_OutOfMemory(size); } #endif return ptr; } /*-------------------------------------------------------------------------- * hypre_Free *--------------------------------------------------------------------------*/ void hypre_Free( char *ptr ) { if (ptr) { #ifdef HYPRE_USE_UMALLOC HYPRE_Int threadid = hypre_GetThreadID(); _ufree_(ptr); #else free(ptr); #endif } }
4,033
21.164835
81
c
AMG
AMG-master/utilities/hypre_memory.h
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /****************************************************************************** * * Header file for memory management utilities * *****************************************************************************/ #ifndef hypre_MEMORY_HEADER #define hypre_MEMORY_HEADER #include <stdio.h> #include <stdlib.h> #ifdef __cplusplus extern "C" { #endif /*-------------------------------------------------------------------------- * Use "Debug Malloc Library", dmalloc *--------------------------------------------------------------------------*/ #ifdef HYPRE_MEMORY_DMALLOC #define hypre_InitMemoryDebug(id) hypre_InitMemoryDebugDML(id) #define hypre_FinalizeMemoryDebug() hypre_FinalizeMemoryDebugDML() #define hypre_TAlloc(type, count) \ ( (type *)hypre_MAllocDML((size_t)(sizeof(type) * (count)),\ __FILE__, __LINE__) ) #define hypre_CTAlloc(type, count) \ ( (type *)hypre_CAllocDML((size_t)(count), (size_t)sizeof(type),\ __FILE__, __LINE__) ) #define hypre_TReAlloc(ptr, type, count) \ ( (type *)hypre_ReAllocDML((char *)ptr,\ (size_t)(sizeof(type) * (count)),\ __FILE__, __LINE__) ) #define hypre_TFree(ptr) \ ( hypre_FreeDML((char *)ptr, __FILE__, __LINE__), ptr = NULL ) /*-------------------------------------------------------------------------- * Use standard memory routines *--------------------------------------------------------------------------*/ #else #define hypre_InitMemoryDebug(id) #define hypre_FinalizeMemoryDebug() #define hypre_TAlloc(type, count) \ ( (type *)hypre_MAlloc((size_t)(sizeof(type) * (count))) ) #define hypre_CTAlloc(type, count) \ ( (type *)hypre_CAlloc((size_t)(count), (size_t)sizeof(type)) ) #define hypre_TReAlloc(ptr, type, count) \ ( (type *)hypre_ReAlloc((char *)ptr, (size_t)(sizeof(type) * (count))) ) #define hypre_TFree(ptr) \ ( hypre_Free((char *)ptr), ptr = NULL ) #endif #define hypre_SharedTAlloc(type, count) hypre_TAlloc(type, (count)) #define hypre_SharedCTAlloc(type, count) hypre_CTAlloc(type, (count)) #define hypre_SharedTReAlloc(type, count) hypre_TReAlloc(type, (count)) #define hypre_SharedTFree(ptr) hypre_TFree(ptr) /*-------------------------------------------------------------------------- * Prototypes *--------------------------------------------------------------------------*/ /* hypre_memory.c */ HYPRE_Int hypre_OutOfMemory ( size_t size ); char *hypre_MAlloc ( size_t size ); char *hypre_CAlloc ( size_t count , size_t elt_size ); char *hypre_ReAlloc ( char *ptr , size_t size ); void hypre_Free ( char *ptr ); char *hypre_SharedMAlloc ( size_t size ); char *hypre_SharedCAlloc ( size_t count , size_t elt_size ); char *hypre_SharedReAlloc ( char *ptr , size_t size ); void hypre_SharedFree ( char *ptr ); HYPRE_Real *hypre_IncrementSharedDataPtr ( HYPRE_Real *ptr , size_t size ); /* memory_dmalloc.c */ HYPRE_Int hypre_InitMemoryDebugDML( HYPRE_Int id ); HYPRE_Int hypre_FinalizeMemoryDebugDML( void ); char *hypre_MAllocDML( HYPRE_Int size , char *file , HYPRE_Int line ); char *hypre_CAllocDML( HYPRE_Int count , HYPRE_Int elt_size , char *file , HYPRE_Int line ); char *hypre_ReAllocDML( char *ptr , HYPRE_Int size , char *file , HYPRE_Int line ); void hypre_FreeDML( char *ptr , char *file , HYPRE_Int line ); #ifdef __cplusplus } #endif #endif
4,292
35.692308
92
h
AMG
AMG-master/utilities/hypre_merge_sort.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Jongsoo Park et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ #include "_hypre_utilities.h" #include "hypre_hopscotch_hash.h" #include "../seq_mv/HYPRE_seq_mv.h" //#define DBG_MERGE_SORT #ifdef DBG_MERGE_SORT #include <assert.h> #include <algorithm> #include <unordered_map> #endif #define SWAP(T, a, b) do { T tmp = a; a = b; b = tmp; } while (0) static void hypre_merge(HYPRE_Int *first1, HYPRE_Int *last1, HYPRE_Int *first2, HYPRE_Int *last2, HYPRE_Int *out) { for ( ; first1 != last1; ++out) { if (first2 == last2) { for ( ; first1 != last1; ++first1, ++out) { *out = *first1; } return; } if (*first2 < *first1) { *out = *first2; ++first2; } else { *out = *first1; ++first1; } } for ( ; first2 != last2; ++first2, ++out) { *out = *first2; } } static void kth_element_( HYPRE_Int *out1, HYPRE_Int *out2, HYPRE_Int *a1, HYPRE_Int *a2, HYPRE_Int left, HYPRE_Int right, HYPRE_Int n1, HYPRE_Int n2, HYPRE_Int k) { while (1) { HYPRE_Int i = (left + right)/2; // right < k -> i < k HYPRE_Int j = k - i - 1; #ifdef DBG_MERGE_SORT assert(left <= right && right <= k); assert(i < k); // i == k implies left == right == k that can never happen assert(j >= 0 && j < n2); #endif if ((j == -1 || a1[i] >= a2[j]) && (j == n2 - 1 || a1[i] <= a2[j + 1])) { *out1 = i; *out2 = j + 1; return; } else if (j >= 0 && a2[j] >= a1[i] && (i == n1 - 1 || a2[j] <= a1[i + 1])) { *out1 = i + 1; *out2 = j; return; } else if (a1[i] > a2[j] && j != n2 - 1 && a1[i] > a2[j+1]) { // search in left half of a1 right = i - 1; } else { // search in right half of a1 left = i + 1; } } } /** * Partition the input so that * a1[0:*out1) and a2[0:*out2) contain the smallest k elements */ static void kth_element( HYPRE_Int *out1, HYPRE_Int *out2, HYPRE_Int *a1, HYPRE_Int *a2, HYPRE_Int n1, HYPRE_Int n2, HYPRE_Int k) { // either of the inputs is empty if (n1 == 0) { *out1 = 0; *out2 = k; return; } if (n2 == 0) { *out1 = k; *out2 = 0; return; } if (k >= n1 + n2) { *out1 = n1; *out2 = n2; return; } // one is greater than the other if (k < n1 && a1[k] <= a2[0]) { *out1 = k; *out2 = 0; return; } if (k - n1 >= 0 && a2[k - n1] >= a1[n1 - 1]) { *out1 = n1; *out2 = k - n1; return; } if (k < n2 && a2[k] <= a1[0]) { *out1 = 0; *out2 = k; return; } if (k - n2 >= 0 && a1[k - n2] >= a2[n2 - 1]) { *out1 = k - n2; *out2 = n2; return; } // now k > 0 // faster to do binary search on the shorter sequence if (n1 > n2) { SWAP(HYPRE_Int, n1, n2); SWAP(HYPRE_Int *, a1, a2); SWAP(HYPRE_Int *, out1, out2); } if (k < (n1 + n2)/2) { kth_element_(out1, out2, a1, a2, 0, hypre_min(n1 - 1, k), n1, n2, k); } else { // when k is big, faster to find (n1 + n2 - k)th biggest element HYPRE_Int offset1 = hypre_max(k - n2, 0), offset2 = hypre_max(k - n1, 0); HYPRE_Int new_k = k - offset1 - offset2; HYPRE_Int new_n1 = hypre_min(n1 - offset1, new_k + 1); HYPRE_Int new_n2 = hypre_min(n2 - offset2, new_k + 1); kth_element_(out1, out2, a1 + offset1, a2 + offset2, 0, new_n1 - 1, new_n1, new_n2, new_k); *out1 += offset1; *out2 += offset2; } #ifdef DBG_MERGE_SORT assert(*out1 + *out2 == k); #endif } /** * @param num_threads number of threads that participate in this merge * @param my_thread_num thread id (zeor-based) among the threads that participate in this merge */ static void hypre_parallel_merge( HYPRE_Int *first1, HYPRE_Int *last1, HYPRE_Int *first2, HYPRE_Int *last2, HYPRE_Int *out, HYPRE_Int num_threads, HYPRE_Int my_thread_num) { HYPRE_Int n1 = last1 - first1; HYPRE_Int n2 = last2 - first2; HYPRE_Int n = n1 + n2; HYPRE_Int n_per_thread = (n + num_threads - 1)/num_threads; HYPRE_Int begin_rank = hypre_min(n_per_thread*my_thread_num, n); HYPRE_Int end_rank = hypre_min(begin_rank + n_per_thread, n); #ifdef DBG_MERGE_SORT assert(std::is_sorted(first1, last1)); assert(std::is_sorted(first2, last2)); #endif HYPRE_Int begin1, begin2, end1, end2; kth_element(&begin1, &begin2, first1, first2, n1, n2, begin_rank); kth_element(&end1, &end2, first1, first2, n1, n2, end_rank); while (begin1 > end1 && begin1 > 0 && begin2 < n2 && first1[begin1 - 1] == first2[begin2]) { #ifdef DBG_MERGE_SORT printf("%s:%d\n", __FILE__, __LINE__); #endif begin1--; begin2++; } while (begin2 > end2 && end1 > 0 && end2 < n2 && first1[end1 - 1] == first2[end2]) { #ifdef DBG_MERGE_SORT printf("%s:%d\n", __FILE__, __LINE__); #endif end1--; end2++; } #ifdef DBG_MERGE_SORT assert(begin1 <= end1); assert(begin2 <= end2); #endif hypre_merge( first1 + begin1, first1 + end1, first2 + begin2, first2 + end2, out + begin1 + begin2); #ifdef DBG_MERGE_SORT assert(std::is_sorted(out + begin1 + begin2, out + end1 + end2)); #endif } void hypre_merge_sort(HYPRE_Int *in, HYPRE_Int *temp, HYPRE_Int len, HYPRE_Int **out) { if (0 == len) return; #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_MERGE] -= hypre_MPI_Wtime(); #endif #ifdef DBG_MERGE_SORT HYPRE_Int *dbg_buf = new HYPRE_Int[len]; std::copy(in, in + len, dbg_buf); std::sort(dbg_buf, dbg_buf + len); #endif // HYPRE_Int thread_private_len[hypre_NumThreads()]; // HYPRE_Int out_len = 0; #ifdef HYPRE_USING_OPENMP #pragma omp parallel #endif { HYPRE_Int num_threads = hypre_NumActiveThreads(); HYPRE_Int my_thread_num = hypre_GetThreadNum(); // thread-private sort HYPRE_Int i_per_thread = (len + num_threads - 1)/num_threads; HYPRE_Int i_begin = hypre_min(i_per_thread*my_thread_num, len); HYPRE_Int i_end = hypre_min(i_begin + i_per_thread, len); hypre_qsort0(in, i_begin, i_end - 1); // merge sorted sequences HYPRE_Int in_group_size; HYPRE_Int *in_buf = in; HYPRE_Int *out_buf = temp; for (in_group_size = 1; in_group_size < num_threads; in_group_size *= 2) { #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif // merge 2 in-groups into 1 out-group HYPRE_Int out_group_size = in_group_size*2; HYPRE_Int group_leader = my_thread_num/out_group_size*out_group_size; // HYPRE_Int group_sub_leader = hypre_min(group_leader + in_group_size, num_threads - 1); HYPRE_Int id_in_group = my_thread_num%out_group_size; HYPRE_Int num_threads_in_group = hypre_min(group_leader + out_group_size, num_threads) - group_leader; HYPRE_Int in_group1_begin = hypre_min(i_per_thread*group_leader, len); HYPRE_Int in_group1_end = hypre_min(in_group1_begin + i_per_thread*in_group_size, len); HYPRE_Int in_group2_begin = hypre_min(in_group1_begin + i_per_thread*in_group_size, len); HYPRE_Int in_group2_end = hypre_min(in_group2_begin + i_per_thread*in_group_size, len); hypre_parallel_merge( in_buf + in_group1_begin, in_buf + in_group1_end, in_buf + in_group2_begin, in_buf + in_group2_end, out_buf + in_group1_begin, num_threads_in_group, id_in_group); HYPRE_Int *temp = in_buf; in_buf = out_buf; out_buf = temp; } *out = in_buf; } /* omp parallel */ #ifdef DBG_MERGE_SORT assert(std::equal(*out, *out + len, dbg_buf)); delete[] dbg_buf; #endif #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_MERGE] += hypre_MPI_Wtime(); #endif } #ifdef HYPRE_CONCURRENT_HOPSCOTCH void hypre_sort_and_create_inverse_map( HYPRE_Int *in, HYPRE_Int len, HYPRE_Int **out, hypre_UnorderedIntMap *inverse_map) { if (len == 0) { return; } #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_MERGE] -= hypre_MPI_Wtime(); #endif HYPRE_Int *temp = hypre_TAlloc(HYPRE_Int, len); hypre_merge_sort(in, temp, len, out); hypre_UnorderedIntMapCreate(inverse_map, 2*len, 16*hypre_NumThreads()); HYPRE_Int i; #pragma omp parallel for HYPRE_SMP_SCHEDULE for (i = 0; i < len; i++) { HYPRE_Int old = hypre_UnorderedIntMapPutIfAbsent(inverse_map, (*out)[i], i); assert(old == HYPRE_HOPSCOTCH_HASH_EMPTY); #ifdef DBG_MERGE_SORT if (hypre_UnorderedIntMapGet(inverse_map, (*out)[i]) != i) { fprintf(stderr, "%d %d\n", i, (*out)[i]); assert(false); } #endif } #ifdef DBG_MERGE_SORT std::unordered_map<HYPRE_Int, HYPRE_Int> inverse_map2(len); for (HYPRE_Int i = 0; i < len; ++i) { inverse_map2[(*out)[i]] = i; if (hypre_UnorderedIntMapGet(inverse_map, (*out)[i]) != i) { fprintf(stderr, "%d %d\n", i, (*out)[i]); assert(false); } } assert(hypre_UnorderedIntMapSize(inverse_map) == len); #endif if (*out == in) { hypre_TFree(temp); } else { hypre_TFree(in); } #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_MERGE] += hypre_MPI_Wtime(); #endif } #endif /* vim: set tabstop=8 softtabstop=3 sw=3 expandtab: */
10,278
26.706199
113
c
AMG
AMG-master/utilities/hypre_prefix_sum.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Jongsoo Park et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ #include "_hypre_utilities.h" void hypre_prefix_sum(HYPRE_Int *in_out, HYPRE_Int *sum, HYPRE_Int *workspace) { #ifdef HYPRE_USING_OPENMP HYPRE_Int my_thread_num = hypre_GetThreadNum(); HYPRE_Int num_threads = hypre_NumActiveThreads(); hypre_assert(1 == num_threads || omp_in_parallel()); workspace[my_thread_num + 1] = *in_out; #pragma omp barrier #pragma omp master { HYPRE_Int i; workspace[0] = 0; for (i = 1; i < num_threads; i++) { workspace[i + 1] += workspace[i]; } *sum = workspace[num_threads]; } #pragma omp barrier *in_out = workspace[my_thread_num]; #else /* !HYPRE_USING_OPENMP */ *sum = *in_out; *in_out = 0; workspace[0] = 0; workspace[1] = *sum; #endif /* !HYPRE_USING_OPENMP */ } void hypre_prefix_sum_pair(HYPRE_Int *in_out1, HYPRE_Int *sum1, HYPRE_Int *in_out2, HYPRE_Int *sum2, HYPRE_Int *workspace) { #ifdef HYPRE_USING_OPENMP HYPRE_Int my_thread_num = hypre_GetThreadNum(); HYPRE_Int num_threads = hypre_NumActiveThreads(); hypre_assert(1 == num_threads || omp_in_parallel()); workspace[(my_thread_num + 1)*2] = *in_out1; workspace[(my_thread_num + 1)*2 + 1] = *in_out2; #pragma omp barrier #pragma omp master { HYPRE_Int i; workspace[0] = 0; workspace[1] = 0; for (i = 1; i < num_threads; i++) { workspace[(i + 1)*2] += workspace[i*2]; workspace[(i + 1)*2 + 1] += workspace[i*2 + 1]; } *sum1 = workspace[num_threads*2]; *sum2 = workspace[num_threads*2 + 1]; } #pragma omp barrier *in_out1 = workspace[my_thread_num*2]; *in_out2 = workspace[my_thread_num*2 + 1]; #else /* !HYPRE_USING_OPENMP */ *sum1 = *in_out1; *sum2 = *in_out2; *in_out1 = 0; *in_out2 = 0; workspace[0] = 0; workspace[1] = 0; workspace[2] = *sum1; workspace[3] = *sum2; #endif /* !HYPRE_USING_OPENMP */ } void hypre_prefix_sum_triple(HYPRE_Int *in_out1, HYPRE_Int *sum1, HYPRE_Int *in_out2, HYPRE_Int *sum2, HYPRE_Int *in_out3, HYPRE_Int *sum3, HYPRE_Int *workspace) { #ifdef HYPRE_USING_OPENMP HYPRE_Int my_thread_num = hypre_GetThreadNum(); HYPRE_Int num_threads = hypre_NumActiveThreads(); hypre_assert(1 == num_threads || omp_in_parallel()); workspace[(my_thread_num + 1)*3] = *in_out1; workspace[(my_thread_num + 1)*3 + 1] = *in_out2; workspace[(my_thread_num + 1)*3 + 2] = *in_out3; #pragma omp barrier #pragma omp master { HYPRE_Int i; workspace[0] = 0; workspace[1] = 0; workspace[2] = 0; for (i = 1; i < num_threads; i++) { workspace[(i + 1)*3] += workspace[i*3]; workspace[(i + 1)*3 + 1] += workspace[i*3 + 1]; workspace[(i + 1)*3 + 2] += workspace[i*3 + 2]; } *sum1 = workspace[num_threads*3]; *sum2 = workspace[num_threads*3 + 1]; *sum3 = workspace[num_threads*3 + 2]; } #pragma omp barrier *in_out1 = workspace[my_thread_num*3]; *in_out2 = workspace[my_thread_num*3 + 1]; *in_out3 = workspace[my_thread_num*3 + 2]; #else /* !HYPRE_USING_OPENMP */ *sum1 = *in_out1; *sum2 = *in_out2; *sum3 = *in_out3; *in_out1 = 0; *in_out2 = 0; *in_out3 = 0; workspace[0] = 0; workspace[1] = 0; workspace[2] = 0; workspace[3] = *sum1; workspace[4] = *sum2; workspace[5] = *sum3; #endif /* !HYPRE_USING_OPENMP */ } void hypre_prefix_sum_multiple(HYPRE_Int *in_out, HYPRE_Int *sum, HYPRE_Int n, HYPRE_Int *workspace) { HYPRE_Int i; #ifdef HYPRE_USING_OPENMP HYPRE_Int my_thread_num = hypre_GetThreadNum(); HYPRE_Int num_threads = hypre_NumActiveThreads(); hypre_assert(1 == num_threads || omp_in_parallel()); for (i = 0; i < n; i++) { workspace[(my_thread_num + 1)*n + i] = in_out[i]; } #pragma omp barrier #pragma omp master { HYPRE_Int t; for (i = 0; i < n; i++) { workspace[i] = 0; } // assuming n is not so big, we don't parallelize this loop for (t = 1; t < num_threads; t++) { for (i = 0; i < n; i++) { workspace[(t + 1)*n + i] += workspace[t*n + i]; } } for (i = 0; i < n; i++) { sum[i] = workspace[num_threads*n + i]; } } #pragma omp barrier for (i = 0; i < n; i++) { in_out[i] = workspace[my_thread_num*n + i]; } #else /* !HYPRE_USING_OPENMP */ for (i = 0; i < n; i++) { sum[i] = in_out[i]; in_out[i] = 0; workspace[i] = 0; workspace[n + i] = sum[i]; } #endif /* !HYPRE_USING_OPENMP */ }
5,468
26.621212
161
c
AMG
AMG-master/utilities/hypre_printf.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ #include "_hypre_utilities.h" #include <stdarg.h> #include <stdio.h> // #ifdef HYPRE_BIGINT /* these prototypes are missing by default for some compilers */ int vscanf( const char *format , va_list arg ); int vfscanf( FILE *stream , const char *format, va_list arg ); int vsscanf( const char *s , const char *format, va_list arg ); HYPRE_Int new_format( const char *format, char **newformat_ptr ) { const char *fp; char *newformat, *nfp; HYPRE_Int newformatlen; HYPRE_Int foundpercent = 0; newformatlen = 2*strlen(format)+1; /* worst case is all %d's to %lld's */ newformat = hypre_TAlloc(char, newformatlen); nfp = newformat; for (fp = format; *fp != '\0'; fp++) { if (*fp == '%') { foundpercent = 1; } else if (foundpercent) { if (*fp == 'l') { fp++; /* remove 'l' and maybe add it back in switch statement */ if (*fp == 'l') { fp++; /* remove second 'l' if present */ } } switch(*fp) { case 'd': case 'i': #if defined(HYPRE_BIGINT) *nfp = 'l'; nfp++; *nfp = 'l'; nfp++; #endif foundpercent = 0; break; case 'f': case 'e': case 'E': case 'g': case 'G': #if defined(HYPRE_SINGLE) /* no modifier */ #elif defined(HYPRE_LONG_DOUBLE) /* modify with 'L' */ *nfp = 'L'; nfp++; #else /* modify with 'l' (default is _double_) */ *nfp = 'l'; nfp++; #endif foundpercent = 0; break; case 'c': case 'n': case 'o': case 'p': case 's': case 'u': case 'x': case 'X': case '%': foundpercent = 0; break; } } *nfp = *fp; nfp++; } *nfp = *fp; *newformat_ptr = newformat; /* printf("\nNEWFORMAT: %s\n", *newformat_ptr);*/ return 0; } HYPRE_Int free_format( char *newformat ) { hypre_TFree(newformat); return 0; } /* printf functions */ HYPRE_Int hypre_printf( const char *format, ...) { va_list ap; char *newformat; HYPRE_Int ierr = 0; va_start(ap, format); new_format(format, &newformat); ierr = vprintf(newformat, ap); free_format(newformat); va_end(ap); return ierr; } HYPRE_Int hypre_fprintf( FILE *stream, const char *format, ...) { va_list ap; char *newformat; HYPRE_Int ierr = 0; va_start(ap, format); new_format(format, &newformat); ierr = vfprintf(stream, newformat, ap); free_format(newformat); va_end(ap); return ierr; } HYPRE_Int hypre_sprintf( char *s, const char *format, ...) { va_list ap; char *newformat; HYPRE_Int ierr = 0; va_start(ap, format); new_format(format, &newformat); ierr = vsprintf(s, newformat, ap); free_format(newformat); va_end(ap); return ierr; } /* scanf functions */ HYPRE_Int hypre_scanf( const char *format, ...) { va_list ap; char *newformat; HYPRE_Int ierr = 0; va_start(ap, format); new_format(format, &newformat); ierr = vscanf(newformat, ap); free_format(newformat); va_end(ap); return ierr; } HYPRE_Int hypre_fscanf( FILE *stream, const char *format, ...) { va_list ap; char *newformat; HYPRE_Int ierr = 0; va_start(ap, format); new_format(format, &newformat); ierr = vfscanf(stream, newformat, ap); free_format(newformat); va_end(ap); return ierr; } HYPRE_Int hypre_sscanf( char *s, const char *format, ...) { va_list ap; char *newformat; HYPRE_Int ierr = 0; va_start(ap, format); new_format(format, &newformat); ierr = vsscanf(s, newformat, ap); free_format(newformat); va_end(ap); return ierr; } // #else // // /* this is used only to eliminate compiler warnings */ // HYPRE_Int hypre_printf_empty; // // #endif
4,972
22.023148
81
c
AMG
AMG-master/utilities/hypre_qsort.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ #include <math.h> #include "_hypre_utilities.h" /*-------------------------------------------------------------------------- *--------------------------------------------------------------------------*/ void hypre_swap( HYPRE_Int *v, HYPRE_Int i, HYPRE_Int j ) { HYPRE_Int temp; temp = v[i]; v[i] = v[j]; v[j] = temp; } /*-------------------------------------------------------------------------- *--------------------------------------------------------------------------*/ void hypre_swap2(HYPRE_Int *v, HYPRE_Real *w, HYPRE_Int i, HYPRE_Int j ) { HYPRE_Int temp; HYPRE_Real temp2; temp = v[i]; v[i] = v[j]; v[j] = temp; temp2 = w[i]; w[i] = w[j]; w[j] = temp2; } /*-------------------------------------------------------------------------- *--------------------------------------------------------------------------*/ void hypre_swap2i(HYPRE_Int *v, HYPRE_Int *w, HYPRE_Int i, HYPRE_Int j ) { HYPRE_Int temp; temp = v[i]; v[i] = v[j]; v[j] = temp; temp = w[i]; w[i] = w[j]; w[j] = temp; } /*-------------------------------------------------------------------------- *--------------------------------------------------------------------------*/ /* AB 11/04 */ void hypre_swap3i(HYPRE_Int *v, HYPRE_Int *w, HYPRE_Int *z, HYPRE_Int i, HYPRE_Int j ) { HYPRE_Int temp; temp = v[i]; v[i] = v[j]; v[j] = temp; temp = w[i]; w[i] = w[j]; w[j] = temp; temp = z[i]; z[i] = z[j]; z[j] = temp; } /*-------------------------------------------------------------------------- *--------------------------------------------------------------------------*/ void hypre_swap3_d(HYPRE_Real *v, HYPRE_Int *w, HYPRE_Int *z, HYPRE_Int i, HYPRE_Int j ) { HYPRE_Int temp; HYPRE_Real temp_d; temp_d = v[i]; v[i] = v[j]; v[j] = temp_d; temp = w[i]; w[i] = w[j]; w[j] = temp; temp = z[i]; z[i] = z[j]; z[j] = temp; } /*-------------------------------------------------------------------------- *--------------------------------------------------------------------------*/ void hypre_swap4_d(HYPRE_Real *v, HYPRE_Int *w, HYPRE_Int *z, HYPRE_Int *y, HYPRE_Int i, HYPRE_Int j ) { HYPRE_Int temp; HYPRE_Real temp_d; temp_d = v[i]; v[i] = v[j]; v[j] = temp_d; temp = w[i]; w[i] = w[j]; w[j] = temp; temp = z[i]; z[i] = z[j]; z[j] = temp; temp = y[i]; y[i] = y[j]; y[j] = temp; } /*-------------------------------------------------------------------------- *--------------------------------------------------------------------------*/ void hypre_swap_d( HYPRE_Real *v, HYPRE_Int i, HYPRE_Int j ) { HYPRE_Real temp; temp = v[i]; v[i] = v[j]; v[j] = temp; } /*-------------------------------------------------------------------------- *--------------------------------------------------------------------------*/ void hypre_qsort0( HYPRE_Int *v, HYPRE_Int left, HYPRE_Int right ) { HYPRE_Int i, last; if (left >= right) return; hypre_swap( v, left, (left+right)/2); last = left; for (i = left+1; i <= right; i++) if (v[i] < v[left]) { hypre_swap(v, ++last, i); } hypre_swap(v, left, last); hypre_qsort0(v, left, last-1); hypre_qsort0(v, last+1, right); } /*-------------------------------------------------------------------------- *--------------------------------------------------------------------------*/ void hypre_qsort1( HYPRE_Int *v, HYPRE_Real *w, HYPRE_Int left, HYPRE_Int right ) { HYPRE_Int i, last; if (left >= right) return; hypre_swap2( v, w, left, (left+right)/2); last = left; for (i = left+1; i <= right; i++) if (v[i] < v[left]) { hypre_swap2(v, w, ++last, i); } hypre_swap2(v, w, left, last); hypre_qsort1(v, w, left, last-1); hypre_qsort1(v, w, last+1, right); } /*-------------------------------------------------------------------------- *--------------------------------------------------------------------------*/ void hypre_qsort2i( HYPRE_Int *v, HYPRE_Int *w, HYPRE_Int left, HYPRE_Int right ) { HYPRE_Int i, last; if (left >= right) { return; } hypre_swap2i( v, w, left, (left+right)/2); last = left; for (i = left+1; i <= right; i++) { if (v[i] < v[left]) { hypre_swap2i(v, w, ++last, i); } } hypre_swap2i(v, w, left, last); hypre_qsort2i(v, w, left, last-1); hypre_qsort2i(v, w, last+1, right); } /*-------------------------------------------------------------------------- *--------------------------------------------------------------------------*/ /* sort on w (HYPRE_Real), move v (AB 11/04) */ void hypre_qsort2( HYPRE_Int *v, HYPRE_Real *w, HYPRE_Int left, HYPRE_Int right ) { HYPRE_Int i, last; if (left >= right) return; hypre_swap2( v, w, left, (left+right)/2); last = left; for (i = left+1; i <= right; i++) if (w[i] < w[left]) { hypre_swap2(v, w, ++last, i); } hypre_swap2(v, w, left, last); hypre_qsort2(v, w, left, last-1); hypre_qsort2(v, w, last+1, right); } /*-------------------------------------------------------------------------- *--------------------------------------------------------------------------*/ /* sort on v, move w and z (AB 11/04) */ void hypre_qsort3i( HYPRE_Int *v, HYPRE_Int *w, HYPRE_Int *z, HYPRE_Int left, HYPRE_Int right ) { HYPRE_Int i, last; if (left >= right) { return; } hypre_swap3i( v, w, z, left, (left+right)/2); last = left; for (i = left+1; i <= right; i++) { if (v[i] < v[left]) { hypre_swap3i(v, w, z, ++last, i); } } hypre_swap3i(v, w, z, left, last); hypre_qsort3i(v, w, z, left, last-1); hypre_qsort3i(v, w, z, last+1, right); } /*-------------------------------------------------------------------------- *--------------------------------------------------------------------------*/ /* sort min to max based on absolute value */ void hypre_qsort3_abs(HYPRE_Real *v, HYPRE_Int *w, HYPRE_Int *z, HYPRE_Int left, HYPRE_Int right ) { HYPRE_Int i, last; if (left >= right) return; hypre_swap3_d( v, w, z, left, (left+right)/2); last = left; for (i = left+1; i <= right; i++) if (fabs(v[i]) < fabs(v[left])) { hypre_swap3_d(v,w, z, ++last, i); } hypre_swap3_d(v, w, z, left, last); hypre_qsort3_abs(v, w, z, left, last-1); hypre_qsort3_abs(v, w, z, last+1, right); } /*-------------------------------------------------------------------------- *--------------------------------------------------------------------------*/ /* sort min to max based on absolute value */ void hypre_qsort4_abs(HYPRE_Real *v, HYPRE_Int *w, HYPRE_Int *z, HYPRE_Int *y, HYPRE_Int left, HYPRE_Int right ) { HYPRE_Int i, last; if (left >= right) return; hypre_swap4_d( v, w, z, y, left, (left+right)/2); last = left; for (i = left+1; i <= right; i++) if (fabs(v[i]) < fabs(v[left])) { hypre_swap4_d(v,w, z, y, ++last, i); } hypre_swap4_d(v, w, z, y, left, last); hypre_qsort4_abs(v, w, z, y, left, last-1); hypre_qsort4_abs(v, w, z, y, last+1, right); } /*-------------------------------------------------------------------------- *--------------------------------------------------------------------------*/ /* sort min to max based on absolute value */ void hypre_qsort_abs(HYPRE_Real *w, HYPRE_Int left, HYPRE_Int right ) { HYPRE_Int i, last; if (left >= right) return; hypre_swap_d( w, left, (left+right)/2); last = left; for (i = left+1; i <= right; i++) if (fabs(w[i]) < fabs(w[left])) { hypre_swap_d(w, ++last, i); } hypre_swap_d(w, left, last); hypre_qsort_abs(w, left, last-1); hypre_qsort_abs(w, last+1, right); }
9,716
24.638522
81
c
AMG
AMG-master/utilities/hypre_smp.h
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ #ifndef HYPRE_SMP_HEADER #define HYPRE_SMP_HEADER #endif #define HYPRE_SMP_SCHEDULE schedule(static)
1,028
41.875
81
h
AMG
AMG-master/utilities/memory_dmalloc.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /****************************************************************************** * * Memory management utilities * * Routines to use "Debug Malloc Library", dmalloc * *****************************************************************************/ #ifdef HYPRE_MEMORY_DMALLOC #include "hypre_memory.h" #include <dmalloc.h> char dmalloc_logpath_memory[256]; /*-------------------------------------------------------------------------- * hypre_InitMemoryDebugDML *--------------------------------------------------------------------------*/ HYPRE_Int hypre_InitMemoryDebugDML( HYPRE_Int id ) { HYPRE_Int *iptr; /* do this to get the Debug Malloc Library started/initialized */ iptr = hypre_TAlloc(HYPRE_Int, 1); hypre_TFree(iptr); dmalloc_logpath = dmalloc_logpath_memory; hypre_sprintf(dmalloc_logpath, "dmalloc.log.%04d", id); return 0; } /*-------------------------------------------------------------------------- * hypre_FinalizeMemoryDebugDML *--------------------------------------------------------------------------*/ HYPRE_Int hypre_FinalizeMemoryDebugDML( ) { dmalloc_verify(NULL); return 0; } /*-------------------------------------------------------------------------- * hypre_MAllocDML *--------------------------------------------------------------------------*/ char * hypre_MAllocDML( HYPRE_Int size, char *file, HYPRE_Int line ) { char *ptr; if (size > 0) ptr = _malloc_leap(file, line, size); else ptr = NULL; return ptr; } /*-------------------------------------------------------------------------- * hypre_CAllocDML *--------------------------------------------------------------------------*/ char * hypre_CAllocDML( HYPRE_Int count, HYPRE_Int elt_size, char *file, HYPRE_Int line ) { char *ptr; HYPRE_Int size = count*elt_size; if (size > 0) { ptr = _calloc_leap(file, line, count, elt_size); } else { ptr = NULL; } return ptr; } /*-------------------------------------------------------------------------- * hypre_ReAllocDML *--------------------------------------------------------------------------*/ char * hypre_ReAllocDML( char *ptr, HYPRE_Int size, char *file, HYPRE_Int line ) { ptr = _realloc_leap(file, line, ptr, size); return ptr; } /*-------------------------------------------------------------------------- * hypre_FreeDML *--------------------------------------------------------------------------*/ void hypre_FreeDML( char *ptr, char *file, HYPRE_Int line ) { if (ptr) { _free_leap(file, line, ptr); } } #else /* this is used only to eliminate compiler warnings */ char hypre_memory_dmalloc_empty; #endif
3,817
25.150685
81
c
AMG
AMG-master/utilities/mpistubs.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ #include "_hypre_utilities.h" /****************************************************************************** * This routine is the same in both the sequential and normal cases * * The 'comm' argument for MPI_Comm_f2c is MPI_Fint, which is always the size of * a Fortran integer and hence usually the size of hypre_int. *****************************************************************************/ hypre_MPI_Comm hypre_MPI_Comm_f2c( hypre_int comm ) { #ifdef HYPRE_HAVE_MPI_COMM_F2C return (hypre_MPI_Comm) MPI_Comm_f2c(comm); #else return (hypre_MPI_Comm) (size_t)comm; #endif } /****************************************************************************** * MPI stubs to generate serial codes without mpi *****************************************************************************/ #ifdef HYPRE_SEQUENTIAL HYPRE_Int hypre_MPI_Init( hypre_int *argc, char ***argv ) { return(0); } HYPRE_Int hypre_MPI_Finalize( ) { return(0); } HYPRE_Int hypre_MPI_Abort( hypre_MPI_Comm comm, HYPRE_Int errorcode ) { return(0); } HYPRE_Real hypre_MPI_Wtime( ) { return(0.0); } HYPRE_Real hypre_MPI_Wtick( ) { return(0.0); } HYPRE_Int hypre_MPI_Barrier( hypre_MPI_Comm comm ) { return(0); } HYPRE_Int hypre_MPI_Comm_create( hypre_MPI_Comm comm, hypre_MPI_Group group, hypre_MPI_Comm *newcomm ) { return(0); } HYPRE_Int hypre_MPI_Comm_dup( hypre_MPI_Comm comm, hypre_MPI_Comm *newcomm ) { return(0); } HYPRE_Int hypre_MPI_Comm_size( hypre_MPI_Comm comm, HYPRE_Int *size ) { *size = 1; return(0); } HYPRE_Int hypre_MPI_Comm_rank( hypre_MPI_Comm comm, HYPRE_Int *rank ) { *rank = 0; return(0); } HYPRE_Int hypre_MPI_Comm_free( hypre_MPI_Comm *comm ) { return 0; } HYPRE_Int hypre_MPI_Comm_group( hypre_MPI_Comm comm, hypre_MPI_Group *group ) { return(0); } HYPRE_Int hypre_MPI_Comm_split( hypre_MPI_Comm comm, HYPRE_Int n, HYPRE_Int m, hypre_MPI_Comm *comms ) { return(0); } HYPRE_Int hypre_MPI_Group_incl( hypre_MPI_Group group, HYPRE_Int n, HYPRE_Int *ranks, hypre_MPI_Group *newgroup ) { return(0); } HYPRE_Int hypre_MPI_Group_free( hypre_MPI_Group *group ) { return 0; } HYPRE_Int hypre_MPI_Address( void *location, hypre_MPI_Aint *address ) { return(0); } HYPRE_Int hypre_MPI_Get_count( hypre_MPI_Status *status, hypre_MPI_Datatype datatype, HYPRE_Int *count ) { return(0); } HYPRE_Int hypre_MPI_Alltoall( void *sendbuf, HYPRE_Int sendcount, hypre_MPI_Datatype sendtype, void *recvbuf, HYPRE_Int recvcount, hypre_MPI_Datatype recvtype, hypre_MPI_Comm comm ) { return(0); } HYPRE_Int hypre_MPI_Allgather( void *sendbuf, HYPRE_Int sendcount, hypre_MPI_Datatype sendtype, void *recvbuf, HYPRE_Int recvcount, hypre_MPI_Datatype recvtype, hypre_MPI_Comm comm ) { HYPRE_Int i; switch (sendtype) { case hypre_MPI_INT: { HYPRE_Int *crecvbuf = (HYPRE_Int *)recvbuf; HYPRE_Int *csendbuf = (HYPRE_Int *)sendbuf; for (i = 0; i < sendcount; i++) { crecvbuf[i] = csendbuf[i]; } } break; case hypre_MPI_DOUBLE: { double *crecvbuf = (double *)recvbuf; double *csendbuf = (double *)sendbuf; for (i = 0; i < sendcount; i++) { crecvbuf[i] = csendbuf[i]; } } break; case hypre_MPI_CHAR: { char *crecvbuf = (char *)recvbuf; char *csendbuf = (char *)sendbuf; for (i = 0; i < sendcount; i++) { crecvbuf[i] = csendbuf[i]; } } break; case hypre_MPI_BYTE: { memcpy(recvbuf, sendbuf, sendcount); } break; case hypre_MPI_REAL: { HYPRE_Real *crecvbuf = (HYPRE_Real *)recvbuf; HYPRE_Real *csendbuf = (HYPRE_Real *)sendbuf; for (i = 0; i < sendcount; i++) { crecvbuf[i] = csendbuf[i]; } } break; case hypre_MPI_COMPLEX: { HYPRE_Complex *crecvbuf = (HYPRE_Complex *)recvbuf; HYPRE_Complex *csendbuf = (HYPRE_Complex *)sendbuf; for (i = 0; i < sendcount; i++) { crecvbuf[i] = csendbuf[i]; } } break; } return(0); } HYPRE_Int hypre_MPI_Allgatherv( void *sendbuf, HYPRE_Int sendcount, hypre_MPI_Datatype sendtype, void *recvbuf, HYPRE_Int *recvcounts, HYPRE_Int *displs, hypre_MPI_Datatype recvtype, hypre_MPI_Comm comm ) { return ( hypre_MPI_Allgather(sendbuf, sendcount, sendtype, recvbuf, *recvcounts, recvtype, comm) ); } HYPRE_Int hypre_MPI_Gather( void *sendbuf, HYPRE_Int sendcount, hypre_MPI_Datatype sendtype, void *recvbuf, HYPRE_Int recvcount, hypre_MPI_Datatype recvtype, HYPRE_Int root, hypre_MPI_Comm comm ) { return ( hypre_MPI_Allgather(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype, comm) ); } HYPRE_Int hypre_MPI_Gatherv( void *sendbuf, HYPRE_Int sendcount, hypre_MPI_Datatype sendtype, void *recvbuf, HYPRE_Int *recvcounts, HYPRE_Int *displs, hypre_MPI_Datatype recvtype, HYPRE_Int root, hypre_MPI_Comm comm ) { return ( hypre_MPI_Allgather(sendbuf, sendcount, sendtype, recvbuf, *recvcounts, recvtype, comm) ); } HYPRE_Int hypre_MPI_Scatter( void *sendbuf, HYPRE_Int sendcount, hypre_MPI_Datatype sendtype, void *recvbuf, HYPRE_Int recvcount, hypre_MPI_Datatype recvtype, HYPRE_Int root, hypre_MPI_Comm comm ) { return ( hypre_MPI_Allgather(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype, comm) ); } HYPRE_Int hypre_MPI_Scatterv( void *sendbuf, HYPRE_Int *sendcounts, HYPRE_Int *displs, hypre_MPI_Datatype sendtype, void *recvbuf, HYPRE_Int recvcount, hypre_MPI_Datatype recvtype, HYPRE_Int root, hypre_MPI_Comm comm ) { return ( hypre_MPI_Allgather(sendbuf, *sendcounts, sendtype, recvbuf, recvcount, recvtype, comm) ); } HYPRE_Int hypre_MPI_Bcast( void *buffer, HYPRE_Int count, hypre_MPI_Datatype datatype, HYPRE_Int root, hypre_MPI_Comm comm ) { return(0); } HYPRE_Int hypre_MPI_Send( void *buf, HYPRE_Int count, hypre_MPI_Datatype datatype, HYPRE_Int dest, HYPRE_Int tag, hypre_MPI_Comm comm ) { return(0); } HYPRE_Int hypre_MPI_Recv( void *buf, HYPRE_Int count, hypre_MPI_Datatype datatype, HYPRE_Int source, HYPRE_Int tag, hypre_MPI_Comm comm, hypre_MPI_Status *status ) { return(0); } HYPRE_Int hypre_MPI_Isend( void *buf, HYPRE_Int count, hypre_MPI_Datatype datatype, HYPRE_Int dest, HYPRE_Int tag, hypre_MPI_Comm comm, hypre_MPI_Request *request ) { return(0); } HYPRE_Int hypre_MPI_Irecv( void *buf, HYPRE_Int count, hypre_MPI_Datatype datatype, HYPRE_Int source, HYPRE_Int tag, hypre_MPI_Comm comm, hypre_MPI_Request *request ) { return(0); } HYPRE_Int hypre_MPI_Send_init( void *buf, HYPRE_Int count, hypre_MPI_Datatype datatype, HYPRE_Int dest, HYPRE_Int tag, hypre_MPI_Comm comm, hypre_MPI_Request *request ) { return 0; } HYPRE_Int hypre_MPI_Recv_init( void *buf, HYPRE_Int count, hypre_MPI_Datatype datatype, HYPRE_Int dest, HYPRE_Int tag, hypre_MPI_Comm comm, hypre_MPI_Request *request ) { return 0; } HYPRE_Int hypre_MPI_Irsend( void *buf, HYPRE_Int count, hypre_MPI_Datatype datatype, HYPRE_Int dest, HYPRE_Int tag, hypre_MPI_Comm comm, hypre_MPI_Request *request ) { return 0; } HYPRE_Int hypre_MPI_Startall( HYPRE_Int count, hypre_MPI_Request *array_of_requests ) { return 0; } HYPRE_Int hypre_MPI_Probe( HYPRE_Int source, HYPRE_Int tag, hypre_MPI_Comm comm, hypre_MPI_Status *status ) { return 0; } HYPRE_Int hypre_MPI_Iprobe( HYPRE_Int source, HYPRE_Int tag, hypre_MPI_Comm comm, HYPRE_Int *flag, hypre_MPI_Status *status ) { return 0; } HYPRE_Int hypre_MPI_Test( hypre_MPI_Request *request, HYPRE_Int *flag, hypre_MPI_Status *status ) { *flag = 1; return(0); } HYPRE_Int hypre_MPI_Testall( HYPRE_Int count, hypre_MPI_Request *array_of_requests, HYPRE_Int *flag, hypre_MPI_Status *array_of_statuses ) { *flag = 1; return(0); } HYPRE_Int hypre_MPI_Wait( hypre_MPI_Request *request, hypre_MPI_Status *status ) { return(0); } HYPRE_Int hypre_MPI_Waitall( HYPRE_Int count, hypre_MPI_Request *array_of_requests, hypre_MPI_Status *array_of_statuses ) { return(0); } HYPRE_Int hypre_MPI_Waitany( HYPRE_Int count, hypre_MPI_Request *array_of_requests, HYPRE_Int *index, hypre_MPI_Status *status ) { return(0); } HYPRE_Int hypre_MPI_Allreduce( void *sendbuf, void *recvbuf, HYPRE_Int count, hypre_MPI_Datatype datatype, hypre_MPI_Op op, hypre_MPI_Comm comm ) { HYPRE_Int i; switch (datatype) { case hypre_MPI_INT: { HYPRE_Int *crecvbuf = (HYPRE_Int *)recvbuf; HYPRE_Int *csendbuf = (HYPRE_Int *)sendbuf; for (i = 0; i < count; i++) { crecvbuf[i] = csendbuf[i]; } } break; case hypre_MPI_DOUBLE: { double *crecvbuf = (double *)recvbuf; double *csendbuf = (double *)sendbuf; for (i = 0; i < count; i++) { crecvbuf[i] = csendbuf[i]; } } break; case hypre_MPI_CHAR: { char *crecvbuf = (char *)recvbuf; char *csendbuf = (char *)sendbuf; for (i = 0; i < count; i++) { crecvbuf[i] = csendbuf[i]; } } break; case hypre_MPI_BYTE: { memcpy(recvbuf, sendbuf, count); } break; case hypre_MPI_REAL: { HYPRE_Real *crecvbuf = (HYPRE_Real *)recvbuf; HYPRE_Real *csendbuf = (HYPRE_Real *)sendbuf; for (i = 0; i < count; i++) { crecvbuf[i] = csendbuf[i]; } } break; case hypre_MPI_COMPLEX: { HYPRE_Complex *crecvbuf = (HYPRE_Complex *)recvbuf; HYPRE_Complex *csendbuf = (HYPRE_Complex *)sendbuf; for (i = 0; i < count; i++) { crecvbuf[i] = csendbuf[i]; } } break; } return 0; } HYPRE_Int hypre_MPI_Reduce( void *sendbuf, void *recvbuf, HYPRE_Int count, hypre_MPI_Datatype datatype, hypre_MPI_Op op, HYPRE_Int root, hypre_MPI_Comm comm ) { hypre_MPI_Allreduce(sendbuf, recvbuf, count, datatype, op, comm); return 0; } HYPRE_Int hypre_MPI_Scan( void *sendbuf, void *recvbuf, HYPRE_Int count, hypre_MPI_Datatype datatype, hypre_MPI_Op op, hypre_MPI_Comm comm ) { hypre_MPI_Allreduce(sendbuf, recvbuf, count, datatype, op, comm); return 0; } HYPRE_Int hypre_MPI_Request_free( hypre_MPI_Request *request ) { return 0; } HYPRE_Int hypre_MPI_Type_contiguous( HYPRE_Int count, hypre_MPI_Datatype oldtype, hypre_MPI_Datatype *newtype ) { return(0); } HYPRE_Int hypre_MPI_Type_vector( HYPRE_Int count, HYPRE_Int blocklength, HYPRE_Int stride, hypre_MPI_Datatype oldtype, hypre_MPI_Datatype *newtype ) { return(0); } HYPRE_Int hypre_MPI_Type_hvector( HYPRE_Int count, HYPRE_Int blocklength, hypre_MPI_Aint stride, hypre_MPI_Datatype oldtype, hypre_MPI_Datatype *newtype ) { return(0); } HYPRE_Int hypre_MPI_Type_struct( HYPRE_Int count, HYPRE_Int *array_of_blocklengths, hypre_MPI_Aint *array_of_displacements, hypre_MPI_Datatype *array_of_types, hypre_MPI_Datatype *newtype ) { return(0); } HYPRE_Int hypre_MPI_Type_commit( hypre_MPI_Datatype *datatype ) { return(0); } HYPRE_Int hypre_MPI_Type_free( hypre_MPI_Datatype *datatype ) { return(0); } HYPRE_Int hypre_MPI_Op_create( hypre_MPI_User_function *function, hypre_int commute, hypre_MPI_Op *op ) { return(0); } HYPRE_Int hypre_MPI_Op_free( hypre_MPI_Op *op ) { return(0); } /****************************************************************************** * MPI stubs to do casting of HYPRE_Int and hypre_int correctly *****************************************************************************/ #else HYPRE_Int hypre_MPI_Init( hypre_int *argc, char ***argv ) { return (HYPRE_Int) MPI_Init(argc, argv); } HYPRE_Int hypre_MPI_Finalize( ) { return (HYPRE_Int) MPI_Finalize(); } HYPRE_Int hypre_MPI_Abort( hypre_MPI_Comm comm, HYPRE_Int errorcode ) { return (HYPRE_Int) MPI_Abort(comm, (hypre_int)errorcode); } HYPRE_Real hypre_MPI_Wtime( ) { return MPI_Wtime(); } HYPRE_Real hypre_MPI_Wtick( ) { return MPI_Wtick(); } HYPRE_Int hypre_MPI_Barrier( hypre_MPI_Comm comm ) { return (HYPRE_Int) MPI_Barrier(comm); } HYPRE_Int hypre_MPI_Comm_create( hypre_MPI_Comm comm, hypre_MPI_Group group, hypre_MPI_Comm *newcomm ) { return (HYPRE_Int) MPI_Comm_create(comm, group, newcomm); } HYPRE_Int hypre_MPI_Comm_dup( hypre_MPI_Comm comm, hypre_MPI_Comm *newcomm ) { return (HYPRE_Int) MPI_Comm_dup(comm, newcomm); } HYPRE_Int hypre_MPI_Comm_size( hypre_MPI_Comm comm, HYPRE_Int *size ) { hypre_int mpi_size; HYPRE_Int ierr; ierr = (HYPRE_Int) MPI_Comm_size(comm, &mpi_size); *size = (HYPRE_Int) mpi_size; return ierr; } HYPRE_Int hypre_MPI_Comm_rank( hypre_MPI_Comm comm, HYPRE_Int *rank ) { hypre_int mpi_rank; HYPRE_Int ierr; ierr = (HYPRE_Int) MPI_Comm_rank(comm, &mpi_rank); *rank = (HYPRE_Int) mpi_rank; return ierr; } HYPRE_Int hypre_MPI_Comm_free( hypre_MPI_Comm *comm ) { return (HYPRE_Int) MPI_Comm_free(comm); } HYPRE_Int hypre_MPI_Comm_group( hypre_MPI_Comm comm, hypre_MPI_Group *group ) { return (HYPRE_Int) MPI_Comm_group(comm, group); } HYPRE_Int hypre_MPI_Comm_split( hypre_MPI_Comm comm, HYPRE_Int n, HYPRE_Int m, hypre_MPI_Comm *comms ) { return (HYPRE_Int) MPI_Comm_split(comm, (hypre_int)n, (hypre_int)m, comms); } HYPRE_Int hypre_MPI_Group_incl( hypre_MPI_Group group, HYPRE_Int n, HYPRE_Int *ranks, hypre_MPI_Group *newgroup ) { hypre_int *mpi_ranks; HYPRE_Int i; HYPRE_Int ierr; mpi_ranks = hypre_TAlloc(hypre_int, n); for (i = 0; i < n; i++) { mpi_ranks[i] = (hypre_int) ranks[i]; } ierr = (HYPRE_Int) MPI_Group_incl(group, (hypre_int)n, mpi_ranks, newgroup); hypre_TFree(mpi_ranks); return ierr; } HYPRE_Int hypre_MPI_Group_free( hypre_MPI_Group *group ) { return (HYPRE_Int) MPI_Group_free(group); } HYPRE_Int hypre_MPI_Address( void *location, hypre_MPI_Aint *address ) { #if MPI_VERSION > 1 return (HYPRE_Int) MPI_Get_address(location, address); #else return (HYPRE_Int) MPI_Address(location, address); #endif } HYPRE_Int hypre_MPI_Get_count( hypre_MPI_Status *status, hypre_MPI_Datatype datatype, HYPRE_Int *count ) { hypre_int mpi_count; HYPRE_Int ierr; ierr = (HYPRE_Int) MPI_Get_count(status, datatype, &mpi_count); *count = (HYPRE_Int) mpi_count; return ierr; } HYPRE_Int hypre_MPI_Alltoall( void *sendbuf, HYPRE_Int sendcount, hypre_MPI_Datatype sendtype, void *recvbuf, HYPRE_Int recvcount, hypre_MPI_Datatype recvtype, hypre_MPI_Comm comm ) { return (HYPRE_Int) MPI_Alltoall(sendbuf, (hypre_int)sendcount, sendtype, recvbuf, (hypre_int)recvcount, recvtype, comm); } HYPRE_Int hypre_MPI_Allgather( void *sendbuf, HYPRE_Int sendcount, hypre_MPI_Datatype sendtype, void *recvbuf, HYPRE_Int recvcount, hypre_MPI_Datatype recvtype, hypre_MPI_Comm comm ) { return (HYPRE_Int) MPI_Allgather(sendbuf, (hypre_int)sendcount, sendtype, recvbuf, (hypre_int)recvcount, recvtype, comm); } HYPRE_Int hypre_MPI_Allgatherv( void *sendbuf, HYPRE_Int sendcount, hypre_MPI_Datatype sendtype, void *recvbuf, HYPRE_Int *recvcounts, HYPRE_Int *displs, hypre_MPI_Datatype recvtype, hypre_MPI_Comm comm ) { hypre_int *mpi_recvcounts, *mpi_displs, csize; HYPRE_Int i; HYPRE_Int ierr; MPI_Comm_size(comm, &csize); mpi_recvcounts = hypre_TAlloc(hypre_int, csize); mpi_displs = hypre_TAlloc(hypre_int, csize); for (i = 0; i < csize; i++) { mpi_recvcounts[i] = (hypre_int) recvcounts[i]; mpi_displs[i] = (hypre_int) displs[i]; } ierr = (HYPRE_Int) MPI_Allgatherv(sendbuf, (hypre_int)sendcount, sendtype, recvbuf, mpi_recvcounts, mpi_displs, recvtype, comm); hypre_TFree(mpi_recvcounts); hypre_TFree(mpi_displs); return ierr; } HYPRE_Int hypre_MPI_Gather( void *sendbuf, HYPRE_Int sendcount, hypre_MPI_Datatype sendtype, void *recvbuf, HYPRE_Int recvcount, hypre_MPI_Datatype recvtype, HYPRE_Int root, hypre_MPI_Comm comm ) { return (HYPRE_Int) MPI_Gather(sendbuf, (hypre_int) sendcount, sendtype, recvbuf, (hypre_int) recvcount, recvtype, (hypre_int)root, comm); } HYPRE_Int hypre_MPI_Gatherv(void *sendbuf, HYPRE_Int sendcount, hypre_MPI_Datatype sendtype, void *recvbuf, HYPRE_Int *recvcounts, HYPRE_Int *displs, hypre_MPI_Datatype recvtype, HYPRE_Int root, hypre_MPI_Comm comm ) { hypre_int *mpi_recvcounts = NULL; hypre_int *mpi_displs = NULL; hypre_int csize, croot; HYPRE_Int i; HYPRE_Int ierr; MPI_Comm_size(comm, &csize); MPI_Comm_rank(comm, &croot); if (croot == (hypre_int) root) { mpi_recvcounts = hypre_TAlloc(hypre_int, csize); mpi_displs = hypre_TAlloc(hypre_int, csize); for (i = 0; i < csize; i++) { mpi_recvcounts[i] = (hypre_int) recvcounts[i]; mpi_displs[i] = (hypre_int) displs[i]; } } ierr = (HYPRE_Int) MPI_Gatherv(sendbuf, (hypre_int)sendcount, sendtype, recvbuf, mpi_recvcounts, mpi_displs, recvtype, (hypre_int) root, comm); hypre_TFree(mpi_recvcounts); hypre_TFree(mpi_displs); return ierr; } HYPRE_Int hypre_MPI_Scatter( void *sendbuf, HYPRE_Int sendcount, hypre_MPI_Datatype sendtype, void *recvbuf, HYPRE_Int recvcount, hypre_MPI_Datatype recvtype, HYPRE_Int root, hypre_MPI_Comm comm ) { return (HYPRE_Int) MPI_Scatter(sendbuf, (hypre_int)sendcount, sendtype, recvbuf, (hypre_int)recvcount, recvtype, (hypre_int)root, comm); } HYPRE_Int hypre_MPI_Scatterv(void *sendbuf, HYPRE_Int *sendcounts, HYPRE_Int *displs, hypre_MPI_Datatype sendtype, void *recvbuf, HYPRE_Int recvcount, hypre_MPI_Datatype recvtype, HYPRE_Int root, hypre_MPI_Comm comm ) { hypre_int *mpi_sendcounts = NULL; hypre_int *mpi_displs = NULL; hypre_int csize, croot; HYPRE_Int i; HYPRE_Int ierr; MPI_Comm_size(comm, &csize); MPI_Comm_rank(comm, &croot); if (croot == (hypre_int) root) { mpi_sendcounts = hypre_TAlloc(hypre_int, csize); mpi_displs = hypre_TAlloc(hypre_int, csize); for (i = 0; i < csize; i++) { mpi_sendcounts[i] = (hypre_int) sendcounts[i]; mpi_displs[i] = (hypre_int) displs[i]; } } ierr = (HYPRE_Int) MPI_Scatterv(sendbuf, mpi_sendcounts, mpi_displs, sendtype, recvbuf, (hypre_int) recvcount, recvtype, (hypre_int) root, comm); hypre_TFree(mpi_sendcounts); hypre_TFree(mpi_displs); return ierr; } HYPRE_Int hypre_MPI_Bcast( void *buffer, HYPRE_Int count, hypre_MPI_Datatype datatype, HYPRE_Int root, hypre_MPI_Comm comm ) { return (HYPRE_Int) MPI_Bcast(buffer, (hypre_int)count, datatype, (hypre_int)root, comm); } HYPRE_Int hypre_MPI_Send( void *buf, HYPRE_Int count, hypre_MPI_Datatype datatype, HYPRE_Int dest, HYPRE_Int tag, hypre_MPI_Comm comm ) { return (HYPRE_Int) MPI_Send(buf, (hypre_int)count, datatype, (hypre_int)dest, (hypre_int)tag, comm); } HYPRE_Int hypre_MPI_Recv( void *buf, HYPRE_Int count, hypre_MPI_Datatype datatype, HYPRE_Int source, HYPRE_Int tag, hypre_MPI_Comm comm, hypre_MPI_Status *status ) { return (HYPRE_Int) MPI_Recv(buf, (hypre_int)count, datatype, (hypre_int)source, (hypre_int)tag, comm, status); } HYPRE_Int hypre_MPI_Isend( void *buf, HYPRE_Int count, hypre_MPI_Datatype datatype, HYPRE_Int dest, HYPRE_Int tag, hypre_MPI_Comm comm, hypre_MPI_Request *request ) { return (HYPRE_Int) MPI_Isend(buf, (hypre_int)count, datatype, (hypre_int)dest, (hypre_int)tag, comm, request); } HYPRE_Int hypre_MPI_Irecv( void *buf, HYPRE_Int count, hypre_MPI_Datatype datatype, HYPRE_Int source, HYPRE_Int tag, hypre_MPI_Comm comm, hypre_MPI_Request *request ) { return (HYPRE_Int) MPI_Irecv(buf, (hypre_int)count, datatype, (hypre_int)source, (hypre_int)tag, comm, request); } HYPRE_Int hypre_MPI_Send_init( void *buf, HYPRE_Int count, hypre_MPI_Datatype datatype, HYPRE_Int dest, HYPRE_Int tag, hypre_MPI_Comm comm, hypre_MPI_Request *request ) { return (HYPRE_Int) MPI_Send_init(buf, (hypre_int)count, datatype, (hypre_int)dest, (hypre_int)tag, comm, request); } HYPRE_Int hypre_MPI_Recv_init( void *buf, HYPRE_Int count, hypre_MPI_Datatype datatype, HYPRE_Int dest, HYPRE_Int tag, hypre_MPI_Comm comm, hypre_MPI_Request *request ) { return (HYPRE_Int) MPI_Recv_init(buf, (hypre_int)count, datatype, (hypre_int)dest, (hypre_int)tag, comm, request); } HYPRE_Int hypre_MPI_Irsend( void *buf, HYPRE_Int count, hypre_MPI_Datatype datatype, HYPRE_Int dest, HYPRE_Int tag, hypre_MPI_Comm comm, hypre_MPI_Request *request ) { return (HYPRE_Int) MPI_Irsend(buf, (hypre_int)count, datatype, (hypre_int)dest, (hypre_int)tag, comm, request); } HYPRE_Int hypre_MPI_Startall( HYPRE_Int count, hypre_MPI_Request *array_of_requests ) { return (HYPRE_Int) MPI_Startall((hypre_int)count, array_of_requests); } HYPRE_Int hypre_MPI_Probe( HYPRE_Int source, HYPRE_Int tag, hypre_MPI_Comm comm, hypre_MPI_Status *status ) { return (HYPRE_Int) MPI_Probe((hypre_int)source, (hypre_int)tag, comm, status); } HYPRE_Int hypre_MPI_Iprobe( HYPRE_Int source, HYPRE_Int tag, hypre_MPI_Comm comm, HYPRE_Int *flag, hypre_MPI_Status *status ) { hypre_int mpi_flag; HYPRE_Int ierr; ierr = (HYPRE_Int) MPI_Iprobe((hypre_int)source, (hypre_int)tag, comm, &mpi_flag, status); *flag = (HYPRE_Int) mpi_flag; return ierr; } HYPRE_Int hypre_MPI_Test( hypre_MPI_Request *request, HYPRE_Int *flag, hypre_MPI_Status *status ) { hypre_int mpi_flag; HYPRE_Int ierr; ierr = (HYPRE_Int) MPI_Test(request, &mpi_flag, status); *flag = (HYPRE_Int) mpi_flag; return ierr; } HYPRE_Int hypre_MPI_Testall( HYPRE_Int count, hypre_MPI_Request *array_of_requests, HYPRE_Int *flag, hypre_MPI_Status *array_of_statuses ) { hypre_int mpi_flag; HYPRE_Int ierr; ierr = (HYPRE_Int) MPI_Testall((hypre_int)count, array_of_requests, &mpi_flag, array_of_statuses); *flag = (HYPRE_Int) mpi_flag; return ierr; } HYPRE_Int hypre_MPI_Wait( hypre_MPI_Request *request, hypre_MPI_Status *status ) { return (HYPRE_Int) MPI_Wait(request, status); } HYPRE_Int hypre_MPI_Waitall( HYPRE_Int count, hypre_MPI_Request *array_of_requests, hypre_MPI_Status *array_of_statuses ) { return (HYPRE_Int) MPI_Waitall((hypre_int)count, array_of_requests, array_of_statuses); } HYPRE_Int hypre_MPI_Waitany( HYPRE_Int count, hypre_MPI_Request *array_of_requests, HYPRE_Int *index, hypre_MPI_Status *status ) { hypre_int mpi_index; HYPRE_Int ierr; ierr = (HYPRE_Int) MPI_Waitany((hypre_int)count, array_of_requests, &mpi_index, status); *index = (HYPRE_Int) mpi_index; return ierr; } HYPRE_Int hypre_MPI_Allreduce( void *sendbuf, void *recvbuf, HYPRE_Int count, hypre_MPI_Datatype datatype, hypre_MPI_Op op, hypre_MPI_Comm comm ) { return (HYPRE_Int) MPI_Allreduce(sendbuf, recvbuf, (hypre_int)count, datatype, op, comm); } HYPRE_Int hypre_MPI_Reduce( void *sendbuf, void *recvbuf, HYPRE_Int count, hypre_MPI_Datatype datatype, hypre_MPI_Op op, HYPRE_Int root, hypre_MPI_Comm comm ) { return (HYPRE_Int) MPI_Reduce(sendbuf, recvbuf, (hypre_int)count, datatype, op, (hypre_int)root, comm); } HYPRE_Int hypre_MPI_Scan( void *sendbuf, void *recvbuf, HYPRE_Int count, hypre_MPI_Datatype datatype, hypre_MPI_Op op, hypre_MPI_Comm comm ) { return (HYPRE_Int) MPI_Scan(sendbuf, recvbuf, (hypre_int)count, datatype, op, comm); } HYPRE_Int hypre_MPI_Request_free( hypre_MPI_Request *request ) { return (HYPRE_Int) MPI_Request_free(request); } HYPRE_Int hypre_MPI_Type_contiguous( HYPRE_Int count, hypre_MPI_Datatype oldtype, hypre_MPI_Datatype *newtype ) { return (HYPRE_Int) MPI_Type_contiguous((hypre_int)count, oldtype, newtype); } HYPRE_Int hypre_MPI_Type_vector( HYPRE_Int count, HYPRE_Int blocklength, HYPRE_Int stride, hypre_MPI_Datatype oldtype, hypre_MPI_Datatype *newtype ) { return (HYPRE_Int) MPI_Type_vector((hypre_int)count, (hypre_int)blocklength, (hypre_int)stride, oldtype, newtype); } HYPRE_Int hypre_MPI_Type_hvector( HYPRE_Int count, HYPRE_Int blocklength, hypre_MPI_Aint stride, hypre_MPI_Datatype oldtype, hypre_MPI_Datatype *newtype ) { #if MPI_VERSION > 1 return (HYPRE_Int) MPI_Type_create_hvector((hypre_int)count, (hypre_int)blocklength, stride, oldtype, newtype); #else return (HYPRE_Int) MPI_Type_hvector((hypre_int)count, (hypre_int)blocklength, stride, oldtype, newtype); #endif } HYPRE_Int hypre_MPI_Type_struct( HYPRE_Int count, HYPRE_Int *array_of_blocklengths, hypre_MPI_Aint *array_of_displacements, hypre_MPI_Datatype *array_of_types, hypre_MPI_Datatype *newtype ) { hypre_int *mpi_array_of_blocklengths; HYPRE_Int i; HYPRE_Int ierr; mpi_array_of_blocklengths = hypre_TAlloc(hypre_int, count); for (i = 0; i < count; i++) { mpi_array_of_blocklengths[i] = (hypre_int) array_of_blocklengths[i]; } #if MPI_VERSION > 1 ierr = (HYPRE_Int) MPI_Type_create_struct((hypre_int)count, mpi_array_of_blocklengths, array_of_displacements, array_of_types, newtype); #else ierr = (HYPRE_Int) MPI_Type_struct((hypre_int)count, mpi_array_of_blocklengths, array_of_displacements, array_of_types, newtype); #endif hypre_TFree(mpi_array_of_blocklengths); return ierr; } HYPRE_Int hypre_MPI_Type_commit( hypre_MPI_Datatype *datatype ) { return (HYPRE_Int) MPI_Type_commit(datatype); } HYPRE_Int hypre_MPI_Type_free( hypre_MPI_Datatype *datatype ) { return (HYPRE_Int) MPI_Type_free(datatype); } HYPRE_Int hypre_MPI_Op_free( hypre_MPI_Op *op ) { return (HYPRE_Int) MPI_Op_free(op); } HYPRE_Int hypre_MPI_Op_create( hypre_MPI_User_function *function, hypre_int commute, hypre_MPI_Op *op ) { return (HYPRE_Int) MPI_Op_create(function, commute, op); } #endif
36,794
27.325635
93
c
AMG
AMG-master/utilities/mpistubs.h
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /****************************************************************************** * * Fake mpi stubs to generate serial codes without mpi * *****************************************************************************/ #ifndef hypre_MPISTUBS #define hypre_MPISTUBS #ifdef __cplusplus extern "C" { #endif #ifdef HYPRE_SEQUENTIAL /****************************************************************************** * MPI stubs to generate serial codes without mpi *****************************************************************************/ /*-------------------------------------------------------------------------- * Change all MPI names to hypre_MPI names to avoid link conflicts. * * NOTE: MPI_Comm is the only MPI symbol in the HYPRE user interface, * and is defined in `HYPRE_utilities.h'. *--------------------------------------------------------------------------*/ #define MPI_Comm hypre_MPI_Comm #define MPI_Group hypre_MPI_Group #define MPI_Request hypre_MPI_Request #define MPI_Datatype hypre_MPI_Datatype #define MPI_Status hypre_MPI_Status #define MPI_Op hypre_MPI_Op #define MPI_Aint hypre_MPI_Aint #define MPI_COMM_WORLD hypre_MPI_COMM_WORLD #define MPI_COMM_NULL hypre_MPI_COMM_NULL #define MPI_COMM_SELF hypre_MPI_COMM_SELF #define MPI_BOTTOM hypre_MPI_BOTTOM #define MPI_FLOAT hypre_MPI_FLOAT #define MPI_DOUBLE hypre_MPI_DOUBLE #define MPI_LONG_DOUBLE hypre_MPI_LONG_DOUBLE #define MPI_INT hypre_MPI_INT #define MPI_LONG_LONG_INT hypre_MPI_INT #define MPI_CHAR hypre_MPI_CHAR #define MPI_LONG hypre_MPI_LONG #define MPI_BYTE hypre_MPI_BYTE #define MPI_C_DOUBLE_COMPLEX hypre_MPI_COMPLEX #define MPI_SUM hypre_MPI_SUM #define MPI_MIN hypre_MPI_MIN #define MPI_MAX hypre_MPI_MAX #define MPI_LOR hypre_MPI_LOR #define MPI_SUCCESS hypre_MPI_SUCCESS #define MPI_STATUSES_IGNORE hypre_MPI_STATUSES_IGNORE #define MPI_UNDEFINED hypre_MPI_UNDEFINED #define MPI_REQUEST_NULL hypre_MPI_REQUEST_NULL #define MPI_ANY_SOURCE hypre_MPI_ANY_SOURCE #define MPI_ANY_TAG hypre_MPI_ANY_TAG #define MPI_SOURCE hypre_MPI_SOURCE #define MPI_TAG hypre_MPI_TAG #define MPI_Init hypre_MPI_Init #define MPI_Finalize hypre_MPI_Finalize #define MPI_Abort hypre_MPI_Abort #define MPI_Wtime hypre_MPI_Wtime #define MPI_Wtick hypre_MPI_Wtick #define MPI_Barrier hypre_MPI_Barrier #define MPI_Comm_create hypre_MPI_Comm_create #define MPI_Comm_dup hypre_MPI_Comm_dup #define MPI_Comm_f2c hypre_MPI_Comm_f2c #define MPI_Comm_group hypre_MPI_Comm_group #define MPI_Comm_size hypre_MPI_Comm_size #define MPI_Comm_rank hypre_MPI_Comm_rank #define MPI_Comm_free hypre_MPI_Comm_free #define MPI_Comm_split hypre_MPI_Comm_split #define MPI_Group_incl hypre_MPI_Group_incl #define MPI_Group_free hypre_MPI_Group_free #define MPI_Address hypre_MPI_Address #define MPI_Get_count hypre_MPI_Get_count #define MPI_Alltoall hypre_MPI_Alltoall #define MPI_Allgather hypre_MPI_Allgather #define MPI_Allgatherv hypre_MPI_Allgatherv #define MPI_Gather hypre_MPI_Gather #define MPI_Gatherv hypre_MPI_Gatherv #define MPI_Scatter hypre_MPI_Scatter #define MPI_Scatterv hypre_MPI_Scatterv #define MPI_Bcast hypre_MPI_Bcast #define MPI_Send hypre_MPI_Send #define MPI_Recv hypre_MPI_Recv #define MPI_Isend hypre_MPI_Isend #define MPI_Irecv hypre_MPI_Irecv #define MPI_Send_init hypre_MPI_Send_init #define MPI_Recv_init hypre_MPI_Recv_init #define MPI_Irsend hypre_MPI_Irsend #define MPI_Startall hypre_MPI_Startall #define MPI_Probe hypre_MPI_Probe #define MPI_Iprobe hypre_MPI_Iprobe #define MPI_Test hypre_MPI_Test #define MPI_Testall hypre_MPI_Testall #define MPI_Wait hypre_MPI_Wait #define MPI_Waitall hypre_MPI_Waitall #define MPI_Waitany hypre_MPI_Waitany #define MPI_Allreduce hypre_MPI_Allreduce #define MPI_Reduce hypre_MPI_Reduce #define MPI_Scan hypre_MPI_Scan #define MPI_Request_free hypre_MPI_Request_free #define MPI_Type_contiguous hypre_MPI_Type_contiguous #define MPI_Type_vector hypre_MPI_Type_vector #define MPI_Type_hvector hypre_MPI_Type_hvector #define MPI_Type_struct hypre_MPI_Type_struct #define MPI_Type_commit hypre_MPI_Type_commit #define MPI_Type_free hypre_MPI_Type_free #define MPI_Op_free hypre_MPI_Op_free #define MPI_Op_create hypre_MPI_Op_create #define MPI_User_function hypre_MPI_User_function /*-------------------------------------------------------------------------- * Types, etc. *--------------------------------------------------------------------------*/ /* These types have associated creation and destruction routines */ typedef HYPRE_Int hypre_MPI_Comm; typedef HYPRE_Int hypre_MPI_Group; typedef HYPRE_Int hypre_MPI_Request; typedef HYPRE_Int hypre_MPI_Datatype; typedef void (hypre_MPI_User_function) (); typedef struct { HYPRE_Int hypre_MPI_SOURCE; HYPRE_Int hypre_MPI_TAG; } hypre_MPI_Status; typedef HYPRE_Int hypre_MPI_Op; typedef HYPRE_Int hypre_MPI_Aint; #define hypre_MPI_COMM_SELF 1 #define hypre_MPI_COMM_WORLD 0 #define hypre_MPI_COMM_NULL -1 #define hypre_MPI_BOTTOM 0x0 #define hypre_MPI_FLOAT 0 #define hypre_MPI_DOUBLE 1 #define hypre_MPI_LONG_DOUBLE 2 #define hypre_MPI_INT 3 #define hypre_MPI_CHAR 4 #define hypre_MPI_LONG 5 #define hypre_MPI_BYTE 6 #define hypre_MPI_REAL 7 #define hypre_MPI_COMPLEX 8 #define hypre_MPI_SUM 0 #define hypre_MPI_MIN 1 #define hypre_MPI_MAX 2 #define hypre_MPI_LOR 3 #define hypre_MPI_SUCCESS 0 #define hypre_MPI_STATUSES_IGNORE 0 #define hypre_MPI_UNDEFINED -9999 #define hypre_MPI_REQUEST_NULL 0 #define hypre_MPI_ANY_SOURCE 1 #define hypre_MPI_ANY_TAG 1 #else /****************************************************************************** * MPI stubs to do casting of HYPRE_Int and hypre_int correctly *****************************************************************************/ typedef MPI_Comm hypre_MPI_Comm; typedef MPI_Group hypre_MPI_Group; typedef MPI_Request hypre_MPI_Request; typedef MPI_Datatype hypre_MPI_Datatype; typedef MPI_Status hypre_MPI_Status; typedef MPI_Op hypre_MPI_Op; typedef MPI_Aint hypre_MPI_Aint; typedef MPI_User_function hypre_MPI_User_function; #define hypre_MPI_COMM_WORLD MPI_COMM_WORLD #define hypre_MPI_COMM_NULL MPI_COMM_NULL #define hypre_MPI_BOTTOM MPI_BOTTOM #define hypre_MPI_COMM_SELF MPI_COMM_SELF #define hypre_MPI_FLOAT MPI_FLOAT #define hypre_MPI_DOUBLE MPI_DOUBLE #define hypre_MPI_LONG_DOUBLE MPI_LONG_DOUBLE /* HYPRE_MPI_INT is defined in HYPRE_utilities.h */ #define hypre_MPI_INT HYPRE_MPI_INT #define hypre_MPI_CHAR MPI_CHAR #define hypre_MPI_LONG MPI_LONG #define hypre_MPI_BYTE MPI_BYTE /* HYPRE_MPI_REAL is defined in HYPRE_utilities.h */ #define hypre_MPI_REAL HYPRE_MPI_REAL /* HYPRE_MPI_COMPLEX is defined in HYPRE_utilities.h */ #define hypre_MPI_COMPLEX HYPRE_MPI_COMPLEX #define hypre_MPI_SUM MPI_SUM #define hypre_MPI_MIN MPI_MIN #define hypre_MPI_MAX MPI_MAX #define hypre_MPI_LOR MPI_LOR #define hypre_MPI_SUCCESS MPI_SUCCESS #define hypre_MPI_STATUSES_IGNORE MPI_STATUSES_IGNORE #define hypre_MPI_UNDEFINED MPI_UNDEFINED #define hypre_MPI_REQUEST_NULL MPI_REQUEST_NULL #define hypre_MPI_ANY_SOURCE MPI_ANY_SOURCE #define hypre_MPI_ANY_TAG MPI_ANY_TAG #define hypre_MPI_SOURCE MPI_SOURCE #define hypre_MPI_TAG MPI_TAG #define hypre_MPI_LAND MPI_LAND #endif /****************************************************************************** * Everything below this applies to both ifdef cases above *****************************************************************************/ /*-------------------------------------------------------------------------- * Prototypes *--------------------------------------------------------------------------*/ /* mpistubs.c */ HYPRE_Int hypre_MPI_Init( hypre_int *argc , char ***argv ); HYPRE_Int hypre_MPI_Finalize( void ); HYPRE_Int hypre_MPI_Abort( hypre_MPI_Comm comm , HYPRE_Int errorcode ); HYPRE_Real hypre_MPI_Wtime( void ); HYPRE_Real hypre_MPI_Wtick( void ); HYPRE_Int hypre_MPI_Barrier( hypre_MPI_Comm comm ); HYPRE_Int hypre_MPI_Comm_create( hypre_MPI_Comm comm , hypre_MPI_Group group , hypre_MPI_Comm *newcomm ); HYPRE_Int hypre_MPI_Comm_dup( hypre_MPI_Comm comm , hypre_MPI_Comm *newcomm ); hypre_MPI_Comm hypre_MPI_Comm_f2c( hypre_int comm ); HYPRE_Int hypre_MPI_Comm_size( hypre_MPI_Comm comm , HYPRE_Int *size ); HYPRE_Int hypre_MPI_Comm_rank( hypre_MPI_Comm comm , HYPRE_Int *rank ); HYPRE_Int hypre_MPI_Comm_free( hypre_MPI_Comm *comm ); HYPRE_Int hypre_MPI_Comm_group( hypre_MPI_Comm comm , hypre_MPI_Group *group ); HYPRE_Int hypre_MPI_Comm_split( hypre_MPI_Comm comm, HYPRE_Int n, HYPRE_Int m, hypre_MPI_Comm * comms ); HYPRE_Int hypre_MPI_Group_incl( hypre_MPI_Group group , HYPRE_Int n , HYPRE_Int *ranks , hypre_MPI_Group *newgroup ); HYPRE_Int hypre_MPI_Group_free( hypre_MPI_Group *group ); HYPRE_Int hypre_MPI_Address( void *location , hypre_MPI_Aint *address ); HYPRE_Int hypre_MPI_Get_count( hypre_MPI_Status *status , hypre_MPI_Datatype datatype , HYPRE_Int *count ); HYPRE_Int hypre_MPI_Alltoall( void *sendbuf , HYPRE_Int sendcount , hypre_MPI_Datatype sendtype , void *recvbuf , HYPRE_Int recvcount , hypre_MPI_Datatype recvtype , hypre_MPI_Comm comm ); HYPRE_Int hypre_MPI_Allgather( void *sendbuf , HYPRE_Int sendcount , hypre_MPI_Datatype sendtype , void *recvbuf , HYPRE_Int recvcount , hypre_MPI_Datatype recvtype , hypre_MPI_Comm comm ); HYPRE_Int hypre_MPI_Allgatherv( void *sendbuf , HYPRE_Int sendcount , hypre_MPI_Datatype sendtype , void *recvbuf , HYPRE_Int *recvcounts , HYPRE_Int *displs , hypre_MPI_Datatype recvtype , hypre_MPI_Comm comm ); HYPRE_Int hypre_MPI_Gather( void *sendbuf , HYPRE_Int sendcount , hypre_MPI_Datatype sendtype , void *recvbuf , HYPRE_Int recvcount , hypre_MPI_Datatype recvtype , HYPRE_Int root , hypre_MPI_Comm comm ); HYPRE_Int hypre_MPI_Gatherv( void *sendbuf , HYPRE_Int sendcount , hypre_MPI_Datatype sendtype , void *recvbuf , HYPRE_Int *recvcounts , HYPRE_Int *displs , hypre_MPI_Datatype recvtype , HYPRE_Int root , hypre_MPI_Comm comm ); HYPRE_Int hypre_MPI_Scatter( void *sendbuf , HYPRE_Int sendcount , hypre_MPI_Datatype sendtype , void *recvbuf , HYPRE_Int recvcount , hypre_MPI_Datatype recvtype , HYPRE_Int root , hypre_MPI_Comm comm ); HYPRE_Int hypre_MPI_Scatterv( void *sendbuf , HYPRE_Int *sendcounts , HYPRE_Int *displs, hypre_MPI_Datatype sendtype , void *recvbuf , HYPRE_Int recvcount , hypre_MPI_Datatype recvtype , HYPRE_Int root , hypre_MPI_Comm comm ); HYPRE_Int hypre_MPI_Bcast( void *buffer , HYPRE_Int count , hypre_MPI_Datatype datatype , HYPRE_Int root , hypre_MPI_Comm comm ); HYPRE_Int hypre_MPI_Send( void *buf , HYPRE_Int count , hypre_MPI_Datatype datatype , HYPRE_Int dest , HYPRE_Int tag , hypre_MPI_Comm comm ); HYPRE_Int hypre_MPI_Recv( void *buf , HYPRE_Int count , hypre_MPI_Datatype datatype , HYPRE_Int source , HYPRE_Int tag , hypre_MPI_Comm comm , hypre_MPI_Status *status ); HYPRE_Int hypre_MPI_Isend( void *buf , HYPRE_Int count , hypre_MPI_Datatype datatype , HYPRE_Int dest , HYPRE_Int tag , hypre_MPI_Comm comm , hypre_MPI_Request *request ); HYPRE_Int hypre_MPI_Irecv( void *buf , HYPRE_Int count , hypre_MPI_Datatype datatype , HYPRE_Int source , HYPRE_Int tag , hypre_MPI_Comm comm , hypre_MPI_Request *request ); HYPRE_Int hypre_MPI_Send_init( void *buf , HYPRE_Int count , hypre_MPI_Datatype datatype , HYPRE_Int dest , HYPRE_Int tag , hypre_MPI_Comm comm , hypre_MPI_Request *request ); HYPRE_Int hypre_MPI_Recv_init( void *buf , HYPRE_Int count , hypre_MPI_Datatype datatype , HYPRE_Int dest , HYPRE_Int tag , hypre_MPI_Comm comm , hypre_MPI_Request *request ); HYPRE_Int hypre_MPI_Irsend( void *buf , HYPRE_Int count , hypre_MPI_Datatype datatype , HYPRE_Int dest , HYPRE_Int tag , hypre_MPI_Comm comm , hypre_MPI_Request *request ); HYPRE_Int hypre_MPI_Startall( HYPRE_Int count , hypre_MPI_Request *array_of_requests ); HYPRE_Int hypre_MPI_Probe( HYPRE_Int source , HYPRE_Int tag , hypre_MPI_Comm comm , hypre_MPI_Status *status ); HYPRE_Int hypre_MPI_Iprobe( HYPRE_Int source , HYPRE_Int tag , hypre_MPI_Comm comm , HYPRE_Int *flag , hypre_MPI_Status *status ); HYPRE_Int hypre_MPI_Test( hypre_MPI_Request *request , HYPRE_Int *flag , hypre_MPI_Status *status ); HYPRE_Int hypre_MPI_Testall( HYPRE_Int count , hypre_MPI_Request *array_of_requests , HYPRE_Int *flag , hypre_MPI_Status *array_of_statuses ); HYPRE_Int hypre_MPI_Wait( hypre_MPI_Request *request , hypre_MPI_Status *status ); HYPRE_Int hypre_MPI_Waitall( HYPRE_Int count , hypre_MPI_Request *array_of_requests , hypre_MPI_Status *array_of_statuses ); HYPRE_Int hypre_MPI_Waitany( HYPRE_Int count , hypre_MPI_Request *array_of_requests , HYPRE_Int *index , hypre_MPI_Status *status ); HYPRE_Int hypre_MPI_Allreduce( void *sendbuf , void *recvbuf , HYPRE_Int count , hypre_MPI_Datatype datatype , hypre_MPI_Op op , hypre_MPI_Comm comm ); HYPRE_Int hypre_MPI_Reduce( void *sendbuf , void *recvbuf , HYPRE_Int count , hypre_MPI_Datatype datatype , hypre_MPI_Op op , HYPRE_Int root , hypre_MPI_Comm comm ); HYPRE_Int hypre_MPI_Scan( void *sendbuf , void *recvbuf , HYPRE_Int count , hypre_MPI_Datatype datatype , hypre_MPI_Op op , hypre_MPI_Comm comm ); HYPRE_Int hypre_MPI_Request_free( hypre_MPI_Request *request ); HYPRE_Int hypre_MPI_Type_contiguous( HYPRE_Int count , hypre_MPI_Datatype oldtype , hypre_MPI_Datatype *newtype ); HYPRE_Int hypre_MPI_Type_vector( HYPRE_Int count , HYPRE_Int blocklength , HYPRE_Int stride , hypre_MPI_Datatype oldtype , hypre_MPI_Datatype *newtype ); HYPRE_Int hypre_MPI_Type_hvector( HYPRE_Int count , HYPRE_Int blocklength , hypre_MPI_Aint stride , hypre_MPI_Datatype oldtype , hypre_MPI_Datatype *newtype ); HYPRE_Int hypre_MPI_Type_struct( HYPRE_Int count , HYPRE_Int *array_of_blocklengths , hypre_MPI_Aint *array_of_displacements , hypre_MPI_Datatype *array_of_types , hypre_MPI_Datatype *newtype ); HYPRE_Int hypre_MPI_Type_commit( hypre_MPI_Datatype *datatype ); HYPRE_Int hypre_MPI_Type_free( hypre_MPI_Datatype *datatype ); HYPRE_Int hypre_MPI_Op_free( hypre_MPI_Op *op ); HYPRE_Int hypre_MPI_Op_create( hypre_MPI_User_function *function , hypre_int commute , hypre_MPI_Op *op ); #ifdef __cplusplus } #endif #endif
16,426
53.214521
226
h
AMG
AMG-master/utilities/qsplit.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ #include "_hypre_utilities.h" #include <math.h> /*-------------------------------------------------------------------------- * hypre_DoubleQuickSplit * C version of the routine "qsplit" from SPARSKIT * Uses a quicksort-type algorithm to split data into * highest "NumberCut" values without completely sorting them. * Data is HYPRE_Real precision data. *--------------------------------------------------------------------------*/ HYPRE_Int hypre_DoubleQuickSplit(HYPRE_Real *values, HYPRE_Int *indices, HYPRE_Int list_length, HYPRE_Int NumberKept ) { HYPRE_Int ierr = 0; HYPRE_Real interchange_value; HYPRE_Real abskey; HYPRE_Int interchange_index; HYPRE_Int first, last; HYPRE_Int mid, j; HYPRE_Int done; first = 0; last = list_length-1; if ( (NumberKept < first+1) || (NumberKept > last+1) ) return( ierr ); /* Loop until the "midpoint" is NumberKept */ done = 0; for ( ; !done; ) { mid = first; abskey = fabs( values[ mid ]); for( j = first+1; j <= last; j ++) { if( fabs( values[ j ]) > abskey ) { mid ++; /* interchange values */ interchange_value = values[ mid]; interchange_index = indices[ mid]; values[ mid] = values[ j]; indices[ mid] = indices[ j]; values[ j] = interchange_value; indices[ j] = interchange_index; } } /* interchange the first and mid value */ interchange_value = values[ mid]; interchange_index = indices[ mid]; values[ mid] = values[ first]; indices[ mid] = indices[ first]; values[ first] = interchange_value; indices[ first] = interchange_index; if ( mid+1 == NumberKept ) { done = 1; break; } if ( mid+1 > NumberKept ) last = mid - 1; else first = mid + 1; } return ( ierr ); }
2,904
30.236559
81
c
AMG
AMG-master/utilities/random.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /****************************************************************************** * * This file contains routines that implement a pseudo-random number generator * detailed in the following paper. * * @article{RNG_Park_Miller, * author = {S. K. Park and K. W. Miller}, * title = {Random number generators: good ones are hard to find}, * journal = {Commun. ACM}, * volume = {31}, * number = {10}, * year = {1988}, * pages = {1192--1201}, * } * * This RNG has been shown to appear fairly random, it is a full period * generating function (the sequence uses all of the values available to it up * to 2147483647), and can be implemented on any architecture using 32-bit * integers. The implementation in this file will not overflow for 32-bit * arithmetic, which all modern computers should support. * * @author David Alber * @date March 2005 * *****************************************************************************/ #include "_hypre_utilities.h" /*-------------------------------------------------------------------------- * Static variables *--------------------------------------------------------------------------*/ static HYPRE_Int Seed = 13579; #define a 16807 #define m 2147483647 #define q 127773 #define r 2836 /*-------------------------------------------------------------------------- * Initializes the pseudo-random number generator to a place in the sequence. * * @param seed an HYPRE_Int containing the seed for the RNG. *--------------------------------------------------------------------------*/ void hypre_SeedRand( HYPRE_Int seed ) { Seed = seed; } /*-------------------------------------------------------------------------- * Computes the next pseudo-random number in the sequence using the global * variable Seed. * * @return a HYPRE_Int between (0, 2147483647] *--------------------------------------------------------------------------*/ HYPRE_Int hypre_RandI() { HYPRE_Int low, high, test; high = Seed / q; low = Seed % q; test = a * low - r * high; if(test > 0) { Seed = test; } else { Seed = test + m; } return Seed; } /*-------------------------------------------------------------------------- * Computes the next pseudo-random number in the sequence using the global * variable Seed. * * @return a HYPRE_Real containing the next number in the sequence divided by * 2147483647 so that the numbers are in (0, 1]. *--------------------------------------------------------------------------*/ HYPRE_Real hypre_Rand() { /* HYPRE_Int low, high, test; high = Seed / q; low = Seed % q; test = a * low - r * high; if(test > 0) { Seed = test; } else { Seed = test + m; } */ return ((HYPRE_Real)(hypre_RandI()) / m); }
3,732
30.905983
81
c
AMG
AMG-master/utilities/threading.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ #include <stdlib.h> #include <stdio.h> #include "_hypre_utilities.h" #ifdef HYPRE_USING_OPENMP HYPRE_Int hypre_NumThreads( ) { HYPRE_Int num_threads; num_threads = omp_get_max_threads(); return num_threads; } /* This next function must be called from within a parallel region! */ HYPRE_Int hypre_NumActiveThreads( ) { HYPRE_Int num_threads; num_threads = omp_get_num_threads(); return num_threads; } /* This next function must be called from within a parallel region! */ HYPRE_Int hypre_GetThreadNum( ) { HYPRE_Int my_thread_num; my_thread_num = omp_get_thread_num(); return my_thread_num; } #endif /* This next function must be called from within a parallel region! */ void hypre_GetSimpleThreadPartition( HYPRE_Int *begin, HYPRE_Int *end, HYPRE_Int n ) { HYPRE_Int num_threads = hypre_NumActiveThreads(); HYPRE_Int my_thread_num = hypre_GetThreadNum(); HYPRE_Int n_per_thread = (n + num_threads - 1)/num_threads; *begin = hypre_min(n_per_thread*my_thread_num, n); *end = hypre_min(*begin + n_per_thread, n); }
1,996
26.356164
81
c
AMG
AMG-master/utilities/threading.h
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ #ifndef hypre_THREADING_HEADER #define hypre_THREADING_HEADER #ifdef HYPRE_USING_OPENMP HYPRE_Int hypre_NumThreads( void ); HYPRE_Int hypre_NumActiveThreads( void ); HYPRE_Int hypre_GetThreadNum( void ); #else #define hypre_NumThreads() 1 #define hypre_NumActiveThreads() 1 #define hypre_GetThreadNum() 0 #endif void hypre_GetSimpleThreadPartition( HYPRE_Int *begin, HYPRE_Int *end, HYPRE_Int n ); #endif
1,338
33.333333
85
h
AMG
AMG-master/utilities/timer.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /* * File: timer.c * Author: Scott Kohn (skohn@llnl.gov) * Description: somewhat portable timing routines for C++, C, and Fortran * * If TIMER_USE_MPI is defined, then the MPI timers are used to get * wallclock seconds, since we assume that the MPI timers have better * resolution than the system timers. */ #include "_hypre_utilities.h" #include <time.h> #ifndef WIN32 #include <unistd.h> #include <sys/times.h> #endif #ifdef TIMER_USE_MPI #include "mpi.h" #endif HYPRE_Real time_getWallclockSeconds(void) { #ifdef TIMER_USE_MPI return(hypre_MPI_Wtime()); #else #ifdef WIN32 clock_t cl=clock(); return(((HYPRE_Real) cl)/((HYPRE_Real) CLOCKS_PER_SEC)); #else struct tms usage; hypre_longint wallclock = times(&usage); return(((HYPRE_Real) wallclock)/((HYPRE_Real) sysconf(_SC_CLK_TCK))); #endif #endif } HYPRE_Real time_getCPUSeconds(void) { #ifndef TIMER_NO_SYS clock_t cpuclock = clock(); return(((HYPRE_Real) (cpuclock))/((HYPRE_Real) CLOCKS_PER_SEC)); #else return(0.0); #endif } HYPRE_Real time_get_wallclock_seconds_(void) { return(time_getWallclockSeconds()); } HYPRE_Real time_get_cpu_seconds_(void) { return(time_getCPUSeconds()); }
2,114
27.581081
81
c
AMG
AMG-master/utilities/timing.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /****************************************************************************** * * Routines for doing timing. * *****************************************************************************/ #define HYPRE_TIMING #define HYPRE_TIMING_GLOBALS #include "_hypre_utilities.h" #include "timing.h" /*------------------------------------------------------- * Timing macros *-------------------------------------------------------*/ #define hypre_StartTiming() \ hypre_TimingWallCount -= time_getWallclockSeconds();\ hypre_TimingCPUCount -= time_getCPUSeconds() #define hypre_StopTiming() \ hypre_TimingWallCount += time_getWallclockSeconds();\ hypre_TimingCPUCount += time_getCPUSeconds() #define hypre_global_timing_ref(index,field) hypre_global_timing->field /*-------------------------------------------------------------------------- * hypre_InitializeTiming *--------------------------------------------------------------------------*/ HYPRE_Int hypre_InitializeTiming( const char *name ) { HYPRE_Int time_index; HYPRE_Real *old_wall_time; HYPRE_Real *old_cpu_time; HYPRE_Real *old_flops; char **old_name; HYPRE_Int *old_state; HYPRE_Int *old_num_regs; HYPRE_Int new_name; HYPRE_Int i; /*------------------------------------------------------- * Allocate global TimingType structure if needed *-------------------------------------------------------*/ if (hypre_global_timing == NULL) { hypre_global_timing = hypre_CTAlloc(hypre_TimingType, 1); } /*------------------------------------------------------- * Check to see if name has already been registered *-------------------------------------------------------*/ new_name = 1; for (i = 0; i < (hypre_global_timing_ref(threadid, size)); i++) { if (hypre_TimingNumRegs(i) > 0) { if (strcmp(name, hypre_TimingName(i)) == 0) { new_name = 0; time_index = i; hypre_TimingNumRegs(time_index) ++; break; } } } if (new_name) { for (i = 0; i < hypre_global_timing_ref(threadid ,size); i++) { if (hypre_TimingNumRegs(i) == 0) { break; } } time_index = i; } /*------------------------------------------------------- * Register the new timing name *-------------------------------------------------------*/ if (new_name) { if (time_index == (hypre_global_timing_ref(threadid, size))) { old_wall_time = (hypre_global_timing_ref(threadid, wall_time)); old_cpu_time = (hypre_global_timing_ref(threadid, cpu_time)); old_flops = (hypre_global_timing_ref(threadid, flops)); old_name = (hypre_global_timing_ref(threadid, name)); old_state = (hypre_global_timing_ref(threadid, state)); old_num_regs = (hypre_global_timing_ref(threadid, num_regs)); (hypre_global_timing_ref(threadid, wall_time)) = hypre_CTAlloc(HYPRE_Real, (time_index+1)); (hypre_global_timing_ref(threadid, cpu_time)) = hypre_CTAlloc(HYPRE_Real, (time_index+1)); (hypre_global_timing_ref(threadid, flops)) = hypre_CTAlloc(HYPRE_Real, (time_index+1)); (hypre_global_timing_ref(threadid, name)) = hypre_CTAlloc(char *, (time_index+1)); (hypre_global_timing_ref(threadid, state)) = hypre_CTAlloc(HYPRE_Int, (time_index+1)); (hypre_global_timing_ref(threadid, num_regs)) = hypre_CTAlloc(HYPRE_Int, (time_index+1)); (hypre_global_timing_ref(threadid, size)) ++; for (i = 0; i < time_index; i++) { hypre_TimingWallTime(i) = old_wall_time[i]; hypre_TimingCPUTime(i) = old_cpu_time[i]; hypre_TimingFLOPS(i) = old_flops[i]; hypre_TimingName(i) = old_name[i]; hypre_TimingState(i) = old_state[i]; hypre_TimingNumRegs(i) = old_num_regs[i]; } hypre_TFree(old_wall_time); hypre_TFree(old_cpu_time); hypre_TFree(old_flops); hypre_TFree(old_name); hypre_TFree(old_state); hypre_TFree(old_num_regs); } hypre_TimingName(time_index) = hypre_CTAlloc(char, 80); strncpy(hypre_TimingName(time_index), name, 79); hypre_TimingState(time_index) = 0; hypre_TimingNumRegs(time_index) = 1; (hypre_global_timing_ref(threadid, num_names)) ++; } return time_index; } /*-------------------------------------------------------------------------- * hypre_FinalizeTiming *--------------------------------------------------------------------------*/ HYPRE_Int hypre_FinalizeTiming( HYPRE_Int time_index ) { HYPRE_Int ierr = 0; HYPRE_Int i; if (hypre_global_timing == NULL) return ierr; if (time_index < (hypre_global_timing_ref(threadid, size))) { if (hypre_TimingNumRegs(time_index) > 0) { hypre_TimingNumRegs(time_index) --; } if (hypre_TimingNumRegs(time_index) == 0) { hypre_TFree(hypre_TimingName(time_index)); (hypre_global_timing_ref(threadid, num_names)) --; } } if ((hypre_global_timing -> num_names) == 0) { for (i = 0; i < (hypre_global_timing -> size); i++) { hypre_TFree(hypre_global_timing_ref(i, wall_time)); hypre_TFree(hypre_global_timing_ref(i, cpu_time)); hypre_TFree(hypre_global_timing_ref(i, flops)); hypre_TFree(hypre_global_timing_ref(i, name)); hypre_TFree(hypre_global_timing_ref(i, state)); hypre_TFree(hypre_global_timing_ref(i, num_regs)); } hypre_TFree(hypre_global_timing); hypre_global_timing = NULL; } return ierr; } /*-------------------------------------------------------------------------- * hypre_IncFLOPCount *--------------------------------------------------------------------------*/ HYPRE_Int hypre_IncFLOPCount( HYPRE_Int inc ) { HYPRE_Int ierr = 0; if (hypre_global_timing == NULL) return ierr; hypre_TimingFLOPCount += (HYPRE_Real) (inc); return ierr; } /*-------------------------------------------------------------------------- * hypre_BeginTiming *--------------------------------------------------------------------------*/ HYPRE_Int hypre_BeginTiming( HYPRE_Int time_index ) { HYPRE_Int ierr = 0; if (hypre_global_timing == NULL) return ierr; if (hypre_TimingState(time_index) == 0) { hypre_StopTiming(); hypre_TimingWallTime(time_index) -= hypre_TimingWallCount; hypre_TimingCPUTime(time_index) -= hypre_TimingCPUCount; hypre_TimingFLOPS(time_index) -= hypre_TimingFLOPCount; hypre_StartTiming(); } hypre_TimingState(time_index) ++; return ierr; } /*-------------------------------------------------------------------------- * hypre_EndTiming *--------------------------------------------------------------------------*/ HYPRE_Int hypre_EndTiming( HYPRE_Int time_index ) { HYPRE_Int ierr = 0; if (hypre_global_timing == NULL) return ierr; hypre_TimingState(time_index) --; if (hypre_TimingState(time_index) == 0) { hypre_StopTiming(); hypre_TimingWallTime(time_index) += hypre_TimingWallCount; hypre_TimingCPUTime(time_index) += hypre_TimingCPUCount; hypre_TimingFLOPS(time_index) += hypre_TimingFLOPCount; hypre_StartTiming(); } return ierr; } /*-------------------------------------------------------------------------- * hypre_ClearTiming *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ClearTiming( ) { HYPRE_Int ierr = 0; HYPRE_Int i; if (hypre_global_timing == NULL) return ierr; for (i = 0; i < (hypre_global_timing_ref(threadid,size)); i++) { hypre_TimingWallTime(i) = 0.0; hypre_TimingCPUTime(i) = 0.0; hypre_TimingFLOPS(i) = 0.0; } return ierr; } /*-------------------------------------------------------------------------- * hypre_PrintTiming *--------------------------------------------------------------------------*/ HYPRE_Int hypre_PrintTiming( const char *heading, HYPRE_Real *wall_time_ptr, MPI_Comm comm ) { HYPRE_Int ierr = 0; HYPRE_Real local_wall_time; HYPRE_Real local_cpu_time; HYPRE_Real wall_time; HYPRE_Real cpu_time; HYPRE_Real wall_mflops; HYPRE_Real cpu_mflops; HYPRE_Int i; HYPRE_Int myrank; if (hypre_global_timing == NULL) return ierr; hypre_MPI_Comm_rank(comm, &myrank ); /* print heading */ if (myrank == 0) { hypre_printf("=============================================\n"); hypre_printf("%s:\n", heading); hypre_printf("=============================================\n"); } for (i = 0; i < (hypre_global_timing -> size); i++) { if (hypre_TimingNumRegs(i) > 0) { local_wall_time = hypre_TimingWallTime(i); local_cpu_time = hypre_TimingCPUTime(i); hypre_MPI_Allreduce(&local_wall_time, &wall_time, 1, hypre_MPI_REAL, hypre_MPI_MAX, comm); hypre_MPI_Allreduce(&local_cpu_time, &cpu_time, 1, hypre_MPI_REAL, hypre_MPI_MAX, comm); if (myrank == 0) { hypre_printf("%s:\n", hypre_TimingName(i)); *wall_time_ptr = wall_time; /* print wall clock info */ hypre_printf(" wall clock time = %f seconds\n", wall_time); if (wall_time) wall_mflops = hypre_TimingFLOPS(i) / wall_time / 1.0E6; else wall_mflops = 0.0; hypre_printf(" wall MFLOPS = %f\n", wall_mflops); /* print CPU clock info */ hypre_printf(" cpu clock time = %f seconds\n", cpu_time); if (cpu_time) cpu_mflops = hypre_TimingFLOPS(i) / cpu_time / 1.0E6; else cpu_mflops = 0.0; hypre_printf(" cpu MFLOPS = %f\n\n", cpu_mflops); } } } return ierr; }
11,219
29.572207
81
c
AMG
AMG-master/utilities/timing.h
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /****************************************************************************** * * Header file for doing timing * *****************************************************************************/ #ifndef HYPRE_TIMING_HEADER #define HYPRE_TIMING_HEADER #include <stdlib.h> #include <stdio.h> #include <string.h> #ifdef __cplusplus extern "C" { #endif /*-------------------------------------------------------------------------- * Prototypes for low-level timing routines *--------------------------------------------------------------------------*/ /* timer.c */ HYPRE_Real time_getWallclockSeconds( void ); HYPRE_Real time_getCPUSeconds( void ); HYPRE_Real time_get_wallclock_seconds_( void ); HYPRE_Real time_get_cpu_seconds_( void ); /*-------------------------------------------------------------------------- * With timing off *--------------------------------------------------------------------------*/ #ifndef HYPRE_TIMING #define hypre_InitializeTiming(name) 0 #define hypre_FinalizeTiming(index) #define hypre_IncFLOPCount(inc) #define hypre_BeginTiming(i) #define hypre_EndTiming(i) #define hypre_PrintTiming(heading, comm) #define hypre_ClearTiming() /*-------------------------------------------------------------------------- * With timing on *--------------------------------------------------------------------------*/ #else /*------------------------------------------------------- * Global timing structure *-------------------------------------------------------*/ typedef struct { HYPRE_Real *wall_time; HYPRE_Real *cpu_time; HYPRE_Real *flops; char **name; HYPRE_Int *state; /* boolean flag to allow for recursive timing */ HYPRE_Int *num_regs; /* count of how many times a name is registered */ HYPRE_Int num_names; HYPRE_Int size; HYPRE_Real wall_count; HYPRE_Real CPU_count; HYPRE_Real FLOP_count; } hypre_TimingType; #ifdef HYPRE_TIMING_GLOBALS hypre_TimingType *hypre_global_timing = NULL; #else extern hypre_TimingType *hypre_global_timing; #endif /*------------------------------------------------------- * Accessor functions *-------------------------------------------------------*/ #define hypre_TimingWallTime(i) (hypre_global_timing -> wall_time[(i)]) #define hypre_TimingCPUTime(i) (hypre_global_timing -> cpu_time[(i)]) #define hypre_TimingFLOPS(i) (hypre_global_timing -> flops[(i)]) #define hypre_TimingName(i) (hypre_global_timing -> name[(i)]) #define hypre_TimingState(i) (hypre_global_timing -> state[(i)]) #define hypre_TimingNumRegs(i) (hypre_global_timing -> num_regs[(i)]) #define hypre_TimingWallCount (hypre_global_timing -> wall_count) #define hypre_TimingCPUCount (hypre_global_timing -> CPU_count) #define hypre_TimingFLOPCount (hypre_global_timing -> FLOP_count) /*------------------------------------------------------- * Prototypes *-------------------------------------------------------*/ /* timing.c */ HYPRE_Int hypre_InitializeTiming( const char *name ); HYPRE_Int hypre_FinalizeTiming( HYPRE_Int time_index ); HYPRE_Int hypre_IncFLOPCount( HYPRE_Int inc ); HYPRE_Int hypre_BeginTiming( HYPRE_Int time_index ); HYPRE_Int hypre_EndTiming( HYPRE_Int time_index ); HYPRE_Int hypre_ClearTiming( void ); HYPRE_Int hypre_PrintTiming( const char *heading , MPI_Comm comm ); #endif #ifdef __cplusplus } #endif #endif
4,315
32.71875
81
h
AMG
AMG-master/utilities/umalloc_local.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ #ifdef HYPRE_USE_UMALLOC #include "umalloc_local.h" void *_uget_fn(Heap_t usrheap, size_t *length, HYPRE_Int *clean) { void *p; *length = ((*length) / INITIAL_HEAP_SIZE) * INITIAL_HEAP_SIZE + INITIAL_HEAP_SIZE; *clean = _BLOCK_CLEAN; p = (void *) calloc(*length, 1); return p; } void _urelease_fn(Heap_t usrheap, void *p, size_t size) { free (p); return; } #else /* this is used only to eliminate compiler warnings */ char umalloc_empty; #endif
1,416
29.804348
81
c
AMG
AMG-master/utilities/umalloc_local.h
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ #ifndef UMALLOC_LOCAL_HEADER #define UMALLOC_LOCAL_HEADER #ifdef HYPRE_USE_UMALLOC #include <umalloc.h> #define MAX_THREAD_COUNT 10 #define INITIAL_HEAP_SIZE 500000 #define GET_MISS_COUNTS struct upc_struct { Heap_t myheap; }; void *_uinitial_block[MAX_THREAD_COUNT]; struct upc_struct _uparam[MAX_THREAD_COUNT]; HYPRE_Int _uheapReleasesCount=0; HYPRE_Int _uheapGetsCount=0; void *_uget_fn(Heap_t usrheap, size_t *length, HYPRE_Int *clean); void _urelease_fn(Heap_t usrheap, void *p, size_t size); #endif #endif
1,449
29.851064
81
h
null
r-mae-main/CODE_OF_CONDUCT.md
# Code of Conduct ## Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to make participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. ## Our Standards Examples of behavior that contributes to creating a positive environment include: * Using welcoming and inclusive language * Being respectful of differing viewpoints and experiences * Gracefully accepting constructive criticism * Focusing on what is best for the community * Showing empathy towards other community members Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or advances * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or electronic address, without explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Our Responsibilities Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. ## Scope This Code of Conduct applies within all project spaces, and it also applies when an individual is representing the project or its community in public spaces. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. This Code of Conduct also applies outside the project spaces when there is a reasonable belief that an individual's behavior may have a negative impact on the project or its community. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at <opensource-conduct@fb.com>. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html [homepage]: https://www.contributor-covenant.org For answers to common questions about this code of conduct, see https://www.contributor-covenant.org/faq
3,540
43.2625
87
md
null
r-mae-main/CONTRIBUTING.md
# Contributing to r-mae We want to make contributing to this project as easy and transparent as possible. ## Pull Requests We actively welcome your pull requests. 1. Fork the repo and create your branch from `main`. 2. If you've added code that should be tested, add tests. 3. If you've changed APIs, update the documentation. 4. Ensure the test suite passes. 5. Make sure your code lints. 6. If you haven't already, complete the Contributor License Agreement ("CLA"). ## Contributor License Agreement ("CLA") In order to accept your pull request, we need you to submit a CLA. You only need to do this once to work on any of Facebook's open source projects. Complete your CLA here: <https://code.facebook.com/cla> ## Issues We use GitHub issues to track public bugs. Please ensure your description is clear and has sufficient instructions to be able to reproduce the issue. Facebook has a [bounty program](https://www.facebook.com/whitehat/) for the safe disclosure of security bugs. In those cases, please go through the process outlined on that page and do not file a public issue. ## License By contributing to r-mae, you agree that your contributions will be licensed under the LICENSE file in the root directory of this source tree.
1,244
39.16129
80
md
null
r-mae-main/README.md
# R-MAE: Regions Meet Masked Autoencoders ![R-MAE](./figs/rmae.png) This repository is an official implementation of [R-MAE: Regions Meet Masked Autoencoders](https://arxiv.org/abs/2306.05411) in PyTorch. It is based on the [BoxeR](https://github.com/kienduynguyen/BoxeR) repository, but adapted for self-supervised pre-training. ## Citing R-MAE If you find R-MAE useful in your research, please consider citing: ```bibtex @article{nguyen2023rmae, title={R-MAE: Regions Meet Masked Autoencoders}, author={Duy{-}Kien Nguyen, Vaibhav Aggarwal, Yanghao Li, Martin R. Oswald, Alexander Kirillov, Cees G. M. Snoek, Xinlei Chen}, journal={arXiv preprint arXiv:2306.05411}, year={2023} } ``` ## Installation ### Requirements * Linux, CUDA>=11, GCC>=5.4 * Python>=3.8 We recommend you to use Anaconda to create a conda environment: ```bash conda create -n rmae python=3.8 ``` Then, activate the environment: ```bash conda activate rmae ``` * PyTorch>=1.10.1, torchvision>=0.11.2 (following instructions [here](https://pytorch.org/)) For example, you could install pytorch and torchvision as following: ```bash pip install torch==1.10.1+cu113 torchvision==0.11.2+cu113 -f https://download.pytorch.org/whl/cu113/torch_stable.html ``` * Other requirements & Compilation If you are inside the repository, then run: ```bash python -m pip install -e ./ ``` ## Usage ### Dataset preparation The datasets are assumed to exist in a directory specified by the environment variable $E2E_DATASETS. If the environment variable is not specified, it will be set to be ```.data```. Under this directory, our code will look for datasets in the structure described below. ``` $E2E_DATASETS/ ├── coco/ └── imnet/ ``` For pre-training on COCO, please download [COCO 2017 dataset](https://cocodataset.org/) and organize them as following: ``` $E2E_DATASETS/ └── coco/ ├── annotations/ ├── instances_train2017.json ├── instances_val2017.json └── image_info_unlabeled2017.json └── image/ ├── train2017/ ├── fh_train2017/ ├── val2017/ ├── fh_val2017/ ├── unlabeled2017/ └── fh_unlabeled2017/ ``` You can generate FH masks for our pre-training by running ```create_fh_mask_for_coco.py``` in ```tools/preprocess```. For pre-training on ImageNet, please download [ImageNet dataset](https://www.image-net.org/) and organize them as following: ``` $E2E_DATASETS/ └── imagenet/ ├── train/ ├── fh_train/ ├── val/ └── fh_val/ ``` You can generate FH masks for our pre-training by running ```create_fh_mask_for_imnet.py``` in ```tools/preprocess```. ### Training Our script is able to automatically detect the number of available gpus on a single node. It works best with Slurm system when it can auto-detect the number of available gpus along with nodes. The command for pre-training R-MAE is simple as following: ```bash python tools/run.py --config ${CONFIG_PATH} --model ${MODEL} --task ${TASK} --dataset ${DATASET} ``` For example, * Pre-training on COCO ```bash python tools/run.py --config pretrain/config/RMAE/COCO/rmae_fh_4000eps.yaml --model rmae --task pretrain --dataset coco ``` * Pre-training on ImageNet ```bash python tools/run.py --config pretrain/config/RMAE/ImageNet/rmae_fh_800eps.yaml --model rmae --task pretrain --dataset imnet ``` #### Some tips to speed-up training * If your file system is slow to read images but your memory is huge, you may consider enabling 'cache_mode' option to load whole dataset into memory at the beginning of training: ```bash python tools/run.py --config ${CONFIG_PATH} --model ${MODEL} --task ${TASK} --dataset ${DATASET} dataset_config.${DATASET}_${TASK}.sampler=shard ``` * If your GPU memory does not fit the batch size, you may consider to use 'iter_per_update' to perform gradient accumulation: ```bash python tools/run.py --config ${CONFIG_PATH} --model ${MODEL} --task ${TASK} --dataset ${DATASET} training.iter_per_update=2 ``` * Our code also supports mixed precision training. It is recommended to use when you GPUs architecture can perform fast FP16 operations: ```bash python tools/run.py --config ${CONFIG_PATH} --model ${MODEL} --task ${TASK} --dataset ${DATASET} training.use_fp16=(float16 or bfloat16) ``` ## License This project is under the CC-BY-NC 4.0 license. See [LICENSE](LICENSE) for details.
4,360
30.832117
261
md
null
r-mae-main/setup.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import os import torch from setuptools import find_packages, setup TORCH_VERSION = tuple(int(x) for x in torch.__version__.split(".")[:2]) assert TORCH_VERSION >= (1, 8), "Requires PyTorch >= 1.8" def get_version(): init_py_path = os.path.join( os.path.abspath(os.path.dirname(__file__)), "pretrain", "__init__.py" ) init_py = open(init_py_path, "r").readlines() version_line = [l.strip() for l in init_py if l.startswith("__version__")][0] version = version_line.split("=")[-1].strip().strip("'\"") return version setup( name="pretrain", version=get_version(), author="Duy-Kien Nguyen", description="Implementation for R-MAE.", packages=find_packages(exclude=("tests", "exps", "scripts")), python_requires=">=3.8", install_requires=[ "Pillow>=7.1", "omegaconf>=2.1", "pycocotools", "numpy", "matplotlib", "scikit-image", "opencv-python", "tensorboard", ], )
1,193
24.956522
81
py
null
r-mae-main/pretrain/__init__.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import pretrain.utils import pretrain.model import pretrain.optim import pretrain.trainer import pretrain.dataset from .utils.env import setup_environment setup_environment() __version__ = "0.1"
396
21.055556
61
py
null
r-mae-main/pretrain/config/default.yaml
# Configuration for training training: # Name of the trainer class used to define the training/evalution loop trainer: "base_trainer" max_norm: 0 # Seed to be used for training. -1 means random seed. # Either pass fixed through your config or command line arguments # Pass null to the seed if you don't want it seeded anyhow and # want to leave it to default seed: 0 # Maximum number of iterations the training will run max_update: null # Maximum epochs in case you don't want to use max_updates # Can be mixed with max iterations, so it will stop whichever is # completed first. Default: null means epochs won't be used max_epoch: null iter_per_update: 1 use_fp16: none use_compile: true # Type of run, train+inference by default means both training and inference # (test) stage will be run, if run_type contains 'val', # inference will be run on val set also. run_type: train_val_test num_checkpoint: 2 # Directory for saving checkpoints and other metadata save_dir: "./save" # After `log_interval` iterations, current iteration's training loss and # metrics will be reported. This will also report validation # loss and metrics on a single batch from validation set # to provide an estimate on validation side log_interval: 100 # Level of logging, only logs which are >= to current level will be logged logger_level: info # Log format: json, simple log_format: simple # Whether to log detailed final configuration parameters log_detailed_config: true # Whether MMF should log or not, Default: False, which means # mmf will log by default should_not_log: false # Tensorboard control, by default tensorboard is disabled tensorboard: false # Log directory for tensorboard, default points to same as logs tensorboard_logdir: null # Size of each batch. If distributed or data_parallel # is used, this will be divided equally among GPUs batch_size: 512 # Number of workers to be used in dataloaders num_workers: 4 # Whether to pin memory in dataloader pin_memory: true # After `checkpoint_interval` iterations, MMF will make a snapshot # which will involve creating a checkpoint for current training scenarios checkpoint_interval: 1000 # This will evaluate validation metrics on whole validation set after evaluation interval evaluation_interval: 1000 # Local rank of the GPU device device: cuda local_rank: null # If resume is true, MMF will try to load automatically load # last of same parameters from save_dir resume: false # `resume_file` can be used to load a specific checkpoint from a file resume_file: null # If verbose dump is active, MMF will dump dataset, model specific # information which can be useful in debugging verbose_dump: false # Turn on if you want to ignore unused parameters in case of DDP find_unused_parameters: false # Configuration for models, default configuration files for various models # included in MMF can be found under configs directory in root folder model_config: {} # Configuration for datasets. Separate configuration # for different datasets are included in dataset folder # which can be mixed and matched to train multiple datasets together # An example for mixing all vqa datasets is present under vqa folder dataset_config: {} # Defines which tasks from the above tasks you want to train on task: null # Defines which datasets from the above tasks you want to train on dataset: null # Defines which model you want to train on model: null # Config file to be optionally passed by the user config: null # Configuration for optimizer, examples can be found in models' configs in # configs folder optimizer: {} # Configuration for scheduler, examples can be found in models' configs scheduler: {} # Configuration for the distributed setup distributed: # Typically tcp://hostname:port that will be used to establish initial connection init_method: null # Rank of the current worker rank: 0 # Port number, not required if using init_method, port: -1 # Backend for distributed setup backend: nccl # Total number of GPUs across all nodes (default: all visible GPUs) world_size: ${device_count:} # Set if you do not want spawn multiple processes even if # multiple GPUs are visible no_spawn: false
4,311
33.496
91
yaml
null
r-mae-main/pretrain/config/MAE/base_mae.yaml
model_config: mae: mask_ratio: 0.75 mae_vit: arch: mae_base_patch16 params: norm_pix_loss: true decoder_embed_dim: 512 decoder_depth: 8 decoder_num_heads: 16 optimizer: type: adamw params: lr: 2.4e-3 # 1.5e-4 * batch_size / 256 use_oss: false weight_decay: 0.05 wd_norm: 0.0 wd_bias: 0.0 eps: 1.0e-08 betas: - 0.9 - 0.95 scheduler: type: cosine_annealing params: T_max: ${training.max_update} eta_min: 0.0 use_warmup: true warmup_factor: 0.0 warmup_iterations: 12000 training: max_update: 144000 batch_size: 4096 iter_per_update: 1 find_unused_parameters: false tensorboard: true evaluation_interval: 5 checkpoint_interval: 1 log_interval: 200 run_type: train iou_type: null
820
17.244444
42
yaml
null
r-mae-main/pretrain/config/MAE/COCO/mae_4000eps.yaml
includes: - config/MAE/base_mae.yaml dataset_config: coco_pretrain: cache_mode: false sampler: infinite filter_small_patches: false imdb_files: train: image_folder: - image/train2017 mask_folder: - image/fh_train2017 anno_file: - annotations/instances_train2017.json val: image_folder: - image/val2017 mask_folder: - image/fh_val2017 anno_file: - annotations/instances_val2017.json processors: image_train_processor: type: compose params: preprocessors: - type: random_resize_crop_w_loop params: image_size: - 224 - 224 scale: - 0.2 - 1.0 ratio: - 0.75 - 1.3333333333333333 interpolation: 3 - type: random_horizontal_flip params: prob: 0.5 - type: to_tensor params: {} - type: normalize params: mean: - 0.485 - 0.456 - 0.406 std: - 0.229 - 0.224 - 0.225 image_test_processor: type: compose params: preprocessors: - type: resize params: image_size: - 224 - 224 interpolation: 3 - type: to_tensor params: {} - type: normalize params: mean: - 0.485 - 0.456 - 0.406 std: - 0.229 - 0.224 - 0.225 training: run_type: train_val evaluation_interval: 50 checkpoint_interval: 10
2,002
23.426829
48
yaml
null
r-mae-main/pretrain/config/MAE/ImageNet/mae_800eps.yaml
includes: - config/MAE/base_mae.yaml dataset_config: imnet_pretrain: cache_mode: false sampler: infinite filter_small_patches: false imdb_files: train: image_folder: train mask_folder: fh_train val: image_folder: val mask_folder: fh_val processors: image_train_processor: type: compose params: preprocessors: - type: random_resize_crop_w_loop params: image_size: - 224 - 224 scale: - 0.2 - 1.0 ratio: - 0.75 - 1.3333333333333333 interpolation: 3 - type: random_horizontal_flip params: prob: 0.5 - type: to_tensor params: {} - type: normalize params: mean: - 0.485 - 0.456 - 0.406 std: - 0.229 - 0.224 - 0.225 image_test_processor: type: compose params: preprocessors: - type: resize params: image_size: - 224 - 224 interpolation: 3 - type: to_tensor params: {} - type: normalize params: mean: - 0.485 - 0.456 - 0.406 std: - 0.229 - 0.224 - 0.225 scheduler: type: cosine_annealing params: T_max: ${training.max_update} eta_min: 0.0 use_warmup: true warmup_factor: 0.0 warmup_iterations: 12480 training: max_update: 249600
1,899
22.45679
45
yaml
null
r-mae-main/pretrain/config/RMAE/base_rmae.yaml
model_config: rmae: mask_ratio: 0.75 mae_vit: arch: rmae_base_patch16 params: norm_pix_loss: true use_mae_loss: true num_region: 0 mae_loss_weight: 1.0 bg_loss_weight: 1.0 region_loss_weight: 1.0 region_mask_ratio: 0.75 region_enc_dim: 128 region_enc_depth: 1 region_enc_num_heads: 8 region_dec_dim: 128 region_dec_depth: 1 region_dec_num_heads: 8 region_sample_type: random region_cross_layer: 8 optimizer: type: adamw params: lr: 2.4e-3 # 1.5e-4 * batch_size / 256 use_oss: false weight_decay: 0.05 wd_norm: 0.0 wd_bias: 0.0 eps: 1.0e-08 betas: - 0.9 - 0.95 scheduler: type: cosine_annealing params: T_max: ${training.max_update} eta_min: 0.0 use_warmup: true warmup_factor: 0.0 warmup_iterations: 12000 training: max_update: 144000 batch_size: 4096 iter_per_update: 1 find_unused_parameters: false tensorboard: true evaluation_interval: 5 checkpoint_interval: 1 log_interval: 200 run_type: train iou_type: null
1,147
19.5
42
yaml
null
r-mae-main/pretrain/config/RMAE/COCO/rmae_fh_4000eps.yaml
includes: - config/RMAE/base_rmae.yaml dataset_config: coco_pretrain: sampler: infinite mask_type: fh filter_small_patches: false imdb_files: train: image_folder: - image/train2017 mask_folder: - image/fh_train2017 anno_file: - annotations/instances_train2017.json val: image_folder: - image/val2017 mask_folder: - image/fh_val2017 anno_file: - annotations/instances_val2017.json processors: image_train_processor: type: compose params: preprocessors: - type: random_resize_crop_w_loop params: image_size: - 224 - 224 scale: - 0.2 - 1.0 ratio: - 0.75 - 1.3333333333333333 interpolation: 3 - type: random_horizontal_flip params: prob: 0.5 - type: to_tensor params: {} - type: normalize params: mean: - 0.485 - 0.456 - 0.406 std: - 0.229 - 0.224 - 0.225 image_test_processor: type: compose params: preprocessors: - type: resize params: image_size: - 224 - 224 interpolation: 3 - type: to_tensor params: {} - type: normalize params: mean: - 0.485 - 0.456 - 0.406 std: - 0.229 - 0.224 - 0.225 training: run_type: train_val evaluation_interval: 50 checkpoint_interval: 10
2,000
23.402439
48
yaml
null
r-mae-main/pretrain/config/RMAE/COCO/rmae_fh_ccplus_4000eps.yaml
includes: - config/RMAE/base_rmae.yaml dataset_config: coco_pretrain: sampler: infinite mask_type: fh filter_small_patches: false imdb_files: train: image_folder: - image/train2017 - image/unlabeled2017 mask_folder: - image/fh_train2017 - image/fh_unlabeled2017 anno_file: - annotations/instances_train2017.json - annotations/image_info_unlabeled2017.json val: image_folder: - image/val2017 mask_folder: - image/fh_val2017 anno_file: - annotations/instances_val2017.json processors: image_train_processor: type: compose params: preprocessors: - type: random_resize_crop_w_loop params: image_size: - 224 - 224 scale: - 0.2 - 1.0 ratio: - 0.75 - 1.3333333333333333 interpolation: 3 - type: random_horizontal_flip params: prob: 0.5 - type: to_tensor params: {} - type: normalize params: mean: - 0.485 - 0.456 - 0.406 std: - 0.229 - 0.224 - 0.225 image_test_processor: type: compose params: preprocessors: - type: resize params: image_size: - 224 - 224 interpolation: 3 - type: to_tensor params: {} - type: normalize params: mean: - 0.485 - 0.456 - 0.406 std: - 0.229 - 0.224 - 0.225 training: run_type: train_val evaluation_interval: 50 checkpoint_interval: 10
2,121
23.964706
53
yaml
null
r-mae-main/pretrain/config/RMAE/ImageNet/rmae_fh_800eps.yaml
includes: - config/RMAE/base_rmae.yaml dataset_config: imnet_pretrain: sampler: infinite mask_type: fh cache_mask: true filter_small_patches: false imdb_files: train: image_folder: train mask_folder: fh_train val: image_folder: val mask_folder: fh_val processors: image_train_processor: type: compose params: preprocessors: - type: random_resize_crop_w_loop params: image_size: - 224 - 224 scale: - 0.2 - 1.0 ratio: - 0.75 - 1.3333333333333333 interpolation: 3 - type: random_horizontal_flip params: prob: 0.5 - type: to_tensor params: {} - type: normalize params: mean: - 0.485 - 0.456 - 0.406 std: - 0.229 - 0.224 - 0.225 image_test_processor: type: compose params: preprocessors: - type: resize params: image_size: - 224 - 224 interpolation: 3 - type: to_tensor params: {} - type: normalize params: mean: - 0.485 - 0.456 - 0.406 std: - 0.229 - 0.224 - 0.225 scheduler: type: cosine_annealing params: T_max: ${training.max_update} eta_min: 0.0 use_warmup: true warmup_factor: 0.0 warmup_iterations: 12480 training: max_update: 249600
1,918
22.402439
45
yaml
null
r-mae-main/pretrain/dataset/__init__.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import importlib import os import warnings from torch.utils.data import DataLoader, DistributedSampler from pretrain.dataset.helper import build_sampler from pretrain.dataset.base import BaseDataset from pretrain.utils.general import get_batch_size from pretrain.utils.distributed import get_world_size TASK_DATASET_REGISTRY = {} __all__ = ["BaseDataset"] def build_dataset(config, dataset_type, current_device): task_name = config.task dataset_name = config.dataset dataset_config_name = dataset_name + "_" + task_name dataset_config = config.dataset_config[dataset_config_name] if task_name not in TASK_DATASET_REGISTRY: raise ValueError("Task {} is not found.".format(task_name)) elif dataset_name not in TASK_DATASET_REGISTRY[task_name]: raise ValueError( "Dataset {} is not found in task {}.".format(dataset_name, task_name) ) if dataset_type not in dataset_config.imdb_files: warnings.warn( "Dataset type {} is not present in " "imdb_files of dataset config. Returning None. " "This dataset won't be used.".format(dataset_type) ) return None imdb_file = dataset_config["imdb_files"][dataset_type] dataset = TASK_DATASET_REGISTRY[task_name][dataset_name]( dataset_config, dataset_type, imdb_file, dataset_name=task_name, current_device=current_device, global_config=config, ) dataset.init_processors() return dataset def build_dataloader(config, dataset_type, dataset): training = config.training num_workers = training.num_workers pin_memory = training.pin_memory other_args = {} if dataset_type == "train": other_args["shuffle"] = True if get_world_size() > 1: other_args["sampler"] = build_sampler(config, dataset, other_args) other_args.pop("shuffle") else: other_args["shuffle"] = False if get_world_size() > 1: other_args["sampler"] = DistributedSampler(dataset, **other_args) other_args.pop("shuffle") if dataset_type == "train": other_args["batch_size"] = get_batch_size(training.batch_size) else: other_args["batch_size"] = 1 if dataset.iter_per_update > 1: other_args["drop_last"] = True loader = DataLoader( dataset=dataset, pin_memory=pin_memory, num_workers=num_workers, collate_fn=dataset.get_collate_fn(), **other_args ) if num_workers >= 0: # Suppress leaking semaphore warning os.environ["PYTHONWARNINGS"] = "ignore:semaphore_tracker:UserWarning" return loader, other_args.get("sampler", None) def register_task(task_name, dataset_name): def register_dataset_cls(cls): if ( task_name in TASK_DATASET_REGISTRY and dataset_name in TASK_DATASET_REGISTRY[task_name] ): raise ValueError( "Cannot register duplicate task ({}:{})".format(task_name, dataset_name) ) elif not issubclass(cls, BaseDataset): raise ValueError( "Dataset ({}) must extend BaseDataset".format(cls.__name__) ) if task_name in TASK_DATASET_REGISTRY: TASK_DATASET_REGISTRY[task_name][dataset_name] = cls else: TASK_DATASET_REGISTRY[task_name] = {dataset_name: cls} return cls return register_dataset_cls def get_task_list(): return tuple(TASK_DATASET_REGISTRY.keys()) datasets_dir = os.path.dirname(__file__) for file in os.listdir(datasets_dir): path = os.path.join(datasets_dir, file) if ( not file.startswith("_") and not file.startswith(".") and (file.endswith(".py") or os.path.isdir(path)) ): dataset_name = file[: file.find(".py")] if file.endswith(".py") else file importlib.import_module("pretrain.dataset." + dataset_name)
4,194
28.751773
88
py
null
r-mae-main/pretrain/dataset/base.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import os import copy import warnings import omegaconf import torch from torch.utils.data.dataset import Dataset from pretrain.dataset.processor import build_processor from pretrain.utils.general import get_cache_dir class BaseDataset(Dataset): def __init__(self, config, dataset_name, dataset_type="train", **kwargs): super().__init__() if config is None: config = {} self.config = config # self._iter_per_update = config.iter_per_update if dataset_type == "train" else 1 self._dataset_name = dataset_name self._dataset_type = dataset_type self._device = kwargs["current_device"] self._global_config = kwargs["global_config"] self._iter_per_update = self._global_config.training.iter_per_update def _get_absolute_path(self, paths): if os.environ.get("E2E_DATASETS") is None: warnings.warn("E2E_DATASETS environment not found! Setting to '.data' ...") os.environ["E2E_DATASETS"] = get_cache_dir(".data") if isinstance(paths, list): return [self._get_absolute_path(path) for path in paths] elif isinstance(paths, str): if not os.path.isabs(paths): paths = os.path.join(os.environ.get("E2E_DATASETS"), paths) return paths else: raise TypeError( "Paths passed to dataset should either be " "string or list" ) def init_processors(self): if not hasattr(self.config, "processors"): return for processor_key, processor_params in self.config.processors.items(): if not processor_params: continue if "answer" in processor_key: processor_params = copy.deepcopy(processor_params) with omegaconf.open_dict(processor_params): file_path = processor_params.params["class_file"] processor_params.params["class_file"] = self._get_absolute_path( file_path ) processor_object = build_processor(processor_params) setattr(self, processor_key, processor_object) def _prepare_batch(self, batch, non_blocking=False): sample, target = batch new_sample = {} new_target = [] for k, v in sample.items(): if isinstance(v, torch.Tensor): new_sample[k] = v.to(self._device, non_blocking=non_blocking) else: new_sample[k] = v for t in target: new_item = {} for k, v in t.items(): if isinstance(v, torch.Tensor): new_item[k] = v.to(self._device, non_blocking=non_blocking) else: new_item[k] = v new_target.append(new_item) return (new_sample, new_target) def prepare_batch(self, batch, non_blocking=False): """ Transfer cpu tensors in batch to gpu :batch: (sample, target) sample: dict of tensors target: list of dict """ if self._iter_per_update > 1: return [ self._prepare_batch(split, non_blocking=non_blocking) for split in batch ] else: return self._prepare_batch(batch, non_blocking=non_blocking) def __getitem__(self, index): raise NotImplementedError @property def dataset_type(self): return self._dataset_type @property def dataset_name(self): return self._dataset_name @property def iter_per_update(self): return self._iter_per_update @dataset_name.setter def dataset_name(self, name): self._dataset_name = name def get_collate_fn(self): raise NotImplementedError @torch.no_grad() def prepare_for_evaluation(self, predictions, *args, **kwargs): raise NotImplementedError @torch.no_grad() def format_for_evalai(self, output, *args, **kwargs): raise NotImplementedError
4,282
31.44697
90
py
null
r-mae-main/pretrain/dataset/pretrain.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. from functools import partial import torch from torch.utils.data import ConcatDataset from pretrain.dataset import BaseDataset, register_task from pretrain.dataset.helper import collate2d, ImageDataset, CocoMask class VisionPretrain(BaseDataset): def __init__(self, config, dataset_type, imdb_file, **kwargs): if "name" in kwargs: dataset_name = kwargs["name"] elif "dataset_name" in kwargs: dataset_name = kwargs["dataset_name"] else: dataset_name = "pretrain" super().__init__( config, dataset_name, dataset_type, current_device=kwargs["current_device"], global_config=kwargs["global_config"], ) def get_collate_fn(self): return partial(collate2d, iter_per_update=self.iter_per_update) def get_answer_size(self): return None class PretrainWithMask(VisionPretrain): def __init__(self, config, dataset_type, imdb_file, **kwargs): super().__init__(config, dataset_type, imdb_file, **kwargs) mask_type = config.get("mask_type", None) assert mask_type in ("fh", None) self.mask_type = mask_type self.cache_mode = config.get("sampler", "standard") == "shard" self.rmae_sampling = self._global_config.model == "rmae" if self.rmae_sampling: rmae_vit_arch = self._global_config.model_config["rmae"].mae_vit.arch if "base_patch16" in rmae_vit_arch: self.patch_size = 16 elif "large_patch16" in rmae_vit_arch: self.patch_size = 16 elif "huge_patch14" in rmae_vit_arch: self.patch_size = 14 rmae_vit_params = self._global_config.model_config["rmae"].mae_vit.params self.num_region = rmae_vit_params.num_region self.region_mask_ratio = rmae_vit_params.region_mask_ratio self.region_sample_type = rmae_vit_params.region_sample_type self.filter_small_patches = config.get("filter_small_patches", False) assert self.region_sample_type in ("random", "random_fg") def _process_mask(self, sample, target): masks = target.pop("masks") assert ( self.mask_type == "fh" ), f"FH masks should be used (mask_type={self.mask_type})" processed_masks = [] for mask in masks.unbind(0): mask = torch.unique(mask).unsqueeze(-1).unsqueeze(-1) == mask processed_masks.append(mask) masks = torch.cat(processed_masks, dim=0) if self.rmae_sampling: if self.filter_small_patches: assert masks.shape[1] == masks.shape[2] ph = pw = masks.shape[1] // self.patch_size b = masks.shape[0] patches = masks.view(b, ph, self.patch_size, pw, self.patch_size) patches = patches.any(-1).any(2).view(b, ph * pw) keep = patches.sum(dim=1, dtype=torch.int32) >= 2 masks = masks[keep] if self.region_sample_type == "random_fg": assert masks.shape[1] == masks.shape[2] h = w = masks.shape[1] // self.patch_size b = masks.shape[0] patches = masks.view(b, h, self.patch_size, w, self.patch_size) patches = patches.any(-1).any(2).view(b, h * w) len_keep = int((1 - self.region_mask_ratio) * h * w) shuffle_ids = torch.randperm(h * w) keep_ids = shuffle_ids[:len_keep] keep = patches[:, keep_ids].any(dim=1) masks = masks[keep] sample["shuffle_ids"] = shuffle_ids n, h, w = masks.shape if n == 0: masks = torch.zeros(self.num_region, h, w) elif n < self.num_region: repeat = (self.num_region + n - 1) // n ids = torch.tensor(list(range(n)) * repeat) ids = ids[torch.randperm(ids.shape[0])][: self.num_region] masks = masks[ids] else: ids = torch.randperm(n)[: self.num_region] masks = masks[ids] sample["region"] = masks.float() return sample, target @register_task("pretrain", "coco") class COCOPretrain(PretrainWithMask): def __init__(self, config, dataset_type, imdb_file, **kwargs): super().__init__(config, dataset_type, imdb_file, **kwargs) coco_dataset = [] for img_folder, mask_folder, anno_file in zip( imdb_file["image_folder"], imdb_file["mask_folder"], imdb_file["anno_file"], ): coco_dataset.append( CocoMask( self._get_absolute_path(img_folder), self._get_absolute_path(mask_folder), self._get_absolute_path(anno_file), cache_mode=self.cache_mode, mask_type=self.mask_type, ) ) self.coco_dataset = ConcatDataset(coco_dataset) def __len__(self): return len(self.coco_dataset) def __getitem__(self, idx): sample = {} if self.mask_type == "fh": img, masks = self.coco_dataset[idx] target = {"image_id": idx, "masks": masks} else: img, masks = self.coco_dataset[idx] target = {"image_id": idx} sample["image"] = img if self._dataset_type == "train": sample, target = self.image_train_processor(sample, target) else: sample, target = self.image_test_processor(sample, target) if self.mask_type is not None: sample, target = self._process_mask(sample, target) return sample, target @register_task("pretrain", "imnet") class ImageNetPretrain(PretrainWithMask): def __init__(self, config, dataset_type, imdb_file, **kwargs): super().__init__(config, dataset_type, imdb_file, **kwargs) mask_folder = self._get_absolute_path(imdb_file["mask_folder"]) self.imnet_dataset = ImageDataset( self._get_absolute_path(imdb_file["image_folder"]), root_mask=mask_folder, mask_type=self.mask_type, cache_mode=self.cache_mode, cache_mask=config.get("cache_mask", False), ) def __len__(self): return len(self.imnet_dataset) def __getitem__(self, idx): sample = {} if self.mask_type == "fh": img, masks = self.imnet_dataset[idx] target = {"image_id": idx, "masks": masks} else: img, masks = self.imnet_dataset[idx] target = {"image_id": idx} sample["image"] = img if self._dataset_type == "train": sample, target = self.image_train_processor(sample, target) else: sample, target = self.image_test_processor(sample, target) if self.mask_type is not None: sample, target = self._process_mask(sample, target) return sample, target
7,337
34.449275
85
py
null
r-mae-main/pretrain/dataset/helper/__init__.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. from pretrain.dataset.helper.image_dataset import ImageDataset from pretrain.dataset.helper.sampler import build_sampler from pretrain.dataset.helper.prefetcher import Prefetcher from pretrain.dataset.helper.coco import ( CocoDetection, CocoMask, ) from pretrain.dataset.helper.collate_fn import default_collate, collate2d __all__ = [ "ImageDataset", "CocoDetection", "CocoMask", "Prefetcher", "build_sampler", "collate2d", "default_collate", ]
680
26.24
73
py
null
r-mae-main/pretrain/dataset/helper/coco.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import os import math import json import random from io import BytesIO import torch import numpy as np from torchvision.datasets.vision import VisionDataset from PIL import Image from pretrain.utils.distributed import get_rank, get_world_size class CocoDataset(VisionDataset): def __init__( self, root, annFile, num_replicas=None, rank=None, transform=None, target_transform=None, transforms=None, cache_mode=False, cache_first=False, ): super(CocoDataset, self).__init__(root, transforms, transform, target_transform) from pycocotools.coco import COCO if num_replicas is None: num_replicas = get_world_size() if rank is None: rank = get_rank() self.coco_api = COCO(annFile) self.ids = list(sorted(self.coco_api.imgs.keys())) self.cache_mode = cache_mode self.rank = rank self.num_replicas = num_replicas self.num_samples = int(math.ceil(len(self.ids) * 1.0 / self.num_replicas)) self.total_size = self.num_samples * self.num_replicas if cache_mode: self.cache = {} if cache_first: self.cache_images() def cache_images(self): indices = torch.arange(len(self.ids)).tolist() indices += indices[: (self.total_size - len(indices))] assert len(indices) == self.total_size offset = self.num_samples * self.rank indices = set(indices[offset : offset + self.num_samples]) self.cache = {} for index, img_id in enumerate(self.ids): if index not in indices: continue path = self.coco_api.loadImgs(img_id)[0]["file_name"] with open(os.path.join(self.root, path), "rb") as f: self.cache[path] = f.read() def get_image(self, path): if self.cache_mode: if path not in self.cache: with open(os.path.join(self.root, path), "rb") as f: self.cache[path] = f.read() return Image.open(BytesIO(self.cache[path])).convert("RGB") return Image.open(os.path.join(self.root, path)).convert("RGB") def __getitem__(self, index): raise NotImplementedError def __len__(self): return len(self.ids) class CocoDetection(CocoDataset): def __init__( self, root, annFile, num_replicas=None, rank=None, transform=None, target_transform=None, transforms=None, cache_mode=False, cache_first=False, ): super(CocoDetection, self).__init__( root, annFile, num_replicas=num_replicas, rank=rank, transform=transform, target_transform=target_transform, transforms=transforms, cache_mode=cache_mode, cache_first=cache_first, ) def __getitem__(self, index): """ Args: index (int): Index Returns: tuple: Tuple (image, target). target is the object returned ``coco.loadAnns``, """ coco_api = self.coco_api img_id = self.ids[index] ann_ids = coco_api.getAnnIds(imgIds=img_id) target = coco_api.loadAnns(ann_ids) path = coco_api.loadImgs(img_id)[0]["file_name"] img = self.get_image(path) if self.transforms is not None: img, target = self.transforms(img, target) return img, target class CocoMask(CocoDataset): def __init__( self, root, maskFolder, annFile, num_replicas=None, rank=None, transform=None, target_transform=None, transforms=None, cache_mode=False, cache_first=False, mask_type=None, ): super(CocoMask, self).__init__( root, annFile, num_replicas=num_replicas, rank=rank, transform=transform, target_transform=target_transform, transforms=transforms, cache_mode=cache_mode, cache_first=cache_first, ) assert mask_type in ("fh", None) self.mask_type = mask_type self.maskFolder = maskFolder def __getitem__(self, index): """ Args: index (int): Index Returns: tuple: Tuple (image, masks). """ coco_api = self.coco_api img_id = self.ids[index] path = coco_api.loadImgs(img_id)[0]["file_name"] img = self.get_image(path) if self.mask_type == "fh": mask_path = path.replace("jpg", "npy") masks = np.load(os.path.join(self.maskFolder, mask_path)) masks = torch.from_numpy(masks) else: masks = None return img, masks class CocoCaption(CocoDataset): def __init__( self, root, annFile, num_replicas=None, rank=None, transform=None, target_transform=None, transforms=None, cache_mode=False, cache_first=False, ): super(CocoDetection, self).__init__( root, annFile, num_replicas=num_replicas, rank=rank, transform=transform, target_transform=target_transform, transforms=transforms, cache_mode=cache_mode, cache_first=cache_first, ) with open(annFile, "r") as f: self.coco = json.load(f) # sort 'images' field so that they are aligned with 'annotations' # i.e., in alphabetical order self.coco["images"] = sorted(self.coco["images"], key=lambda x: x["id"]) # sanity check if "annotations" in self.coco: for img, ann in zip(self.coco["images"], self.coco["annotations"]): assert img["file_name"][:-4] == ann["file_name"][:-4] assert tuple(map(lambda x: x["id"], self.coco["images"])) == tuple(self.ids) def __getitem__(self, index): ann_info = ( self.coco["annotations"][index] if "annotations" in self.coco else self.coco["images"][index] ) img_path = os.path.join(self.root, ann_info["file_name"]).replace( ".png", ".jpg" ) img = self.get_image(img_path) w, h = img.size target = {} target["image_id"] = torch.tensor( [ann_info["image_id"] if "image_id" in ann_info else ann_info["id"]] ) target["size"] = torch.as_tensor([int(h), int(w)]) target["orig_size"] = torch.as_tensor([int(h), int(w)]) if "captions" in ann_info: target["captions"] = ann_info["captions"] if self.transforms is not None: img, target = self.transforms(img, target) return img, target
7,198
27.681275
90
py
null
r-mae-main/pretrain/dataset/helper/collate_fn.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import collections import re import torch string_classes = str np_str_obj_array_pattern = re.compile(r"[SaUO]") default_collate_err_msg_format = ( "default_collate: batch must contain tensors, numpy arrays, numbers, " "dicts or lists; found {}" ) def default_collate(batch): r"""Puts each data field into a tensor with outer dimension batch size""" elem = batch[0] elem_type = type(elem) if isinstance(elem, torch.Tensor): out = None if torch.utils.data.get_worker_info() is not None: # If we're in a background process, concatenate directly into a # shared memory tensor to avoid an extra copy numel = sum([x.numel() for x in batch]) storage = elem.storage()._new_shared(numel) out = elem.new(storage) return torch.stack(batch, 0, out=out) elif ( elem_type.__module__ == "numpy" and elem_type.__name__ != "str_" and elem_type.__name__ != "string_" ): if elem_type.__name__ == "ndarray" or elem_type.__name__ == "memmap": # array of string classes and object if np_str_obj_array_pattern.search(elem.dtype.str) is not None: raise TypeError(default_collate_err_msg_format.format(elem.dtype)) return default_collate([torch.as_tensor(b) for b in batch]) elif elem.shape == (): # scalars return torch.as_tensor(batch) elif isinstance(elem, float): return torch.tensor(batch, dtype=torch.float64) elif isinstance(elem, int): return torch.tensor(batch) elif isinstance(elem, string_classes): return batch elif isinstance(elem, collections.abc.Mapping): return {key: default_collate([d[key] for d in batch]) for key in elem} elif isinstance(elem, tuple) and hasattr(elem, "_fields"): # namedtuple return elem_type(*(default_collate(samples) for samples in zip(*batch))) elif isinstance(elem, collections.abc.Sequence): # check to make sure that the elements in batch have consistent size it = iter(batch) elem_size = len(next(it)) if not all(len(elem) == elem_size for elem in it): raise RuntimeError("each element in list of batch should be of equal size") transposed = zip(*batch) return [default_collate(samples) for samples in transposed] raise TypeError(default_collate_err_msg_format.format(elem_type)) def _collate_sample2d(sample): assert sample[0]["image"].ndim == 3 image_size = sample[0].get("image_size", None) if isinstance(image_size, int): image_size = (image_size, image_size) if len(sample) == 1 and image_size is None: new_sample = {"image": sample[0]["image"][None], "mask": None} else: new_sample = {} if image_size is None: total_shape = (sample[i]["image"].shape for i in range(len(sample))) shape = (len(sample), *(max(elem) for elem in zip(*total_shape))) else: max_channels = max(sample[i]["image"].shape[0] for i in range(len(sample))) shape = (len(sample), max_channels, image_size[0], image_size[1]) new_sample["image"] = sample[0]["image"].new_zeros(shape) b, h, w = shape[0], shape[2], shape[3] new_sample["mask"] = sample[0]["image"].new_ones(b, h, w).bool() for i, elem in enumerate(sample): c, h, w = elem["image"].shape new_sample["image"][i, :c, :h, :w].copy_(elem["image"]) new_sample["mask"][i, :h, :w] = False for key in sample[0].keys(): if key in ("image", "image_size", "mask"): continue if isinstance(sample[0][key], torch.Tensor): new_sample[key] = torch.stack([elem[key] for elem in sample], dim=0) return new_sample def collate2d(batch, iter_per_update=1): batch = list(zip(*batch)) if iter_per_update == 1: new_batch = [_collate_sample2d(batch[0]), batch[1]] elif iter_per_update > 1: sample = batch[0] target = batch[1] batch_size = len(sample) split_size = (batch_size + iter_per_update - 1) // iter_per_update num_split = (batch_size + split_size - 1) // split_size new_batch = [ [ _collate_sample2d(sample[i * split_size : (i + 1) * split_size]), target[i * split_size : (i + 1) * split_size], ] for i in range(num_split) ] else: raise ValueError("iter_per_update should be greater than or equal to 1") return new_batch
4,819
35.240602
87
py
null
r-mae-main/pretrain/dataset/helper/constants.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. IMAGENET_DEFAULT_MEAN = (0.485, 0.456, 0.406) IMAGENET_DEFAULT_STD = (0.229, 0.224, 0.225)
289
31.222222
61
py
null
r-mae-main/pretrain/dataset/helper/image_dataset.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import os from io import BytesIO import torch import numpy as np import torchvision import cv2 from PIL import Image class ImageDataset(torchvision.datasets.ImageFolder): def __init__( self, root: str, root_mask=None, transform=None, target_transform=None, is_valid_file=None, cache_mode=False, mask_type=None, reader_type="pil", cache_mask=False, ): super().__init__( root, transform=transform, target_transform=target_transform, is_valid_file=is_valid_file, ) assert mask_type in ("fh", None) self.mask_type = mask_type self.root_mask = root_mask self.cache_mode = cache_mode self.cache_mask = cache_mask self.reader_type = reader_type if cache_mode: self.cache = {} if cache_mode or cache_mask: self.mask_cache = {} if root_mask is not None else None def _get_pil_image(self, path): if self.cache_mode: if path not in self.cache: with open(os.path.join(self.root, path), "rb") as f: self.cache[path] = f.read() return Image.open(BytesIO(self.cache[path])).convert("RGB") return Image.open(os.path.join(self.root, path)).convert("RGB") def _get_cv2_image(self, path): if self.cache_mode: if path not in self.cache: img = cv2.imread(path) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) self.cache[path] = img return Image.fromarray(self.cache[path]) img = cv2.imread(path) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) return Image.fromarray(img) def get_image(self, path): if self.reader_type == "pil": return self._get_pil_image(path) elif self.reader_type == "cv2": return self._get_cv2_image(path) else: raise ValueError("Only pil|cv2 supported!") def get_mask(self, path): if self.cache_mode or self.cache_mask: if path not in self.mask_cache: loads = np.load(os.path.join(self.root_mask, path)) self.mask_cache[path] = loads return self.mask_cache[path] return np.load(os.path.join(self.root_mask, path)) def __getitem__(self, idx): path = self.samples[idx][0] if self.mask_type == "fh": mask_path = path.replace(self.root, self.root_mask).replace("JPEG", "npy") masks = self.get_mask(mask_path) masks = torch.from_numpy(masks) else: masks = None sample = self.get_image(path) if self.transform is not None: sample = self.transform(sample) return sample, masks
3,059
27.867925
86
py
null
r-mae-main/pretrain/dataset/helper/prefetcher.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch class Prefetcher: def __init__(self, loader, dataset, prefetch=True): self.loader = iter(loader) self.prefetch = prefetch self.dataset = dataset if prefetch: self.stream = torch.cuda.Stream() self.preload() def preload(self): try: self.next_batch = next(self.loader) except StopIteration: self.next_batch = None return with torch.cuda.stream(self.stream): self.next_batch = self.dataset.prepare_batch( self.next_batch, non_blocking=True ) def _record_batch(self, batch): samples, targets = batch if samples is not None: for k, v in samples.items(): if isinstance(v, torch.Tensor): v.record_stream(torch.cuda.current_stream()) if targets is not None: for t in targets: for k, v in t.items(): if isinstance(v, torch.Tensor): v.record_stream(torch.cuda.current_stream()) def get_next_sample(self): if self.prefetch: torch.cuda.current_stream().wait_stream(self.stream) batch = self.next_batch if self.dataset.iter_per_update > 1: for split in batch: self._record_batch(split) else: self._record_batch(batch) self.preload() else: try: batch = next(self.loader) batch = self.dataset.prepare_batch(batch) except StopIteration: batch = None return batch
1,890
29.5
68
py
null
r-mae-main/pretrain/dataset/helper/sampler.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import math import itertools from collections import defaultdict from typing import TypeVar, Optional, Iterator import torch import torch.distributed as dist from torch.utils.data.sampler import Sampler from torch.utils.data import Dataset from pretrain.utils.distributed import shared_random_seed T_co = TypeVar("T_co", covariant=True) SAMPLER_REGISTRY = {} def register_sampler(name): def register_sampler_cls(cls): if name in SAMPLER_REGISTRY: raise ValueError("Cannot register duplicate sampler ({})".format(name)) SAMPLER_REGISTRY[name] = cls return cls return register_sampler_cls def build_sampler(config, dataset, other_args): training = config.training task_name = config.task dataset_name = config.dataset dataset_config_name = dataset_name + "_" + task_name dataset_config = config.dataset_config[dataset_config_name] sampler_type = dataset_config.get("sampler", "standard") if sampler_type == "standard": sampler = DistributedSampler(dataset, shuffle=other_args["shuffle"]) elif sampler_type == "shard": sampler = ShardDistribtedSampler(dataset, shuffle=other_args["shuffle"]) elif sampler_type == "infinite": batch_size = training.batch_size max_update = training.max_update max_epoch = training.max_epoch if max_epoch is not None: total_size = max_epoch * len(dataset) else: total_size = max_update * batch_size sampler = InfiniteDistributedSampler( dataset, total_size, shuffle=other_args["shuffle"] ) elif sampler_type == "repeat_factor": batch_size = training.batch_size max_update = training.max_update max_epoch = training.max_epoch if max_epoch is not None: total_size = max_epoch * len(dataset) else: total_size = max_update * batch_size repeat_factors = ( RepeatFactorDistributedSampler.repeat_factors_from_category_frequency( dataset.data.dataset_dicts, 0.001, ) ) sampler = RepeatFactorDistributedSampler( repeat_factors, dataset, total_size, shuffle=other_args["shuffle"] ) return sampler class DistributedSampler(Sampler[T_co]): def __init__( self, dataset: Dataset, num_replicas: Optional[int] = None, rank: Optional[int] = None, shuffle: bool = True, seed: int = 0, drop_last: bool = False, ) -> None: if num_replicas is None: if not dist.is_available(): raise RuntimeError("Requires distributed package to be available") num_replicas = dist.get_world_size() if rank is None: if not dist.is_available(): raise RuntimeError("Requires distributed package to be available") rank = dist.get_rank() if rank >= num_replicas or rank < 0: raise ValueError( "Invalid rank {}, rank should be in the interval" " [0, {}]".format(rank, num_replicas - 1) ) self.dataset = dataset self.num_replicas = num_replicas self.rank = rank self.epoch = 0 self.drop_last = drop_last # If the dataset length is evenly divisible by # of replicas, then there # is no need to drop any data, since the dataset will be split equally. if self.drop_last and len(self.dataset) % self.num_replicas != 0: # type: ignore[arg-type] # Split to nearest available length that is evenly divisible. # This is to ensure each rank receives the same amount of data when # using this Sampler. self.num_samples = math.ceil( (len(self.dataset) - self.num_replicas) / self.num_replicas # type: ignore[arg-type] ) else: self.num_samples = math.ceil(len(self.dataset) / self.num_replicas) # type: ignore[arg-type] self.total_size = self.num_samples * self.num_replicas self.shuffle = shuffle self.seed = seed def __iter__(self) -> Iterator[T_co]: if self.shuffle: # deterministically shuffle based on epoch and seed g = torch.Generator() g.manual_seed(self.seed + self.epoch) indices = torch.randperm(len(self.dataset), generator=g).tolist() # type: ignore[arg-type] else: indices = list(range(len(self.dataset))) # type: ignore[arg-type] if not self.drop_last: # add extra samples to make it evenly divisible padding_size = self.total_size - len(indices) if padding_size <= len(indices): indices += indices[:padding_size] else: indices += (indices * math.ceil(padding_size / len(indices)))[ :padding_size ] else: # remove tail of data to make it evenly divisible. indices = indices[: self.total_size] assert len(indices) == self.total_size # subsample indices = indices[self.rank : self.total_size : self.num_replicas] assert len(indices) == self.num_samples return iter(indices) def __len__(self) -> int: return self.num_samples def set_epoch(self, epoch: int) -> None: r""" Sets the epoch for this sampler. When :attr:`shuffle=True`, this ensures all replicas use a different random ordering for each epoch. Otherwise, the next iteration of this sampler will yield the same ordering. Args: epoch (int): Epoch number. """ self.epoch = epoch class RepeatFactorDistributedSampler(Sampler[T_co]): def __init__( self, repeat_factors: torch.Tensor, dataset: Dataset, total_size: int, num_replicas: Optional[int] = None, rank: Optional[int] = None, shuffle: bool = True, seed: Optional[int] = None, ): if num_replicas is None: if not dist.is_available(): raise RuntimeError("Requires distributed package to be available") num_replicas = dist.get_world_size() if rank is None: if not dist.is_available(): raise RuntimeError("Requires distributed package to be available") rank = dist.get_rank() if rank >= num_replicas or rank < 0: raise ValueError( "Invalid rank {}, rank should be in the interval" " [0, {}]".format(rank, num_replicas - 1) ) self.dataset = dataset self.num_replicas = num_replicas self.total_size = total_size self.rank = rank self.shuffle = shuffle self.num_samples = math.ceil(total_size / self.num_replicas) if seed is None: seed = shared_random_seed() self.seed = int(seed) self.int_part = torch.trunc(repeat_factors) self.frac_part = repeat_factors - self.int_part @staticmethod def repeat_factors_from_category_frequency(dataset_dicts, repeat_thresh): # 1. For each category c, compute the fraction of images that contain it: f(c) category_freq = defaultdict(int) for dataset_dict in dataset_dicts: # For each image (without repeats) cat_ids = {ann["category_id"] for ann in dataset_dict["annotations"]} for cat_id in cat_ids: category_freq[cat_id] += 1 num_images = len(dataset_dicts) for k, v in category_freq.items(): category_freq[k] = v / num_images # 2. For each category c, compute the category-level repeat factor: # r(c) = max(1, sqrt(t / f(c))) category_rep = { cat_id: max(1.0, math.sqrt(repeat_thresh / cat_freq)) for cat_id, cat_freq in category_freq.items() } # 3. For each image I, compute the image-level repeat factor: # r(I) = max_{c in I} r(c) rep_factors = [] for dataset_dict in dataset_dicts: cat_ids = {ann["category_id"] for ann in dataset_dict["annotations"]} rep_factor = max({category_rep[cat_id] for cat_id in cat_ids}, default=1.0) rep_factors.append(rep_factor) return torch.tensor(rep_factors, dtype=torch.float32) def __len__(self) -> int: return self.num_samples def __iter__(self): start = self.rank yield from itertools.islice( self._infinite_indices(), start, None, self.num_replicas ) def set_epoch(self, epoch): self.epoch = epoch def _get_epoch_indices(self, generator): """ Create a list of dataset indices (with repeats) to use for one epoch. Args: generator (torch.Generator): pseudo random number generator used for stochastic rounding. Returns: torch.Tensor: list of dataset indices to use in one epoch. Each index is repeated based on its calculated repeat factor. """ # Since repeat factors are fractional, we use stochastic rounding so # that the target repeat factor is achieved in expectation over the # course of training rands = torch.rand(len(self.frac_part), generator=generator) rep_factors = self.int_part + (rands < self.frac_part).float() # Construct a list of indices in which we repeat images as specified indices = [] for dataset_index, rep_factor in enumerate(rep_factors): indices.extend([dataset_index] * int(rep_factor.item())) return torch.tensor(indices, dtype=torch.int64) def _infinite_indices(self): g = torch.Generator() g.manual_seed(self.seed) while True: # Sample indices with repeats determined by stochastic rounding; each # "epoch" may have a slightly different size due to the rounding. indices = self._get_epoch_indices(g) if self.shuffle: randperm = torch.randperm(len(indices), generator=g) yield from indices[randperm].tolist() else: yield from indices.tolist() class InfiniteDistributedSampler(Sampler[T_co]): def __init__( self, dataset: Dataset, total_size: int, num_replicas: Optional[int] = None, rank: Optional[int] = None, shuffle: bool = True, seed: Optional[int] = None, ) -> None: if num_replicas is None: if not dist.is_available(): raise RuntimeError("Requires distributed package to be available") num_replicas = dist.get_world_size() if rank is None: if not dist.is_available(): raise RuntimeError("Requires distributed package to be available") rank = dist.get_rank() if rank >= num_replicas or rank < 0: raise ValueError( "Invalid rank {}, rank should be in the interval" " [0, {}]".format(rank, num_replicas - 1) ) self.dataset = dataset self.num_replicas = num_replicas self.total_size = total_size self.rank = rank self.shuffle = shuffle self.num_samples = math.ceil(self.total_size / self.num_replicas) if seed is None: seed = shared_random_seed() self.seed = int(seed) def __len__(self) -> int: return self.num_samples def __iter__(self) -> Iterator[T_co]: start = self.rank yield from itertools.islice( self._infinite_indices(), start, None, self.num_replicas ) def set_epoch(self, epoch): self.epoch = epoch def _infinite_indices(self): g = torch.Generator() g.manual_seed(self.seed) while True: if self.shuffle: yield from torch.randperm(len(self.dataset), generator=g).tolist() else: yield from torch.arange(len(self.dataset)).tolist() class ShardDistribtedSampler(Sampler[T_co]): def __init__( self, dataset: Dataset, num_replicas: Optional[int] = None, rank: Optional[int] = None, shuffle: bool = True, seed: int = 0, drop_last: bool = False, ) -> None: if num_replicas is None: if not dist.is_available(): raise RuntimeError("Requires distributed package to be available") num_replicas = dist.get_world_size() if rank is None: if not dist.is_available(): raise RuntimeError("Requires distributed package to be available") rank = dist.get_rank() if rank >= num_replicas or rank < 0: raise ValueError( "Invalid rank {}, rank should be in the interval" " [0, {}]".format(rank, num_replicas - 1) ) self.dataset = dataset self.num_replicas = num_replicas self.rank = rank self.epoch = 0 self.drop_last = drop_last # If the dataset length is evenly divisible by # of replicas, then there # is no need to drop any data, since the dataset will be split equally. if self.drop_last and len(self.dataset) % self.num_replicas != 0: # type: ignore[arg-type] # Split to nearest available length that is evenly divisible. # This is to ensure each rank receives the same amount of data when # using this Sampler. self.num_samples = math.ceil( (len(self.dataset) - self.num_replicas) / self.num_replicas # type: ignore[arg-type] ) else: self.num_samples = math.ceil(len(self.dataset) / self.num_replicas) # type: ignore[arg-type] self.total_size = self.num_samples * self.num_replicas self.shuffle = shuffle self.seed = seed def __iter__(self): indices = torch.arange(len(self.dataset)).tolist() # indices += indices[: (self.total_size - len(indices))] # assert len(indices) == self.total_size indices = indices[self.rank : self.total_size : self.num_replicas] if self.shuffle: g = torch.Generator() g.manual_seed(self.epoch) shuffled_idx = torch.randperm(len(indices), generator=g) indices = torch.tensor(indices)[shuffled_idx].tolist() if len(indices) < self.num_samples: indices += [indices[0]] if len(indices) > self.num_samples: indices = indices[:-1] assert len(indices) == self.num_samples return iter(indices) def __len__(self): return self.num_samples def set_epoch(self, epoch): self.epoch = epoch
15,162
35.803398
105
py
null
r-mae-main/pretrain/dataset/processor/__init__.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. from pretrain.dataset.processor.processors import build_processor __all__ = ["build_processor"]
295
28.6
65
py
null
r-mae-main/pretrain/dataset/processor/functional.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import collections import math import random import torch import torchvision.transforms.functional as F import numpy as np from torchvision.transforms.functional import _interpolation_modes_from_int from pretrain.utils.box_ops import box_xyxy_to_cxcywh from pretrain.utils.general import interpolate # =========================== # # --------- 2d ops ---------- # # =========================== # def random_resize_crop_with_loop(sample, target, scale, ratio, size, interpolation): def _get_crop(image_size, scale, ratio): width, height = image_size area = width * height for attempt in range(10): target_area = random.uniform(*scale) * area log_ratio = (math.log(ratio[0]), math.log(ratio[1])) aspect_ratio = math.exp(random.uniform(*log_ratio)) w = int(round(math.sqrt(target_area * aspect_ratio))) h = int(round(math.sqrt(target_area / aspect_ratio))) if w <= width and h <= height: i = random.randint(0, height - h) j = random.randint(0, width - w) return i, j, h, w # Fallback to central crop in_ratio = width / height if in_ratio < min(ratio): w = width h = int(round(w / min(ratio))) elif in_ratio > max(ratio): h = height w = int(round(h * max(ratio))) else: # whole image w = width h = height i = (height - h) // 2 j = (width - w) // 2 return (i, j, h, w) i, j, h, w = _get_crop(sample["image"].size, scale, ratio) sample, target = crop(sample, target, (i, j, h, w)) assert isinstance(size, collections.abc.Sequence) sample, target = resize(sample, target, size, interpolation=interpolation) return sample, target def random_resize_crop(sample, target, scale, ratio, size, interpolation): def _get_crop(image_size, scale, ratio): width, height = image_size area = height * width target_area = area * torch.empty(1).uniform_(scale[0], scale[1]).item() log_ratio = torch.log(torch.tensor(ratio)) aspect_ratio = torch.exp( torch.empty(1).uniform_(log_ratio[0], log_ratio[1]) ).item() w = int(round(math.sqrt(target_area * aspect_ratio))) h = int(round(math.sqrt(target_area / aspect_ratio))) w = min(w, width) h = min(h, height) i = torch.randint(0, height - h + 1, size=(1,)).item() j = torch.randint(0, width - w + 1, size=(1,)).item() return (i, j, h, w) i, j, h, w = _get_crop(sample["image"].size, scale, ratio) sample, target = crop(sample, target, (i, j, h, w)) assert isinstance(size, collections.abc.Sequence) sample, target = resize(sample, target, size, interpolation=interpolation) return sample, target def center_crop(sample, target, size): def _get_crop(image_size, size): h, w = size width, height = image_size if h > height: h = height if w > width: w = width i = (height - h) // 2 j = (width - w) // 2 return (i, j, h, w) i, j, h, w = _get_crop(sample["image"].size, size) sample, target = crop(sample, target, (i, j, h, w)) return sample, target def resize_scale(sample, target, scale, target_height, target_width, interpolation=2): def _get_resize(image_size, scale): w, h = image_size input_size = torch.tensor([h, w]) # Compute new target size given a scale target_size = torch.tensor([target_height, target_width]) target_scale_size = target_size * scale # Compute actual rescaling applied to input image and output size output_scale = torch.minimum( target_scale_size[0] / input_size[0], target_scale_size[1] / input_size[1] ) output_size = torch.round(input_size * output_scale).int() oh, ow = output_size.tolist() return (ow, oh) size = _get_resize(sample["image"].size, scale) return resize(sample, target, size, interpolation=interpolation) def random_crop(sample, target, crop_size, is_fixed=True, pad_value=128): def _get_crop(image_size, crop_size, is_fixed): w, h = image_size ow, oh = crop_size # Add random crop if the image is scaled up max_offset = torch.tensor([h, w]) - torch.tensor([oh, ow]) max_offset = torch.clamp(max_offset, min=0) offset = max_offset * np.random.uniform(0.0, 1.0) offset = torch.round(offset).int().tolist() if is_fixed: return (offset[0], offset[1], oh, ow) return (offset[0], offset[1], min(oh, h), min(ow, w)) size = _get_crop(sample["image"].size, crop_size, is_fixed) if is_fixed: w, h = sample["image"].size ow, oh = crop_size pad_size = torch.tensor([oh, ow]) - torch.tensor([h, w]) pad_size = torch.clamp(pad_size, min=0).tolist() sample, target = pad( sample, target, (pad_size[1], pad_size[0]), pad_value=pad_value ) return crop(sample, target, size) def crop(sample, target, region): """ Crop region in the image. For 3D annotations, it considers their 2D projection on image. """ cropped_image = F.crop(sample["image"], *region) if target is None: sample["image"] = cropped_image return sample, None i, j, h, w = region target = target.copy() target["size"] = torch.tensor([h, w]) fields = ["labels", "area", "iscrowd", "keypoints"] if "boxes" in target: boxes = target["boxes"] # x1, y1, x2, y2 max_size = torch.tensor([w, h], dtype=torch.float32) cropped_boxes = boxes - torch.tensor([j, i, j, i]) cropped_boxes = torch.min(cropped_boxes.reshape(-1, 2, 2), max_size) cropped_boxes = cropped_boxes.clamp(min=0) area = (cropped_boxes[:, 1] - cropped_boxes[:, 0]).prod(dim=1) target["boxes"] = cropped_boxes.view(-1, 4) target["area"] = area fields.append("boxes") if "masks" in target: target["masks"] = target["masks"][:, i : i + h, j : j + w] fields.append("masks") if "keypoints" in target: target["keypoints"][..., 0] -= j target["keypoints"][..., 1] -= i keypoints_xy = target["keypoints"][..., :2] # Set all out-of-boundary points to "unlabeled" inside = (keypoints_xy >= torch.tensor([0, 0])) & ( keypoints_xy <= torch.tensor([w, h]) ) inside = inside.all(dim=-1) target["keypoints"][..., :2] = keypoints_xy target["keypoints"][..., 2][~inside] = 0 # remove elements for which the boxes or masks that have zero area if "boxes" in target or ( "masks" in target and isinstance(target["masks"], torch.BoolTensor) ): # favor boxes selection when defining which elements to keep # this is compatible with previous implementation if "boxes" in target: cropped_boxes = target["boxes"].view(-1, 2, 2) keep = torch.all(cropped_boxes[:, 1] > cropped_boxes[:, 0], dim=1) if "masks" in target and isinstance(target["masks"], torch.BoolTensor): keep = target["masks"].flatten(1).any(1) for field in fields: if field in target: target[field] = target[field][keep] sample["image"] = cropped_image return sample, target def hflip(sample, target): flipped_image = F.hflip(sample["image"]) if target is None: sample["image"] = flipped_image return sample, None w, h = sample["image"].size target = target.copy() if "boxes" in target: boxes = target["boxes"] boxes = boxes[:, [2, 1, 0, 3]] * torch.tensor([-1, 1, -1, 1]) + torch.tensor( [w, 0, w, 0] ) target["boxes"] = boxes if "masks" in target: target["masks"] = target["masks"].flip(-1) if "keypoints" in target: target["keypoints"][..., 0] = w - target["keypoints"][..., 0] keypoints = target["keypoints"] keypoint_hflip_indices = target["keypoint_hflip_indices"] assert keypoints.shape[1] == len(keypoint_hflip_indices) keypoints = keypoints[ :, torch.tensor(keypoint_hflip_indices, dtype=torch.long), : ] target["keypoints"] = keypoints sample["image"] = flipped_image return sample, target def pad(sample, target, padding, pad_value=128): # assumes that we only pad on the bottom right corners padded_image = F.pad( sample["image"], (0, 0, padding[0], padding[1]), fill=pad_value ) if target is None: sample["image"] = padded_image return sample, None target = target.copy() target["size"] = torch.tensor(padded_image.size[::-1]) if "masks" in target: target["masks"] = torch.nn.functional.pad( target["masks"], (0, padding[0], 0, padding[1]) ) sample["image"] = padded_image return sample, target def resize(sample, target, size, max_size=None, interpolation=2): # size can be min_size (scalar) or (w, h) tuple def _get_size_with_aspect_ratio(image_size, size, max_size=None): w, h = image_size if max_size is not None: min_orig_size = float(min((w, h))) max_orig_size = float(max((w, h))) if max_orig_size / min_orig_size * size > max_size: size = int(math.floor(max_size * min_orig_size / max_orig_size)) if (w <= h and w == size) or (h <= w and h == size): return (h, w) if w < h: ow = size oh = int(size * h / w) else: oh = size ow = int(size * w / h) return (oh, ow) def _get_size(image_size, size, max_size=None): if isinstance(size, collections.abc.Sequence): return size[::-1] else: return _get_size_with_aspect_ratio(image_size, size, max_size) if isinstance(interpolation, int): interpolation = _interpolation_modes_from_int(interpolation) size = _get_size(sample["image"].size, size, max_size) rescaled_image = F.resize(sample["image"], size, interpolation=interpolation) if target is None: sample["image"] = rescaled_image return sample, None ratios = tuple( float(s) / float(s_orig) for s, s_orig in zip(rescaled_image.size, sample["image"].size) ) ratio_width, ratio_height = ratios target = target.copy() if "boxes" in target: boxes = target["boxes"] scaled_boxes = boxes * torch.as_tensor( [ratio_width, ratio_height, ratio_width, ratio_height] ) target["boxes"] = scaled_boxes if "area" in target: area = target["area"] scaled_area = area * (ratio_width * ratio_height) target["area"] = scaled_area h, w = size target["size"] = torch.tensor([h, w]) if "masks" in target: if isinstance(target["masks"], torch.ByteTensor): target["masks"] = interpolate( target["masks"][:, None], size, mode="nearest" )[:, 0] else: target["masks"] = interpolate( target["masks"][:, None].float(), size, mode="nearest" )[:, 0].to(target["masks"]) if "keypoints" in target: target["keypoints"][..., 0] = target["keypoints"][..., 0] * ratio_width target["keypoints"][..., 1] = target["keypoints"][..., 1] * ratio_height sample["image"] = rescaled_image return sample, target def to_tensor(sample, target): sample["image"] = F.to_tensor(sample["image"]) return sample, target def normalize(sample, target, mean, std): sample["image"] = F.normalize(sample["image"], mean=mean, std=std) if target is None: return sample, None target = target.copy() h, w = sample["image"].shape[-2:] if h == 0 or w == 0: raise RuntimeError("Image have 0 dimension!") if "boxes" in target: boxes = target["boxes"] target["orig_boxes"] = boxes boxes = box_xyxy_to_cxcywh(boxes) boxes = boxes / torch.tensor([w, h, w, h], dtype=torch.float32) target["boxes"] = boxes return sample, target
12,623
29.941176
92
py