2012-05-30 8 views
5

Tôi bắt đầu sử dụng thư viện PETSc để giải quyết hệ phương trình tuyến tính của phương trình song song. Tôi đã cài đặt tất cả các gói, xây dựng và chạy thành công các ví dụ trong thư mục petsc/src/ksp/ksp/ví dụ/hướng dẫn/thư mục, ví dụ: ex.cPETSc giải quyết hệ thống tuyến tính với hướng dẫn ksp

Nhưng tôi không thể hiểu cách điền các ma trận A, X an B bằng cách đọc chúng ví dụ từ tập tin.

Ở đây tôi cung cấp mã trong tập tin ex2.c:

/* Program usage: mpiexec -n <procs> ex2 [-help] [all PETSc options] */ 

static char help[] = "Solves a linear system in parallel with KSP.\n\ 
Input parameters include:\n\ 
    -random_exact_sol : use a random exact solution vector\n\ 
    -view_exact_sol : write exact solution vector to stdout\n\ 
    -m <mesh_x>  : number of mesh points in x-direction\n\ 
    -n <mesh_n>  : number of mesh points in y-direction\n\n"; 

/*T 
    Concepts: KSP^basic parallel example; 
    Concepts: KSP^Laplacian, 2d 
    Concepts: Laplacian, 2d 
    Processors: n 
T*/ 

/* 
    Include "petscksp.h" so that we can use KSP solvers. Note that this file 
    automatically includes: 
    petscsys.h  - base PETSc routines petscvec.h - vectors 
    petscmat.h - matrices 
    petscis.h  - index sets   petscksp.h - Krylov subspace methods 
    petscviewer.h - viewers    petscpc.h - preconditioners 
*/ 
#include <C:\PETSC\include\petscksp.h> 

#undef __FUNCT__ 
#define __FUNCT__ "main" 
int main(int argc,char **args) 
{ 
    Vec   x,b,u; /* approx solution, RHS, exact solution */ 
    Mat   A;  /* linear system matrix */ 
    KSP   ksp;  /* linear solver context */ 
    PetscRandom rctx;  /* random number generator context */ 
    PetscReal  norm;  /* norm of solution error */ 
    PetscInt  i,j,Ii,J,Istart,Iend,m = 8,n = 7,its; 
    PetscErrorCode ierr; 
    PetscBool  flg = PETSC_FALSE; 
    PetscScalar v; 
#if defined(PETSC_USE_LOG) 
    PetscLogStage stage; 
#endif 

    PetscInitialize(&argc,&args,(char *)0,help); 
    ierr = PetscOptionsGetInt(PETSC_NULL,"-m",&m,PETSC_NULL);CHKERRQ(ierr); 
    ierr = PetscOptionsGetInt(PETSC_NULL,"-n",&n,PETSC_NULL);CHKERRQ(ierr); 
    /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
     Compute the matrix and right-hand-side vector that define 
     the linear system, Ax = b. 
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ 
    /* 
    Create parallel matrix, specifying only its global dimensions. 
    When using MatCreate(), the matrix format can be specified at 
    runtime. Also, the parallel partitioning of the matrix is 
    determined by PETSc at runtime. 

    Performance tuning note: For problems of substantial size, 
    preallocation of matrix memory is crucial for attaining good 
    performance. See the matrix chapter of the users manual for details. 
    */ 
    ierr = MatCreate(PETSC_COMM_WORLD,&A);CHKERRQ(ierr); 
    ierr = MatSetSizes(A,PETSC_DECIDE,PETSC_DECIDE,m*n,m*n);CHKERRQ(ierr); 
    ierr = MatSetFromOptions(A);CHKERRQ(ierr); 
    ierr = MatMPIAIJSetPreallocation(A,5,PETSC_NULL,5,PETSC_NULL);CHKERRQ(ierr); 
    ierr = MatSeqAIJSetPreallocation(A,5,PETSC_NULL);CHKERRQ(ierr); 

    /* 
    Currently, all PETSc parallel matrix formats are partitioned by 
    contiguous chunks of rows across the processors. Determine which 
    rows of the matrix are locally owned. 
    */ 
    ierr = MatGetOwnershipRange(A,&Istart,&Iend);CHKERRQ(ierr); 

    /* 
    Set matrix elements for the 2-D, five-point stencil in parallel. 
     - Each processor needs to insert only elements that it owns 
     locally (but any non-local elements will be sent to the 
     appropriate processor during matrix assembly). 
     - Always specify global rows and columns of matrix entries. 

    Note: this uses the less common natural ordering that orders first 
    all the unknowns for x = h then for x = 2h etc; Hence you see J = Ii +- n 
    instead of J = I +- m as you might expect. The more standard ordering 
    would first do all variables for y = h, then y = 2h etc. 

    */ 
    ierr = PetscLogStageRegister("Assembly", &stage);CHKERRQ(ierr); 
    ierr = PetscLogStagePush(stage);CHKERRQ(ierr); 
    for (Ii=Istart; Ii<Iend; Ii++) { 
    v = -1.0; i = Ii/n; j = Ii - i*n; 
    if (i>0) {J = Ii - n; ierr = MatSetValues(A,1,&Ii,1,&J,&v,INSERT_VALUES);CHKERRQ(ierr);} 
    if (i<m-1) {J = Ii + n; ierr = MatSetValues(A,1,&Ii,1,&J,&v,INSERT_VALUES);CHKERRQ(ierr);} 
    if (j>0) {J = Ii - 1; ierr = MatSetValues(A,1,&Ii,1,&J,&v,INSERT_VALUES);CHKERRQ(ierr);} 
    if (j<n-1) {J = Ii + 1; ierr = MatSetValues(A,1,&Ii,1,&J,&v,INSERT_VALUES);CHKERRQ(ierr);} 
    v = 4.0; ierr = MatSetValues(A,1,&Ii,1,&Ii,&v,INSERT_VALUES);CHKERRQ(ierr); 
    } 

    /* 
    Assemble matrix, using the 2-step process: 
     MatAssemblyBegin(), MatAssemblyEnd() 
    Computations can be done while messages are in transition 
    by placing code between these two statements. 
    */ 
    ierr = MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr); 
    ierr = MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr); 
    ierr = PetscLogStagePop();CHKERRQ(ierr); 

    /* A is symmetric. Set symmetric flag to enable ICC/Cholesky preconditioner */ 
    ierr = MatSetOption(A,MAT_SYMMETRIC,PETSC_TRUE);CHKERRQ(ierr); 

    /* 
    Create parallel vectors. 
     - We form 1 vector from scratch and then duplicate as needed. 
     - When using VecCreate(), VecSetSizes and VecSetFromOptions() 
     in this example, we specify only the 
     vector's global dimension; the parallel partitioning is determined 
     at runtime. 
     - When solving a linear system, the vectors and matrices MUST 
     be partitioned accordingly. PETSc automatically generates 
     appropriately partitioned matrices and vectors when MatCreate() 
     and VecCreate() are used with the same communicator. 
     - The user can alternatively specify the local vector and matrix 
     dimensions when more sophisticated partitioning is needed 
     (replacing the PETSC_DECIDE argument in the VecSetSizes() statement 
     below). 
    */ 
    ierr = VecCreate(PETSC_COMM_WORLD,&u);CHKERRQ(ierr); 
    ierr = VecSetSizes(u,PETSC_DECIDE,m*n);CHKERRQ(ierr); 
    ierr = VecSetFromOptions(u);CHKERRQ(ierr); 
    ierr = VecDuplicate(u,&b);CHKERRQ(ierr); 
    ierr = VecDuplicate(b,&x);CHKERRQ(ierr); 

    /* 
    Set exact solution; then compute right-hand-side vector. 
    By default we use an exact solution of a vector with all 
    elements of 1.0; Alternatively, using the runtime option 
    -random_sol forms a solution vector with random components. 
    */ 
    ierr = PetscOptionsGetBool(PETSC_NULL,"-random_exact_sol",&flg,PETSC_NULL);CHKERRQ(ierr); 
    if (flg) { 
    ierr = PetscRandomCreate(PETSC_COMM_WORLD,&rctx);CHKERRQ(ierr); 
    ierr = PetscRandomSetFromOptions(rctx);CHKERRQ(ierr); 
    ierr = VecSetRandom(u,rctx);CHKERRQ(ierr); 
    ierr = PetscRandomDestroy(&rctx);CHKERRQ(ierr); 
    } else { 
    ierr = VecSet(u,1.0);CHKERRQ(ierr); 
    } 
    ierr = MatMult(A,u,b);CHKERRQ(ierr); 

    /* 
    View the exact solution vector if desired 
    */ 
    flg = PETSC_FALSE; 
    ierr = PetscOptionsGetBool(PETSC_NULL,"-view_exact_sol",&flg,PETSC_NULL);CHKERRQ(ierr); 
    if (flg) {ierr = VecView(u,PETSC_VIEWER_STDOUT_WORLD);CHKERRQ(ierr);} 

    /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
       Create the linear solver and set various options 
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ 

    /* 
    Create linear solver context 
    */ 
    ierr = KSPCreate(PETSC_COMM_WORLD,&ksp);CHKERRQ(ierr); 

    /* 
    Set operators. Here the matrix that defines the linear system 
    also serves as the preconditioning matrix. 
    */ 
    ierr = KSPSetOperators(ksp,A,A,DIFFERENT_NONZERO_PATTERN);CHKERRQ(ierr); 

    /* 
    Set linear solver defaults for this problem (optional). 
    - By extracting the KSP and PC contexts from the KSP context, 
     we can then directly call any KSP and PC routines to set 
     various options. 
    - The following two statements are optional; all of these 
     parameters could alternatively be specified at runtime via 
     KSPSetFromOptions(). All of these defaults can be 
     overridden at runtime, as indicated below. 
    */ 
    ierr = KSPSetTolerances(ksp,1.e-2/((m+1)*(n+1)),1.e-50,PETSC_DEFAULT, 
          PETSC_DEFAULT);CHKERRQ(ierr); 

    /* 
    Set runtime options, e.g., 
     -ksp_type <type> -pc_type <type> -ksp_monitor -ksp_rtol <rtol> 
    These options will override those specified above as long as 
    KSPSetFromOptions() is called _after_ any other customization 
    routines. 
    */ 
    ierr = KSPSetFromOptions(ksp);CHKERRQ(ierr); 

    /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
         Solve the linear system 
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ 

    ierr = KSPSolve(ksp,b,x);CHKERRQ(ierr); 

    /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
         Check solution and clean up 
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ 

    /* 
    Check the error 
    */ 
    ierr = VecAXPY(x,-1.0,u);CHKERRQ(ierr); 
    ierr = VecNorm(x,NORM_2,&norm);CHKERRQ(ierr); 
    ierr = KSPGetIterationNumber(ksp,&its);CHKERRQ(ierr); 
    /* Scale the norm */ 
    /* norm *= sqrt(1.0/((m+1)*(n+1))); */ 

    /* 
    Print convergence information. PetscPrintf() produces a single 
    print statement from all processes that share a communicator. 
    An alternative is PetscFPrintf(), which prints to a file. 
    */ 
    ierr = PetscPrintf(PETSC_COMM_WORLD,"Norm of error %A iterations %D\n", 
        norm,its);CHKERRQ(ierr); 

    /* 
    Free work space. All PETSc objects should be destroyed when they 
    are no longer needed. 
    */ 
    ierr = KSPDestroy(&ksp);CHKERRQ(ierr); 
    ierr = VecDestroy(&u);CHKERRQ(ierr); ierr = VecDestroy(&x);CHKERRQ(ierr); 
    ierr = VecDestroy(&b);CHKERRQ(ierr); ierr = MatDestroy(&A);CHKERRQ(ierr); 

    /* 
    Always call PetscFinalize() before exiting a program. This routine 
     - finalizes the PETSc libraries as well as MPI 
     - provides summary and diagnostic information if certain runtime 
     options are chosen (e.g., -log_summary). 
    */ 
    ierr = PetscFinalize(); 
    return 0; 
} 

Có ai biết làm thế nào để điền vào ma trận riêng trong ví dụ?

Trả lời

11

Vâng, điều này có thể hơi khó khăn khi bạn bắt đầu. Có một hướng dẫn tốt về quy trình trong hướng dẫn thisACTS từ năm 2006; các tutorials listed trên trang web của PetSC nói chung là khá tốt.

Các bộ phận quan trọng của việc này là:

ierr = MatCreate(PETSC_COMM_WORLD,&A);CHKERRQ(ierr); 

Trên thực tế tạo ra các đối tượng ma trận PetSC, Mat A;

ierr = MatSetSizes(A,PETSC_DECIDE,PETSC_DECIDE,m*n,m*n);CHKERRQ(ierr); 

đặt kích thước; ở đây, ma trận là m*n x m*n, vì nó là một stencil để hoạt động trên một lưới m x n 2d

ierr = MatSetFromOptions(A);CHKERRQ(ierr); 

này chỉ mất bất kỳ tùy chọn dòng lệnh PetSC mà bạn có thể đã cung cấp vào thời gian chạy và áp dụng chúng vào ma trận, nếu bạn muốn kiểm soát cách A được thiết lập; nếu không, bạn chỉ có thể sử dụng MatCreateMPIAIJ() để tạo nó làm ma trận định dạng AIJ (mặc định), MatCreateMPIDense() nếu nó là một ma trận dày đặc.

ierr = MatMPIAIJSetPreallocation(A,5,PETSC_NULL,5,PETSC_NULL);CHKERRQ(ierr); 
    ierr = MatSeqAIJSetPreallocation(A,5,PETSC_NULL);CHKERRQ(ierr); 

Bây giờ chúng tôi đã nhận được ma trận AIJ, các cuộc gọi này chỉ phân bổ trước ma trận thưa thớt, giả sử 5 số không trên mỗi hàng. Đây là cho hiệu suất. Lưu ý rằng cả hai hàm MPI và Seq phải được gọi để đảm bảo rằng nó hoạt động với cả bộ xử lý 1 và nhiều bộ xử lý; điều này luôn có vẻ kỳ lạ, nhưng bạn đã đi.

Ok, bây giờ ma trận đã được thiết lập xong, đây là nơi chúng ta bắt đầu đi vào thịt thực sự của vật chất.

Trước tiên, chúng tôi tìm hiểu những hàng mà quy trình cụ thể này sở hữu. Phân bố theo hàng, là một phân bố tốt cho các ma trận thưa thớt điển hình.

ierr = MatGetOwnershipRange(A,&Istart,&Iend);CHKERRQ(ierr); 

Vì vậy, sau cuộc gọi này, mỗi bộ xử lý có phiên bản riêng của Istart và Iend, và công việc của bộ vi xử lý này của mình để cập nhật hàng bắt đầu từ Istart cuối kết thúc ngay trước Iend, như bạn thấy trong này cho vòng lặp:

for (Ii=Istart; Ii<Iend; Ii++) { 
    v = -1.0; i = Ii/n; j = Ii - i*n; 

Ok, vì vậy nếu chúng ta đang hoạt động trên hàng Ii, điều này tương ứng với vị trí trên lưới (i,j) nơi i = Ii/nj = Ii % n. Ví dụ: vị trí lưới (i,j) tương ứng với hàng Ii = i*n + j. Có ý nghĩa?

Tôi sẽ loại bỏ các câu lệnh if ở đây vì chúng quan trọng nhưng chúng chỉ xử lý các giá trị biên và chúng làm cho mọi thứ trở nên phức tạp hơn.

Trong hàng này, sẽ có +4 trên đường chéo và -1 ở cột tương ứng với , (i+1,j), (i,j-1)(i,j+1). Giả sử rằng chúng tôi đã không đi ra khỏi cuối của lưới điện cho các (ví dụ, 1 < i < m-11 < j < n-1), có nghĩa

J = Ii - n; ierr = MatSetValues(A,1,&Ii,1,&J,&v,INSERT_VALUES);CHKERRQ(ierr); 
    J = Ii + n; ierr = MatSetValues(A,1,&Ii,1,&J,&v,INSERT_VALUES);CHKERRQ(ierr); 
    J = Ii - 1; ierr = MatSetValues(A,1,&Ii,1,&J,&v,INSERT_VALUES);CHKERRQ(ierr); 
    J = Ii + 1; ierr = MatSetValues(A,1,&Ii,1,&J,&v,INSERT_VALUES);CHKERRQ(ierr); 

    v = 4.0; ierr = MatSetValues(A,1,&Ii,1,&Ii,&v,INSERT_VALUES);CHKERRQ(ierr); 
    } 

Các câu lệnh if Tôi lấy ra chỉ cần tránh thiết lập những giá trị nếu họ không tồn tại, và macro CHKERRQ chỉ in ra một lỗi hữu ích nếu ierr != 0, ví dụ như cuộc gọi giá trị đã đặt không thành công (vì chúng tôi đã cố đặt giá trị không hợp lệ).

Bây giờ, chúng tôi đã đặt giá trị cục bộ; các cuộc gọi MatAssembly bắt đầu giao tiếp để đảm bảo mọi giá trị cần thiết được trao đổi giữa các bộ xử lý. Nếu bạn có bất kỳ công việc không liên quan để làm, nó có thể bị mắc kẹt giữa Begin và End để cố gắng chồng chéo thông tin liên lạc và tính toán:

ierr = MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr); 
    ierr = MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr); 

Và bây giờ bạn đã hoàn tất và có thể gọi giải quyết của bạn.

Vì vậy, một quy trình làm việc điển hình là:

  • Tạo ma trận của bạn (MatCreate)
  • Đặt kích thước của nó (MatSetSizes)
  • Đặt tùy chọn ma trận khác nhau (MatSetFromOptions là một lựa chọn tốt, chứ không phải là hardcoding điều)
  • Đối với ma trận thưa thớt, hãy đặt mức độ preallocation cho các dự đoán hợp lý cho số lượng số không trên mỗi hàng; bạn có thể làm điều này với một giá trị duy nhất (như ở đây), hoặc với một mảng đại diện cho số không số không mỗi hàng (ở đây điền vào với PETSC_NULL): (MatMPIAIJSetPreallocation, MatSeqAIJSetPreallocation)
  • Tìm hiểu các hàng là trách nhiệm của bạn: (MatGetOwnershipRange)
  • Đặt các giá trị (gọi MatSetValues hoặc một lần cho mỗi giá trị, hoặc đi qua trong một đoạn của các giá trị; INSERT_VALUES bộ các yếu tố mới, ADD_VALUES gia bất kỳ yếu tố hiện có)
  • Sau đó làm việc lắp ráp (MatAssemblyBegin, MatAssemblyEnd).

Các trường hợp sử dụng phức tạp hơn có thể xảy ra.

+0

điều này cần nhiều phiếu bầu hơn – pyCthon