From b37f869cc5e0a38caafea5123b85946764aefa38 Mon Sep 17 00:00:00 2001 From: ignis Date: Mon, 1 Jun 2026 06:37:38 +0000 Subject: [PATCH] docs: annotate compact difference and compiler stage cores using standard conventions --- code/Compact.f90 | 27 ++++++++++++------ code/code_gen/post.py | 56 ++++++++++++++++++++++++++++++++++--- code/m_calculate.f90 | 8 +++--- code/pycompact/pycompact.py | 43 ++++++++++++++++++++++++++++ 4 files changed, 118 insertions(+), 16 deletions(-) diff --git a/code/Compact.f90 b/code/Compact.f90 index b62f844..63758e5 100644 --- a/code/Compact.f90 +++ b/code/Compact.f90 @@ -1,18 +1,18 @@ !> @author Ignis - !> @brief High-order compact finite difference scheme solver. + !> @brief 특정한 order of accuracy를 가지는 compact finite difference scheme (generalized Padé scheme)을 구현한 모듈입니다. !! - !! This module handles the generation of tridiagonal/pentadiagonal matrices, - !! LU decomposition calculations, and tridiagonal solver operations for periodic - !! and non-periodic boundary conditions. + !! 이 모듈은 high-order compact 차분 스킴을 정의하고 수치 미분을 수행합니다. + !! Compact 차분 스킴은 implicit 스킴이므로, 모듈 내부에서 implicit 연산을 빠르게 해결하기 위해 + !! tridiagonal matrix solver(stdlu, ptdlu 등)가 함께 구현되어 동작합니다. MODULE Compact use, intrinsic :: iso_fortran_env, only: real64 IMPLICIT NONE - REAL(KIND=8), DIMENSION(:), ALLOCATABLE :: lxf,lxs,wxf,wxs, & - lyf,lys,wyf,wys, & - lzf,lzs,wzf,wzs + REAL(KIND=8), DIMENSION(:), ALLOCATABLE :: lxf,lxs,wxf,wxs, & !< x-방향 LU Decomposition 밴드 계수 + lyf,lys,wyf,wys, & !< y-방향 LU Decomposition 밴드 계수 + lzf,lzs,wzf,wzs !< z-방향 LU Decomposition 밴드 계수 - INTEGER :: nxc,nyc,nzc + INTEGER :: nxc,nyc,nzc !< 각 방향의 실제 격자 사이즈 수치 (x, y, z) REAL(KIND=8), PARAMETER :: ezero = 1.0e-14 @@ -43,6 +43,17 @@ END SUBROUTINE ludcmp + !> LU 분해를 위한 포트란 workspace 배열 메모리를 동적 할당하는 서브루틴입니다. + !! + !! 경계 조건(xp, yp, zp = 0 주기적 경계 조건, 1 비주기적 경계 조건)에 따라 배열 크기와 + !! 할당 여부를 결정하며, 할당에 실패하면 에러를 출력하고 즉시 프로그램을 안전하게 종료(STOP)시킵니다. + !! + !! @param nx Grid size in x-direction. + !! @param ny Grid size in y-direction. + !! @param nz Grid size in z-direction. + !! @param xp Periodic flag for x-direction (0 = periodic, other = non-periodic). + !! @param yp Periodic flag for y-direction (0 = periodic, other = non-periodic). + !! @param zp Periodic flag for z-direction (0 = periodic, other = non-periodic). SUBROUTINE ludcmp_allocate(nx,ny,nz,xp,yp,zp) INTEGER, INTENT(IN) :: nx,ny,nz INTEGER, INTENT(IN) :: xp,yp,zp diff --git a/code/code_gen/post.py b/code/code_gen/post.py index 86fcc74..f209732 100644 --- a/code/code_gen/post.py +++ b/code/code_gen/post.py @@ -6,7 +6,17 @@ from sympy.printing.fortran import FCodePrinter @v_args(inline=True) class LarkToSympy(Transformer): + """Transformer that parses Lark AST mathematical nodes into SymPy expression objects. + + This recursively traverses the AST for algebraic equations, mapping operations, + constants, brackets, and custom derivative definitions directly to standard SymPy nodes. + """ def __init__(self, fdict): + """Initializes the Lark-to-SymPy transformer. + + Args: + fdict (dict): Dictionary mapping variables to their Field definitions. + """ self.fdict = fdict def number(self, numeral): @@ -1083,9 +1093,18 @@ call MPI_ALLREDUCE(MPI_IN_PLACE, {{ name }}, nxp, MPI_REAL8, MPI_SUM, MPI_COMM_T class Stage1(): - ''' conversion from tree to python data ''' + """First compilation stage. Performs conversion of Lark AST tree into Python field datasets. + + This uses a visitor class to collect all algebraic equations, primary variables, + derived fields, and average specs from the parsed DSL input. + """ def __init__ (self, raw_tree): + """Initializes Stage 1 by parsing the raw AST tree. + + Args: + raw_tree (lark.Tree): The parsed AST representation of the DSL input. + """ self.primary = set([]) self.derived = {} self.averaged = {} @@ -1098,9 +1117,18 @@ class Stage1(): class Stage2(): - ''' expand derivatives and averages''' + """Second compilation stage. Expands derivative and fluctuation terms. + + This stage traverses the collected definitions, resolving and creating matching + derived fields for derivatives, fluctuations, and weighted averages. + """ def __init__ (self, src): + """Initializes Stage 2 by expanding variables from the previous stage. + + Args: + src (Stage1): Completed Stage 1 compilation dataset. + """ self.src = src self.primary = src.primary self.derived = src.derived @@ -1144,9 +1172,19 @@ class Stage2(): class Stage3(): - ''' calculate execution order ''' + """Third compilation stage. Calculates the topological execution order. + + Resolves dependencies between algebraic equations and calculates the correct order + of calculations. It splits calculation passes into two distinct execution blocks + (Pre-averaging Pass 1, and Post-averaging Pass 2) using a topological sorter. + """ def __init__ (self, src): + """Initializes Stage 3 by resolving execution flows. + + Args: + src (Stage2): Completed Stage 2 dataset. + """ self.src = src self.primary = src.primary self.derived = src.derived @@ -1291,8 +1329,18 @@ close (200) class Stage4(): - ''' analyze liveness and allocate array ''' + """Fourth compilation stage. Performs variable liveness analysis and memory pooling. + + Analyzes variable lifetimes inside loops to perform cache-friendly array pooling. + It leverages SymPy to simplify expressions, count flops, extract Common Subexpressions (CSE), + and compile highly optimized Fortran calculations with minimal memory footprint. + """ def __init__ (self, src): + """Initializes Stage 4. + + Args: + src (Stage3): Completed Stage 3 execution order. + """ self.src = src self.primary = src.primary self.derived = src.derived diff --git a/code/m_calculate.f90 b/code/m_calculate.f90 index ebae9e7..089967c 100644 --- a/code/m_calculate.f90 +++ b/code/m_calculate.f90 @@ -1,9 +1,9 @@ !> @author Google DeepMind Team & Ignis -!> @brief DNS post-processing mathematical operations and derivatives. +!> @brief 유동 도메인(Flow domain)이 정의되었을 때 x, y, z 방향에 적절한 compact 차분 스킴을 매칭하고 캐시(Cache) 관점의 계산 최적화를 수행하는 모듈입니다. !! -!! This module calculates spatial derivatives (first and second derivatives in X, Y, Z directions) -!! using high-order compact finite difference schemes. It also calculates chemical reaction rates, -!! positive/negative component extraction, and threshold operations. +!! 이 모듈은 3차원 유동 도메인 필드 데이터를 입력받아 각 차원 방향으로 수치 미분을 행합니다. +!! 특히 1차 및 2차 공간 미분(ddx, ddy, ddz 등)을 고차 컴팩트 스킴으로 해결하며, +!! 메모리 캐시 효율성(Cache blocking) 및 전치(Transpose) 최적화 연산(`tp2`)을 포함하고 있습니다. module m_calculate use, intrinsic :: iso_fortran_env, only: real64 diff --git a/code/pycompact/pycompact.py b/code/pycompact/pycompact.py index 0b46dab..e157f5f 100644 --- a/code/pycompact/pycompact.py +++ b/code/pycompact/pycompact.py @@ -2,8 +2,27 @@ import numpy as np from compact import compact class CompactScheme: + """Python wrapper for the high-order compact finite difference scheme core. + + This wraps the compiled Fortran `compact` solver module, handling grid configurations, + boundary periodicities, array allocations, and LU decompositions. It exposes + differentiation methods ddx, ddy, and ddz to Python. + """ def __init__ (self, nx, ny, nz, px, py, pz, lx, ly, lz): + """Initializes the CompactScheme solver. + + Args: + nx (int): Grid points in X direction. + ny (int): Grid points in Y direction. + nz (int): Grid points in Z direction. + px (bool): Periodic boundary condition flag for X direction. + py (bool): Periodic boundary condition flag for Y direction. + pz (bool): Periodic boundary condition flag for Z direction. + lx (float): Domain size in X direction. + ly (float): Domain size in Y direction. + lz (float): Domain size in Z direction. + """ pi8 = np.arccos(-1., dtype=np.float64) @@ -196,6 +215,14 @@ class CompactScheme: def ddx (self, src): + """Computes the first-order spatial derivative in the X direction. + + Args: + src (numpy.ndarray): 3D input field array matching (nz, ny, nx) shape. + + Returns: + numpy.ndarray: 3D first derivative array in the X direction. + """ if src.shape != self.shape: print ("error") @@ -219,6 +246,14 @@ class CompactScheme: return dst def ddy (self, src): + """Computes the first-order spatial derivative in the Y direction. + + Args: + src (numpy.ndarray): 3D input field array matching (nz, ny, nx) shape. + + Returns: + numpy.ndarray: 3D first derivative array in the Y direction. + """ if src.shape != self.shape: print ("error") @@ -242,6 +277,14 @@ class CompactScheme: return dst def ddz (self, src): + """Computes the first-order spatial derivative in the Z direction. + + Args: + src (numpy.ndarray): 3D input field array matching (nz, ny, nx) shape. + + Returns: + numpy.ndarray: 3D first derivative array in the Z direction. + """ if src.shape != self.shape: print ("error")