|
| 1 | +import os |
| 2 | +import ctypes |
| 3 | +from pathlib import Path |
| 4 | + |
| 5 | +from petsctools import get_petscvariables, MissingPetscException |
| 6 | + |
| 7 | +from devito.tools import memoized_func |
| 8 | + |
| 9 | + |
| 10 | +class PetscOSError(OSError): |
| 11 | + pass |
| 12 | + |
| 13 | + |
| 14 | +@memoized_func |
| 15 | +def get_petsc_dir(): |
| 16 | + petsc_dir = os.environ.get('PETSC_DIR') |
| 17 | + if petsc_dir is None: |
| 18 | + raise PetscOSError("PETSC_DIR environment variable not set") |
| 19 | + else: |
| 20 | + petsc_dir = (Path(petsc_dir),) |
| 21 | + |
| 22 | + petsc_arch = os.environ.get('PETSC_ARCH') |
| 23 | + if petsc_arch is not None: |
| 24 | + petsc_dir += (petsc_dir[0] / petsc_arch,) |
| 25 | + |
| 26 | + petsc_installed = petsc_dir[-1] / 'include' / 'petscconf.h' |
| 27 | + if not petsc_installed.is_file(): |
| 28 | + raise PetscOSError("PETSc is not installed") |
| 29 | + |
| 30 | + return petsc_dir |
| 31 | + |
| 32 | + |
| 33 | +@memoized_func |
| 34 | +def core_metadata(): |
| 35 | + petsc_dir = get_petsc_dir() |
| 36 | + |
| 37 | + petsc_include = tuple([arch / 'include' for arch in petsc_dir]) |
| 38 | + petsc_lib = tuple([arch / 'lib' for arch in petsc_dir]) |
| 39 | + |
| 40 | + return { |
| 41 | + 'includes': ('petscsnes.h', 'petscdmda.h'), |
| 42 | + 'include_dirs': petsc_include, |
| 43 | + 'libs': ('petsc'), |
| 44 | + 'lib_dirs': petsc_lib, |
| 45 | + 'ldflags': tuple([f"-Wl,-rpath,{lib}" for lib in petsc_lib]) |
| 46 | + } |
| 47 | + |
| 48 | + |
| 49 | +try: |
| 50 | + petsc_variables = get_petscvariables() |
| 51 | +except MissingPetscException: |
| 52 | + petsc_variables = {} |
| 53 | + |
| 54 | + |
| 55 | +def get_petsc_type_mappings(): |
| 56 | + try: |
| 57 | + petsc_precision = petsc_variables['PETSC_PRECISION'] |
| 58 | + except KeyError: |
| 59 | + printer_mapper = {} |
| 60 | + petsc_type_to_ctype = {} |
| 61 | + else: |
| 62 | + petsc_scalar = 'PetscScalar' |
| 63 | + # TODO: Check to see whether Petsc is compiled with |
| 64 | + # 32-bit or 64-bit integers |
| 65 | + printer_mapper = {ctypes.c_int: 'PetscInt'} |
| 66 | + |
| 67 | + if petsc_precision == 'single': |
| 68 | + printer_mapper[ctypes.c_float] = petsc_scalar |
| 69 | + elif petsc_precision == 'double': |
| 70 | + printer_mapper[ctypes.c_double] = petsc_scalar |
| 71 | + |
| 72 | + # Used to construct ctypes.Structures that wrap PETSc objects |
| 73 | + petsc_type_to_ctype = {v: k for k, v in printer_mapper.items()} |
| 74 | + # Add other PETSc types |
| 75 | + petsc_type_to_ctype.update({ |
| 76 | + 'KSPType': ctypes.c_char_p, |
| 77 | + 'KSPConvergedReason': petsc_type_to_ctype['PetscInt'], |
| 78 | + 'KSPNormType': petsc_type_to_ctype['PetscInt'], |
| 79 | + }) |
| 80 | + return printer_mapper, petsc_type_to_ctype |
| 81 | + |
| 82 | + |
| 83 | +petsc_type_mappings, petsc_type_to_ctype = get_petsc_type_mappings() |
| 84 | + |
| 85 | + |
| 86 | +petsc_languages = ['petsc'] |
0 commit comments