// PETSc includes #include // C++ includes #include #include #include #include #include #include int main (int argc, char** argv) { PetscErrorCode ierr; PetscMPIInt size, rank; PetscInt m,n; ierr = PetscInitialize(&argc,&argv,(char*) 0,"Test matrix assembly"); ierr = MPI_Comm_size(PETSC_COMM_WORLD,&size);CHKERRQ(ierr); ierr = MPI_Comm_rank(PETSC_COMM_WORLD,&rank);CHKERRQ(ierr); if (size > 2) SETERRQ(PETSC_COMM_WORLD,PETSC_ERR_SUP,"This example is for <=2 procs"); const unsigned int n_dofs = 26559; unsigned int first_local_index; unsigned int last_local_index; if ( size == 1 ) { first_local_index = 0; last_local_index = 26559; } else if ( size == 2 ) { if ( rank == 0 ) { first_local_index = 0; last_local_index = 13911; } else { first_local_index = 13911; last_local_index = 26559; } } else { std::cout << "Not implemented for np>2"; return 1; } // Read element dof indices from files std::vector>> elem_dof_indices(size); for ( unsigned int proc_id = 0; proc_id < size; ++proc_id ) { const std::string dof_fname = "dof_indices_np_" + std::to_string(size) + "_proc_" + std::to_string(proc_id) + ".txt"; std::string line; std::ifstream dof_file(dof_fname); if (dof_file.good()) { while ( std::getline (dof_file,line) ) { std::vector dof_indices; std::stringstream sstream(line); std::string token; while (std::getline(sstream, token, ' ')) { dof_indices.push_back(std::stoi(token)); } elem_dof_indices[proc_id].push_back(dof_indices); } } else { std::cout << "Could not open file"; return 1; } } // Debugging: Verify we read in elem_dof_indices correctly // for (unsigned int i=0; i > sparsity(n_dofs); for (unsigned int proc_id = 0; proc_id < size; ++proc_id) for (auto & dof_indices : elem_dof_indices[proc_id]) for (unsigned int i = 0; i < dof_indices.size(); ++i) for (unsigned int j = 0; j < dof_indices.size(); ++j) sparsity[dof_indices[i]].insert(dof_indices[j]); // Determine the local nonzeros on this processor const unsigned int n_local_dofs = last_local_index - first_local_index; std::vector n_nz(n_local_dofs); std::vector n_oz(n_local_dofs); for ( unsigned int i = 0; i < n_local_dofs; ++i ) for ( auto dof : sparsity[i+first_local_index] ) { if ((dof >= first_local_index) && (dof < last_local_index)) n_nz[i]++; else n_oz[i]++; } // Debugging: print number of on/off diagonal nonzeros // for (unsigned int i=0; i zero_mat( dof_indices.size(), dof_indices.size() ); // B.add_matrix( zero_mat, dof_indices ); std::vector ones(dof_indices.size() * dof_indices.size(), 1.); ierr = MatSetValues (mat, dof_indices.size(), dof_indices.data(), dof_indices.size(), dof_indices.data(), ones.data(), ADD_VALUES);CHKERRQ(ierr); } // Matrix assembly ierr = MatAssemblyBegin(mat, MAT_FINAL_ASSEMBLY);CHKERRQ(ierr); ierr = MatAssemblyEnd(mat, MAT_FINAL_ASSEMBLY);CHKERRQ(ierr); // Clean up ierr = MatDestroy(&mat);CHKERRQ(ierr); ierr = PetscFinalize(); return ierr; }