gt4py.cartesian package¶
Subpackages¶
- gt4py.cartesian.backend package
- Subpackages
- Submodules
- gt4py.cartesian.backend.base module
BackendBaseBackendBasePyExtBackendBasePyExtBackend._abc_implBasePyExtBackend.build_extension_module()BasePyExtBackend.extra_cache_infoBasePyExtBackend.extra_cache_validation_keysBasePyExtBackend.generate()BasePyExtBackend.pyext_build_dir_pathBasePyExtBackend.pyext_class_nameBasePyExtBackend.pyext_module_nameBasePyExtBackend.pyext_module_path
from_name()register()
- gt4py.cartesian.backend.dace_backend module
BaseDaceBackendDaCeBindingsCodegenDaCeCUDAPyExtModuleGeneratorDaCeComputationCodegenDaCeExtGeneratorDaCePyExtModuleGeneratorDaceCPUBackendDaceCPUKFirstBackendDaceCPU_KJIDaceGPUBackendDaceGPUBackendIJKSDFGManager_sdfg_add_arrays_and_edges()_sdfg_specialize_symbols()_specialize_transient_strides()freeze_origin_domain_sdfg()
- gt4py.cartesian.backend.dace_lazy_stencil module
- gt4py.cartesian.backend.dace_stencil_object module
- gt4py.cartesian.backend.debug_backend module
- gt4py.cartesian.backend.gtc_common module
- gt4py.cartesian.backend.gtcpp_backend module
GTBaseBackendGTCppBindingsCodegenGTCppBindingsCodegen.ProgramGTCppBindingsCodegen._node_visitor_cache_GTCppBindingsCodegen._unique_indexGTCppBindingsCodegen.apply()GTCppBindingsCodegen.unique_index()GTCppBindingsCodegen.visit_DataType()GTCppBindingsCodegen.visit_FieldDecl()GTCppBindingsCodegen.visit_GlobalParamDecl()GTCppBindingsCodegen.visit_Program()
GTCpuIfirstBackendGTCpuKfirstBackendGTExtGeneratorGTGpuBackend
- gt4py.cartesian.backend.module_generator module
BaseModuleGeneratorBaseModuleGenerator.SOURCE_LINE_LENGTHBaseModuleGenerator.TEMPLATE_INDENT_SIZEBaseModuleGenerator.TEMPLATE_RESOURCEBaseModuleGenerator.__call__()BaseModuleGenerator._abc_implBaseModuleGenerator.args_dataBaseModuleGenerator.backend_nameBaseModuleGenerator.builderBaseModuleGenerator.generate_backend_name()BaseModuleGenerator.generate_base_class_name()BaseModuleGenerator.generate_class_members()BaseModuleGenerator.generate_class_name()BaseModuleGenerator.generate_constants()BaseModuleGenerator.generate_docstring()BaseModuleGenerator.generate_implementation()BaseModuleGenerator.generate_imports()BaseModuleGenerator.generate_module_members()BaseModuleGenerator.generate_options()BaseModuleGenerator.generate_post_run()BaseModuleGenerator.generate_pre_run()BaseModuleGenerator.generate_signature()BaseModuleGenerator.generate_sources()BaseModuleGenerator.template
ModuleDatamake_args_data_from_gtir()
- gt4py.cartesian.backend.numpy_backend module
- gt4py.cartesian.backend.pyext_builder module
- gt4py.cartesian.backend.python_common module
- Module contents
BackendBaseBackendBaseModuleGeneratorBaseModuleGenerator.SOURCE_LINE_LENGTHBaseModuleGenerator.TEMPLATE_INDENT_SIZEBaseModuleGenerator.TEMPLATE_RESOURCEBaseModuleGenerator.__call__()BaseModuleGenerator._abc_implBaseModuleGenerator.args_dataBaseModuleGenerator.backend_nameBaseModuleGenerator.builderBaseModuleGenerator.generate_backend_name()BaseModuleGenerator.generate_base_class_name()BaseModuleGenerator.generate_class_members()BaseModuleGenerator.generate_class_name()BaseModuleGenerator.generate_constants()BaseModuleGenerator.generate_docstring()BaseModuleGenerator.generate_implementation()BaseModuleGenerator.generate_imports()BaseModuleGenerator.generate_module_members()BaseModuleGenerator.generate_options()BaseModuleGenerator.generate_post_run()BaseModuleGenerator.generate_pre_run()BaseModuleGenerator.generate_signature()BaseModuleGenerator.generate_sources()BaseModuleGenerator.template
BasePyExtBackendBasePyExtBackend._abc_implBasePyExtBackend.build_extension_module()BasePyExtBackend.extra_cache_infoBasePyExtBackend.extra_cache_validation_keysBasePyExtBackend.generate()BasePyExtBackend.pyext_build_dir_pathBasePyExtBackend.pyext_class_nameBasePyExtBackend.pyext_module_nameBasePyExtBackend.pyext_module_path
DaceCPUBackendDaceCPUKFirstBackendDaceGPUBackendDebugBackendGTCpuIfirstBackendGTCpuKfirstBackendGTGpuBackendNumpyBackendfrom_name()register()
- gt4py.cartesian.frontend package
- Submodules
- gt4py.cartesian.frontend.base module
- gt4py.cartesian.frontend.defir_builder module
- gt4py.cartesian.frontend.defir_to_gtir module
DataDimensionsCheckerDefIRToGTIRDefIRToGTIR.GT4PY_BUILTIN_TO_GTIRDefIRToGTIR.GT4PY_DTYPE_TO_GTIR_DTYPEDefIRToGTIR.GT4PY_ITERATIONORDER_TO_GTIR_LOOPORDERDefIRToGTIR.GT4PY_LEVELMARKER_TO_GTIR_LEVELMARKERDefIRToGTIR.GT4PY_NATIVE_FUNC_TO_GTIRDefIRToGTIR.GT4PY_OP_TO_GTIR_OPDefIRToGTIR.GT4PY_UNARYOP_TO_GTIRDefIRToGTIR.apply()DefIRToGTIR.transform_offset()DefIRToGTIR.visit_ArgumentInfo()DefIRToGTIR.visit_Assign()DefIRToGTIR.visit_AxisBound()DefIRToGTIR.visit_AxisInterval()DefIRToGTIR.visit_BinOpExpr()DefIRToGTIR.visit_BlockStmt()DefIRToGTIR.visit_BuiltinLiteral()DefIRToGTIR.visit_Cast()DefIRToGTIR.visit_ComputationBlock()DefIRToGTIR.visit_FieldDecl()DefIRToGTIR.visit_FieldRef()DefIRToGTIR.visit_HorizontalIf()DefIRToGTIR.visit_If()DefIRToGTIR.visit_IteratorAccess()DefIRToGTIR.visit_NativeFuncCall()DefIRToGTIR.visit_RuntimeAxisBound()DefIRToGTIR.visit_ScalarLiteral()DefIRToGTIR.visit_StencilDefinition()DefIRToGTIR.visit_TernaryOpExpr()DefIRToGTIR.visit_UnaryOpExpr()DefIRToGTIR.visit_VarDecl()DefIRToGTIR.visit_VarRef()DefIRToGTIR.visit_While()
UnrollVectorAssignmentsUnrollVectorExpressions_convert_dtype()_make_literal()
- gt4py.cartesian.frontend.exceptions module
- gt4py.cartesian.frontend.gtscript_frontend module
AssertionCheckerCallInlinerCallInliner.__call__()CallInliner._process_stmts()CallInliner.apply()CallInliner.visit()CallInliner.visit_Assert()CallInliner.visit_Assign()CallInliner.visit_Call()CallInliner.visit_Expr()CallInliner.visit_FunctionDef()CallInliner.visit_If()CallInliner.visit_While()CallInliner.visit_With()
CollectLocalSymbolsAstVisitorCompiledIfInlinerGTScriptFrontendGTScriptParserHorizontalIntervalParserIRMakerIRMaker.__call__()IRMaker._absolute_K_index_method()IRMaker._are_blocks_sorted()IRMaker._are_intervals_nonoverlapping()IRMaker._domain_from_gtscript_axis()IRMaker._eval_index()IRMaker._eval_new_spatial_index()IRMaker._is_field()IRMaker._is_known()IRMaker._is_local_symbol()IRMaker._is_parameter()IRMaker._parse_assign_target()IRMaker._parse_region_intervals()IRMaker._resolve_assign()IRMaker._visit_computation_node()IRMaker._visit_interval_node()IRMaker._visit_iteration_order_node()IRMaker._visit_with_horizontal()IRMaker.stencil_nameIRMaker.visit_Add()IRMaker.visit_And()IRMaker.visit_AnnAssign()IRMaker.visit_Assign()IRMaker.visit_Attribute()IRMaker.visit_AugAssign()IRMaker.visit_BinOp()IRMaker.visit_BoolOp()IRMaker.visit_Call()IRMaker.visit_Compare()IRMaker.visit_Constant()IRMaker.visit_Div()IRMaker.visit_Eq()IRMaker.visit_FunctionDef()IRMaker.visit_Gt()IRMaker.visit_GtE()IRMaker.visit_If()IRMaker.visit_IfExp()IRMaker.visit_Lt()IRMaker.visit_LtE()IRMaker.visit_MatMult()IRMaker.visit_Mod()IRMaker.visit_Mult()IRMaker.visit_Name()IRMaker.visit_Not()IRMaker.visit_NotEq()IRMaker.visit_Or()IRMaker.visit_Pow()IRMaker.visit_Raise()IRMaker.visit_Sub()IRMaker.visit_Subscript()IRMaker.visit_Tuple()IRMaker.visit_UAdd()IRMaker.visit_USub()IRMaker.visit_UnaryOp()IRMaker.visit_While()IRMaker.visit_With()IRMaker.written_vars
IntervalParserParsingContextReturnReplacerValueInlinerVerticalIntervalParser_ENUM_REGISTER_filter_absolute_K_index_method()_find_accesses_with_offsets()_is_datadims_indexing_name()_is_datadims_indexing_node()_is_ellipsis_node()_is_iterator_access()_make_init_computations()_make_temp_decls()_trim_indexing_symbol()
- gt4py.cartesian.frontend.node_util module
- gt4py.cartesian.frontend.nodes module
- Definitions
- Definition IR
AbsoluteKIndexArgumentInfoAssignAxisAxisBoundAxisIndexAxisIntervalAxisPositionBaseAxisBoundBinOpExprBinaryOperatorBinaryOperator.ADDBinaryOperator.ANDBinaryOperator.DIVBinaryOperator.EQBinaryOperator.GEBinaryOperator.GTBinaryOperator.IR_OP_TO_PYTHON_OPBinaryOperator.IR_OP_TO_PYTHON_SYMBOLBinaryOperator.LEBinaryOperator.LTBinaryOperator.MATMULTBinaryOperator.MODBinaryOperator.MULBinaryOperator.NEBinaryOperator.ORBinaryOperator.POWBinaryOperator.SUBBinaryOperator.python_opBinaryOperator.python_symbol
BlockStmtBuiltinBuiltinLiteralCastCompositeExprComputationBlockDataTypeDeclDomainEmptyExprFieldDeclFieldRefHorizontalIfIfInvalidBranchIterationOrderIteratorAccessLevelMarkerLiteralLocationNativeFuncCallNativeFunctionNativeFunction.ABSNativeFunction.ARCCOSNativeFunction.ARCCOSHNativeFunction.ARCSINNativeFunction.ARCSINHNativeFunction.ARCTANNativeFunction.ARCTANHNativeFunction.CBRTNativeFunction.CEILNativeFunction.COSNativeFunction.COSHNativeFunction.ERFNativeFunction.ERFCNativeFunction.EXPNativeFunction.FLOAT32NativeFunction.FLOAT64NativeFunction.FLOORNativeFunction.GAMMANativeFunction.INT32NativeFunction.INT64NativeFunction.IR_OP_TO_NUM_ARGSNativeFunction.ISFINITENativeFunction.ISINFNativeFunction.ISNANNativeFunction.LOGNativeFunction.LOG10NativeFunction.MAXNativeFunction.MINNativeFunction.MODNativeFunction.ROUNDNativeFunction.ROUND_AWAY_FROM_ZERONativeFunction.SINNativeFunction.SINHNativeFunction.SQRTNativeFunction.TANNativeFunction.TANHNativeFunction.TRUNCNativeFunction.arity
NodeRefRuntimeAxisBoundScalarLiteralStatementStencilDefinitionTernaryOpExprUnaryOpExprUnaryOperatorVarDeclVarRefWhilefrontend_type_to_native_type()
- Module contents
- gt4py.cartesian.gtc package
- Subpackages
- gt4py.cartesian.gtc.dace package
- gt4py.cartesian.gtc.debug package
- gt4py.cartesian.gtc.gtcpp package
- gt4py.cartesian.gtc.numpy package
- gt4py.cartesian.gtc.passes package
- Subpackages
- Submodules
- gt4py.cartesian.gtc.passes.gtir_definitive_assignment_analysis module
- gt4py.cartesian.gtc.passes.gtir_dtype_resolver module
- gt4py.cartesian.gtc.passes.gtir_k_boundary module
- gt4py.cartesian.gtc.passes.gtir_pipeline module
- gt4py.cartesian.gtc.passes.gtir_prune_unused_parameters module
- gt4py.cartesian.gtc.passes.gtir_upcaster module
- gt4py.cartesian.gtc.passes.horizontal_masks module
- gt4py.cartesian.gtc.passes.oir_access_kinds module
- gt4py.cartesian.gtc.passes.oir_pipeline module
- Module contents
- Submodules
- gt4py.cartesian.gtc.common module
AbsoluteKIndexAbsoluteKIndex__ExprArithmeticOperatorAssignStmtAssignStmt__FieldAccess_ExprAssignStmt__VectorLValue_ExprAssignStmt__gt4py_cartesian_gtc_gtcpp_gtcpp_localaccess_gt4py_cartesian_gtc_gtcpp_gtcpp_accessorref_ExprAssignStmt__gt4py_cartesian_gtc_gtcpp_gtcpp_localaccess_gt4py_cartesian_gtc_gtcpp_gtcpp_accessorref_Expr.leftAssignStmt__gt4py_cartesian_gtc_gtcpp_gtcpp_localaccess_gt4py_cartesian_gtc_gtcpp_gtcpp_accessorref_Expr.rightAssignStmt__gt4py_cartesian_gtc_gtcpp_gtcpp_localaccess_gt4py_cartesian_gtc_gtcpp_gtcpp_accessorref_Expr.update_forward_refs()
AssignStmt__gt4py_cartesian_gtc_oir_scalaraccess_gt4py_cartesian_gtc_oir_fieldaccess_ExprAssignStmt__gt4py_cartesian_gtc_oir_scalaraccess_gt4py_cartesian_gtc_oir_fieldaccess_Expr.leftAssignStmt__gt4py_cartesian_gtc_oir_scalaraccess_gt4py_cartesian_gtc_oir_fieldaccess_Expr.rightAssignStmt__gt4py_cartesian_gtc_oir_scalaraccess_gt4py_cartesian_gtc_oir_fieldaccess_Expr.update_forward_refs()
AssignmentKindAxisBoundBaseAxisBoundBinaryOpBinaryOp__ExprBlockStmtBlockStmt__StmtBuiltInLiteralCartesianOffsetCastCast__ExprComparisonOperatorDataTypeExprExprKindFieldAccessFieldAccess__Expr_VariableKOffsetGTCPostconditionErrorGTCPreconditionErrorHorizontalIntervalHorizontalMaskHorizontalRestrictionHorizontalRestriction__StmtIfStmtIfStmt__BlockStmt_ExprLevelMarkerLiteralLocNodeLogicalOperatorLoopOrderNativeFuncCallNativeFuncCall__ExprNativeFunctionNativeFunction.ABSNativeFunction.ARCCOSNativeFunction.ARCCOSHNativeFunction.ARCSINNativeFunction.ARCSINHNativeFunction.ARCTANNativeFunction.ARCTANHNativeFunction.CBRTNativeFunction.CEILNativeFunction.COSNativeFunction.COSHNativeFunction.ERFNativeFunction.ERFCNativeFunction.EXPNativeFunction.FLOAT32NativeFunction.FLOAT64NativeFunction.FLOORNativeFunction.GAMMANativeFunction.INT32NativeFunction.INT64NativeFunction.IR_OP_TO_NUM_ARGSNativeFunction.ISFINITENativeFunction.ISINFNativeFunction.ISNANNativeFunction.LOGNativeFunction.LOG10NativeFunction.MAXNativeFunction.MINNativeFunction.MODNativeFunction.POWNativeFunction.ROUNDNativeFunction.ROUND_AWAY_FROM_ZERONativeFunction.SINNativeFunction.SINHNativeFunction.SQRTNativeFunction.TANNativeFunction.TANHNativeFunction.TRUNCNativeFunction.arity
RuntimeAxisBoundScalarAccessStmtTernaryOpTernaryOp__ExprUnaryOpUnaryOp__ExprUnaryOperatorVariableKOffsetVariableKOffset__ExprWhileWhile__Stmt_Expr_LvalueDimsValidator_make_root_validator()assign_stmt_dtype_validation()binary_op_dtype_propagation()compute_kind()data_type_to_typestr()native_func_call_dtype_propagation()op_to_ufunc()ternary_op_dtype_propagation()typestr_to_data_type()validate_dtype_is_set()validate_lvalue_dims()verify_and_get_common_dtype()verify_condition_is_boolean()
- gt4py.cartesian.gtc.definitions module
BoundaryCartesianSpaceCenteredExtentExtentFrameTupleFrameTuple._apply()FrameTuple._broadcast()FrameTuple._check_value()FrameTuple._compare()FrameTuple._reduce()FrameTuple.append()FrameTuple.concatenate()FrameTuple.from_k()FrameTuple.from_lower_upper()FrameTuple.intersection()FrameTuple.is_symmetricFrameTuple.is_valid()FrameTuple.is_zeroFrameTuple.lower_indicesFrameTuple.ndimsFrameTuple.ones()FrameTuple.union()FrameTuple.upper_indicesFrameTuple.zeros()
IndexNumericTupleNumericTuple._DEFAULTNumericTuple._apply()NumericTuple._broadcast()NumericTuple._check_value()NumericTuple._compare()NumericTuple.filter_mask()NumericTuple.from_k()NumericTuple.from_mask()NumericTuple.from_value()NumericTuple.intersection()NumericTuple.is_valid()NumericTuple.ndimsNumericTuple.ones()NumericTuple.union()NumericTuple.zeros()
Shape
- gt4py.cartesian.gtc.gtir module
AbsoluteKIndexArgumentBinaryOpBlockStmtCastDeclExprFieldAccessFieldDeclFieldIfStmtHorizontalRestrictionIntervalIteratorAccessLiteralNativeFuncCallParAssignStmtScalarAccessScalarDeclScalarIfStmtStencilStmtTernaryOpUnaryOpVariableKOffsetVerticalLoopWhile_cartesian_fieldaccess()_written_and_read_with_offset()
- gt4py.cartesian.gtc.gtir_to_oir module
GTIRToOIRGTIRToOIR.ContextGTIRToOIR._node_visitor_cache_GTIRToOIR.visit_AbsoluteKIndex()GTIRToOIR.visit_BinaryOp()GTIRToOIR.visit_Cast()GTIRToOIR.visit_FieldAccess()GTIRToOIR.visit_FieldDecl()GTIRToOIR.visit_FieldIfStmt()GTIRToOIR.visit_HorizontalRestriction()GTIRToOIR.visit_Interval()GTIRToOIR.visit_IteratorAccess()GTIRToOIR.visit_Literal()GTIRToOIR.visit_NativeFuncCall()GTIRToOIR.visit_ParAssignStmt()GTIRToOIR.visit_ScalarAccess()GTIRToOIR.visit_ScalarDecl()GTIRToOIR.visit_ScalarIfStmt()GTIRToOIR.visit_Stencil()GTIRToOIR.visit_TernaryOp()GTIRToOIR.visit_UnaryOp()GTIRToOIR.visit_VariableKOffset()GTIRToOIR.visit_VerticalLoop()GTIRToOIR.visit_While()
validate_stencil_memory_accesses()
- gt4py.cartesian.gtc.oir module
AbsoluteKIndexAssignStmtBinaryOpCacheDescCastCodeBlockDeclExprFieldAccessFieldDeclHorizontalExecutionHorizontalRestrictionIJCacheIntervalIteratorAccessKCacheLiteralLocalScalarMaskStmtNativeFuncCallScalarAccessScalarDeclStencilStmtTemporaryTernaryOpUnaryOpUnboundedIntervalVariableKOffsetVerticalLoopVerticalLoopSectionWhile_check_interval()
- gt4py.cartesian.gtc.ufuncs module
- gt4py.cartesian.gtc.utils module
- Module contents
- Subpackages
- gt4py.cartesian.testing package
- Submodules
- gt4py.cartesian.testing.input_strategies module
- gt4py.cartesian.testing.suites module
StencilTestSuiteStencilTestSuite.dtypesStencilTestSuite.domain_rangeStencilTestSuite.symbolsStencilTestSuite.definitionStencilTestSuite.validationStencilTestSuite.definition_strategiesStencilTestSuite.validation_strategiesStencilTestSuite.ndimsStencilTestSuite.global_boundariesStencilTestSuite._run_test_implementation()StencilTestSuite._skip_StencilTestSuite._test_generation()StencilTestSuite._test_implementation()
SuiteMetaunique_str()
- gt4py.cartesian.testing.utils module
- Module contents
StencilTestSuiteStencilTestSuite.dtypesStencilTestSuite.domain_rangeStencilTestSuite.symbolsStencilTestSuite.definitionStencilTestSuite.validationStencilTestSuite.definition_strategiesStencilTestSuite.validation_strategiesStencilTestSuite.ndimsStencilTestSuite.global_boundariesStencilTestSuite._run_test_implementation()StencilTestSuite._skip_StencilTestSuite._test_generation()StencilTestSuite._test_implementation()
field()global_name()none()parameter()
- gt4py.cartesian.utils package
- Submodules
- gt4py.cartesian.utils.attrib module
AttributeClassLike_GenericTypeDescriptor_TypeDescriptor_make_any_validator()_make_dict_validator()_make_list_validator()_make_nothing_validator()_make_sequence_validator()_make_set_validator()_make_tuple_validator()_make_type_validator()_make_union_validator()attribclass()attribkwclass()attribute()attributes_of()
- gt4py.cartesian.utils.base module
BaseFrozenBaseSingletonClassPropertyRegistryUniqueIdGeneratorclassmethod_to_function()classpropertycompose()flatten()flatten_iter()get_member()is_collection()is_identifier_name()is_iterable_of()is_mapping_of()jsonify()listify()make_dir()make_local_dir()make_module_from_file()namespace_from_nested_dict()normalize_mapping()patch_module()restore_module()shash()shashed_id()slugify()warn_experimental_feature()
- gt4py.cartesian.utils.compiler module
- gt4py.cartesian.utils.field module
- gt4py.cartesian.utils.meta module
ASTEvaluatorASTEvaluator.AST_OP_TO_OPASTEvaluator.apply()ASTEvaluator.generic_visit()ASTEvaluator.visit_Attribute()ASTEvaluator.visit_BinOp()ASTEvaluator.visit_BoolOp()ASTEvaluator.visit_Compare()ASTEvaluator.visit_Constant()ASTEvaluator.visit_Name()ASTEvaluator.visit_NameConstant()ASTEvaluator.visit_Num()ASTEvaluator.visit_Tuple()ASTEvaluator.visit_UnaryOp()
ASTPassASTTransformPassAssignTargetsCollectorImportsCollectorQualifiedNameCollectorSymbolsNameMapperast_dump()ast_eval()collect_assign_targets()collect_decorators()collect_imported_symbols()collect_names()get_ast()get_closure()get_qualified_name_from_node()get_source()map_symbol_names()remove_decorators()split_def_decorators()
- Module contents
BaseFrozenBaseSingletonFieldRegistryUniqueIdGeneratorclassmethod_to_function()classpropertycompose()flatten()flatten_iter()get_member()is_collection()is_identifier_name()is_iterable_of()is_mapping_of()jsonify()listify()make_dir()make_local_dir()make_module_from_file()namespace_from_nested_dict()normalize_mapping()patch_module()restore_module()shash()shashed_id()slugify()warn_experimental_feature()
Submodules¶
gt4py.cartesian.__externals__ module¶
Implementation of GTScript: an embedded DSL in Python for stencil computations.
Interface functions to define and compile GTScript definitions and empty symbol definitions for the keywords of the DSL.
gt4py.cartesian.__gtscript__ module¶
Implementation of GTScript: an embedded DSL in Python for stencil computations.
Interface functions to define and compile GTScript definitions and empty symbol definitions for the keywords of the DSL.
gt4py.cartesian.caching module¶
Caching strategies for stencil generation.
- class gt4py.cartesian.caching.CachingStrategy(builder: StencilBuilder)[source]¶
Bases:
ABC- _abc_impl = <_abc._abc_data object>¶
- abstract property backend_root_path: Path¶
Calculate and if necessary create the caching base path for the backend being used.
Avoid trying to create the root_path automatically.
- abstract property cache_info: Dict[str, Any]¶
Read currently stored cache info from file into a dictionary.
Empty if file is not found or not readable or no caching is intended.
- abstract property cache_info_path: Path | None¶
Calculate the file path where caching info for the current process should be stored.
- capture_externals() Dict[str, Any][source]¶
Extract externals from the annotated stencil definition for fingerprinting. Freezes the references.
- property class_name: str¶
Calculate the name for the stencil class, default is to read from build options.
- abstractmethod generate_cache_info() Dict[str, Any][source]¶
Generate the cache info dict.
Backend specific additions can be added via a hook properly on the backend instance. Override
gt4py.backend.base.Backend.extra_cache_info()to store extra info.
- abstractmethod is_cache_info_available_and_consistent(*, validate_hash: bool) bool[source]¶
Check if the cache can be read and is consistent.
If the cache info file can be read, try to validate it against the current info as returned by py:meth:generate_cache_info.
- Parameters:
validate_hash – Should the stencil fingerprint and source code hash be validated or not
- property module_postfix: str¶
Generate the postfix for stencil modules, can depend on the fingerprint.
Backends use this property when generating the module filename.
The example code would cause the generated module and class names to depend on the fingerprint of the stencil. That would ensure that after changing and regenerating a stencil it’s module can be loaded without unloading the previous version first. The default is empty and is suitable for when no caching is used.
Can also be re-used elsewhere for similar purposes.
- property module_prefix: str¶
Generate the prefix for stencil modules.
Backends use this property to determine the stencil module filename. This may help distinguish python modules from other files.
The default is an empty string and is suitable for situations where no caching is required and the generated module is intended to be imported manually.
- abstract property root_path: Path¶
Calculate and if necessary create the root path for stencil generation operations.
- class gt4py.cartesian.caching.JITCachingStrategy(builder: StencilBuilder, *, root_path: str | None = None, dir_name: str | None = None)[source]¶
Bases:
CachingStrategyCaching strategy for JIT stencil generation.
Assign a fingerprint to the stencil being generated based on the definition function and some of the build options. During generation, store this fingerprint along with other information in a cache info file.
In order to decide whether the stencil can be loaded from cache, check if a cache info file exists in the location corresponding to the current stencil. If it exists, compare it to the additional caching information for the current stencil. If the cache is consistent, a rebuild can be avoided.
- _abc_impl = <_abc._abc_data object>¶
- _externals¶
Extract externals from the annotated stencil definition for fingerprinting.
- _extract_api_annotations() List[str][source]¶
Extract API annotations from the annotated stencil definition for fingerprinting.
- property backend_root_path: Path¶
Calculate and if necessary create the caching base path for the backend being used.
Avoid trying to create the root_path automatically.
- property cache_info: Dict[str, Any]¶
Read currently stored cache info from file into a dictionary.
Empty if file is not found or not readable or no caching is intended.
- capture_externals() Dict[str, Any][source]¶
Extract externals from the annotated stencil definition for fingerprinting.
- property class_name: str¶
Calculate the name for the stencil class, default is to read from build options.
- generate_cache_info() Dict[str, Any][source]¶
Generate the cache info dict.
Backend specific additions can be added via a hook properly on the backend instance. Override
gt4py.backend.base.Backend.extra_cache_info()to store extra info.
- is_cache_info_available_and_consistent(*, validate_hash: bool, catch_exceptions: bool = True) bool[source]¶
Check if the cache can be read and is consistent.
If the cache info file can be read, try to validate it against the current info as returned by py:meth:generate_cache_info.
- Parameters:
validate_hash – Should the stencil fingerprint and source code hash be validated or not
- property module_postfix: str¶
Generate the postfix for stencil modules, can depend on the fingerprint.
Backends use this property when generating the module filename.
The example code would cause the generated module and class names to depend on the fingerprint of the stencil. That would ensure that after changing and regenerating a stencil it’s module can be loaded without unloading the previous version first. The default is empty and is suitable for when no caching is used.
Can also be re-used elsewhere for similar purposes.
- property module_prefix: str¶
Generate the prefix for stencil modules.
Backends use this property to determine the stencil module filename. This may help distinguish python modules from other files.
The default is an empty string and is suitable for situations where no caching is required and the generated module is intended to be imported manually.
- property root_path: Path¶
Calculate and if necessary create the root path for stencil generation operations.
- class gt4py.cartesian.caching.NoCachingStrategy(builder: StencilBuilder, *, output_path: pathlib.Path = PosixPath('.'))[source]¶
Bases:
CachingStrategyApply no caching.
Instead of calculating paths and names based on a stencil fingerprint, use user input or by default the current working dir to output source and build files.
This caching strategy is incapable of avoiding rebuilds and after rebuilding at runtime the old stencil and it’s module has to be unloaded by the user before reloading for any changes to take effect.
All methods related to generating or checking the cache info are noops and cache validation always fails.
- Parameters:
builder – A stencil builder instance
output_path – The path to where all source code should be written
- _abc_impl = <_abc._abc_data object>¶
- property cache_info: Dict[str, Any]¶
Read currently stored cache info from file into a dictionary.
Empty if file is not found or not readable or no caching is intended.
- property cache_info_path: Path | None¶
Calculate the file path where caching info for the current process should be stored.
- generate_cache_info() Dict[str, Any][source]¶
Generate the cache info dict.
Backend specific additions can be added via a hook properly on the backend instance. Override
gt4py.backend.base.Backend.extra_cache_info()to store extra info.
- is_cache_info_available_and_consistent(*, validate_hash: bool) bool[source]¶
Check if the cache can be read and is consistent.
If the cache info file can be read, try to validate it against the current info as returned by py:meth:generate_cache_info.
- Parameters:
validate_hash – Should the stencil fingerprint and source code hash be validated or not
- gt4py.cartesian.caching.strategy_factory(name: str, builder: StencilBuilder, *args: Any, **kwargs: Any) CachingStrategy[source]¶
gt4py.cartesian.config module¶
gt4py.cartesian.definitions module¶
- class gt4py.cartesian.definitions.AccessKind(*values)[source]¶
Bases:
IntFlag- NONE = 0¶
- READ = 1¶
- READ_WRITE = 3¶
- WRITE = 2¶
- _all_bits_ = 3¶
- _boundary_ = 'keep'¶
- _flag_mask_ = 3¶
- static _generate_next_value_(name, start, count, last_values)¶
Generate the next value when not given.
name: the name of the member start: the initial start value or None count: the number of existing members last_values: the last value assigned or None
- _inverted_ = None¶
- _singles_mask_ = 3¶
- class gt4py.cartesian.definitions.BuildOptions(*, name: str, module: str, format_source: bool = True, backend_opts: Dict[str, Any] = NOTHING, build_info: dict = None, rebuild: bool = False, raise_if_not_cached: bool = False, cache_settings: Dict[str, Any] = NOTHING, impl_opts: Dict[str, Any] = NOTHING, literal_int_precision: int = 64, literal_float_precision: int = 64)[source]¶
Bases:
AttributeClassLikeBuild options.
- literal_float_precision¶
Literal precision for float types and casts. Defaults to architecture precision unless overwritten by the environment variable GT4PY_LITERAL_FLOAT_PRECISION.
- literal_int_precision¶
Literal precision for int types and casts. Defaults to architecture precision unless overwritten by the environment variable GT4PY_LITERAL_INT_PRECISION.
- property qualified_name¶
- property shashed_id¶
- validate()¶
Validate this instance’s data attributes.
- class gt4py.cartesian.definitions.DomainInfo(parallel_axes: Tuple[str, ...], sequential_axis: str, min_sequential_axis_size: int, ndim: int)[source]¶
Bases:
object
- class gt4py.cartesian.definitions.FieldInfo(access: gt4py.cartesian.definitions.AccessKind, boundary: gt4py.cartesian.gtc.definitions.Boundary, axes: Tuple[str, ...], data_dims: Tuple[numbers.Integral, ...], dtype: numpy.dtype)[source]¶
Bases:
object- access: AccessKind¶
- exception gt4py.cartesian.definitions.GTSyntaxError(message: str, *, frontend: str)[source]¶
Bases:
GTError
- gt4py.cartesian.definitions.LITERAL_FLOAT_PRECISION = 64¶
Default literal precision used for unspecific float types and casts.
- gt4py.cartesian.definitions.LITERAL_INT_PRECISION = 64¶
Default literal precision used for unspecific int types and casts.
- class gt4py.cartesian.definitions.ParameterInfo(access: Literal[<AccessKind.NONE: 0>] | Literal[<AccessKind.READ: 1>], dtype: numpy.dtype)[source]¶
Bases:
object
- class gt4py.cartesian.definitions.StencilID(qualified_name: str, version: str)[source]¶
Bases:
AttributeClassLike- validate()¶
Validate this instance’s data attributes.
- gt4py.cartesian.definitions._ARCHITECTURE_LITERAL_PRECISION = '64'¶
Literal precision of the architecture; expected 64 or 32.
gt4py.cartesian.gt_cache_manager module¶
Utils for cleaning and querying the internal GT4Py cache for generated code.
gt4py.cartesian.gtscript module¶
Implementation of GTScript: an embedded DSL in Python for stencil computations.
Interface functions to define and compile GTScript definitions and empty symbol definitions for the keywords of the DSL.
- gt4py.cartesian.gtscript.BACKWARD = -1¶
Backward iteration order.
- gt4py.cartesian.gtscript.FORWARD = 1¶
Forward iteration order.
- gt4py.cartesian.gtscript.Field = <gt4py.cartesian.gtscript._FieldDescriptorMaker object>¶
Field descriptor.
- gt4py.cartesian.gtscript.I = Axis(name=I)¶
I axes (parallel).
- gt4py.cartesian.gtscript.IJ = (Axis(name=I), Axis(name=J))¶
Tuple of axes I, J.
- gt4py.cartesian.gtscript.IJK = (Axis(name=I), Axis(name=J), Axis(name=K))¶
Tuple of axes I, J, K.
- gt4py.cartesian.gtscript.IK = (Axis(name=I), Axis(name=K))¶
Tuple of axes I, K.
- gt4py.cartesian.gtscript.J = Axis(name=J)¶
J axes (parallel).
- gt4py.cartesian.gtscript.JK = (Axis(name=J), Axis(name=K))¶
Tuple of axes J, K.
- gt4py.cartesian.gtscript.K = Axis(name=K)¶
K axes (sequential).
- gt4py.cartesian.gtscript.PARALLEL = 0¶
Parallel iteration order.
- gt4py.cartesian.gtscript.Sequence = <gt4py.cartesian.gtscript._SequenceDescriptorMaker object>¶
Sequence descriptor.
- gt4py.cartesian.gtscript.__INLINED(compile_if_expression)[source]¶
Evaluate condition at compile time and inline statements from selected branch.
- gt4py.cartesian.gtscript.abs(x) int32 | int64 | float32 | float64[source]¶
Return the absolute value of the argument
- gt4py.cartesian.gtscript.acos(x) int32 | int64 | float32 | float64[source]¶
Return the arc cosine of x, in radians.
- gt4py.cartesian.gtscript.acosh(x) int32 | int64 | float32 | float64[source]¶
Return the inverse hyperbolic cosine of x, in radians.
- gt4py.cartesian.gtscript.asin(x) int32 | int64 | float32 | float64[source]¶
return the arc sine of x, in radians.
- gt4py.cartesian.gtscript.asinh(x) int32 | int64 | float32 | float64[source]¶
return the inverse hyperbolic sine of x, in radians.
- gt4py.cartesian.gtscript.atan(x) int32 | int64 | float32 | float64[source]¶
Return the arc tangent of x, in radians.
- gt4py.cartesian.gtscript.atanh(x) int32 | int64 | float32 | float64[source]¶
Return the inverse hyperbolic tangent of x, in radians.
- gt4py.cartesian.gtscript.cbrt(x) int32 | int64 | float32 | float64[source]¶
Return the cubic root of x.
- gt4py.cartesian.gtscript.ceil(x) int32 | int64 | float32 | float64[source]¶
Return the ceiling of x, the smallest integer greater than or equal to x.
- gt4py.cartesian.gtscript.compile_assert(expr)[source]¶
Assert that expr evaluates to True at compile-time.
- gt4py.cartesian.gtscript.cos(x) int32 | int64 | float32 | float64[source]¶
Return the cosine of x radians.
- gt4py.cartesian.gtscript.cosh(x) int32 | int64 | float32 | float64[source]¶
Return the hyperbolic cosine of x radians.
- gt4py.cartesian.gtscript.erf(x) int32 | int64 | float32 | float64[source]¶
Computes the error function of x.
- gt4py.cartesian.gtscript.erfc(x) int32 | int64 | float32 | float64[source]¶
Computes the complementary error function of x, which is 1.0 - erf(x).
- gt4py.cartesian.gtscript.exp(x) int32 | int64 | float32 | float64[source]¶
Return e raised to the power x, where e is the base of natural logarithms.
- class gt4py.cartesian.gtscript.float32(value=0, /)¶
Bases:
floatingSingle-precision floating-point number type, compatible with C
float.- Character code:
'f'- Canonical name:
numpy.single
- Alias on this platform (Linux x86_64):
numpy.float32: 32-bit-precision floating-point number type: sign bit, 8 bits exponent, 23 bits mantissa.
- as_integer_ratio()¶
Return a pair of integers, whose ratio is exactly equal to the original floating point number, and with a positive denominator. Raise OverflowError on infinities and a ValueError on NaNs.
>>> np.single(10.0).as_integer_ratio() (10, 1) >>> np.single(0.0).as_integer_ratio() (0, 1) >>> np.single(-.25).as_integer_ratio() (-1, 4)
- class gt4py.cartesian.gtscript.float64(value=0, /)¶
-
Double-precision floating-point number type, compatible with Python
floatand Cdouble.- Character code:
'd'- Canonical name:
numpy.double
- Alias on this platform (Linux x86_64):
numpy.float64: 64-bit precision floating-point number type: sign bit, 11 bits exponent, 52 bits mantissa.
- as_integer_ratio()¶
Return a pair of integers, whose ratio is exactly equal to the original floating point number, and with a positive denominator. Raise OverflowError on infinities and a ValueError on NaNs.
>>> np.double(10.0).as_integer_ratio() (10, 1) >>> np.double(0.0).as_integer_ratio() (0, 1) >>> np.double(-.25).as_integer_ratio() (-1, 4)
- gt4py.cartesian.gtscript.floor(x) int32 | int64 | float32 | float64[source]¶
Return the floor of x, the largest integer less than or equal to x.
- gt4py.cartesian.gtscript.gamma(x) int32 | int64 | float32 | float64[source]¶
Return the gamma function of x.
- gt4py.cartesian.gtscript.horizontal(*args)[source]¶
Define a block of code that is restricted to a set of regions in the parallel axes.
- class gt4py.cartesian.gtscript.int32(value=0, /)¶
Bases:
signedintegerSigned integer type, compatible with C
int.- Character code:
'i'- Canonical name:
numpy.intc
- Alias on this platform (Linux x86_64):
numpy.int32: 32-bit signed integer (
-2_147_483_648to2_147_483_647).
- class gt4py.cartesian.gtscript.int64(value=0, /)¶
Bases:
signedintegerSigned integer type, compatible with C
long.- Character code:
'l'- Canonical name:
numpy.long
- Alias on this platform (Linux x86_64):
numpy.int64: 64-bit signed integer (
-9_223_372_036_854_775_808to9_223_372_036_854_775_807).- Alias on this platform (Linux x86_64):
numpy.intp: Signed integer large enough to fit pointer, compatible with C
intptr_t.
- gt4py.cartesian.gtscript.interval(*args)[source]¶
Define the interval of computation in the ‘K’ sequential axis.
- gt4py.cartesian.gtscript.isfinite(x) int32 | int64 | float32 | float64[source]¶
Return True if x is neither an infinity nor a NaN, and False otherwise. (Note that 0.0 is considered finite.)
- gt4py.cartesian.gtscript.isinf(x) int32 | int64 | float32 | float64[source]¶
Return True if x is a positive or negative infinity, and False otherwise.
- gt4py.cartesian.gtscript.isnan(x) int32 | int64 | float32 | float64[source]¶
Return True if x is a NaN (not a number), and False otherwise.
- gt4py.cartesian.gtscript.lazy_stencil(backend=None, definition=None, *, build_info=None, dtypes=None, externals=None, format_source=True, name=None, rebuild=False, raise_if_not_cached=False, eager=False, check_syntax=True, **kwargs)[source]¶
Create a stencil object with deferred building and optional up-front syntax checking.
- Parameters:
backend (str) – Name of the implementation backend.
definition (None when used as a decorator, otherwise a function or a :class:`gt4py.StencilObject) – Function object defining the stencil.
build_info (dict, optional) – Dictionary used to store information about the stencil generation. (None by default).
dtypes (dict`[`str, dtype_definition], optional) – Specify dtypes for string keys in the argument annotations.
externals (dict, optional) – Specify values for otherwise unbound symbols.
format_source (bool, optional) – Format generated sources when possible (True by default).
name (str, optional) – The fully qualified name of the generated
StencilObject. If None, it will be set to the qualified name of the definition function. (None by default).rebuild (bool, optional) – Force rebuild of the
gt4py.StencilObjecteven if it is found in the cache. (False by default).raise_if_not_cached (bool, optional) – If this is True, the call will raise an exception if the stencil does not exist in the cache, or if the cache is inconsistent. (False by default).
eager (bool, optional) – If true do not defer stencil building and instead return the fully built raw implementation object.
check_syntax (bool, default=True, optional) – If true, build and cache the IR build stage already, which checks stencil definition syntax.
**kwargs (dict, optional) – Extra backend-specific options. Check the specific backend documentation for further information.
- Returns:
Wrapper around an instance of the dynamically-generated subclass of
gt4py.StencilObject. Defers the generation step until the last moment and allows syntax checking independently. Also gives access to a more fine grained generate / build process.- Return type:
gridtools.build.LazyStencil
- gt4py.cartesian.gtscript.log(x) int32 | int64 | float32 | float64[source]¶
Return the natural logarithm of x (to base e).
- gt4py.cartesian.gtscript.log10(x) int32 | int64 | float32 | float64[source]¶
Return the base-10 logarithm of x.
- gt4py.cartesian.gtscript.max(x, y) int32 | int64 | float32 | float64[source]¶
Return the largest of two or more arguments.
- gt4py.cartesian.gtscript.min(x, y) int32 | int64 | float32 | float64[source]¶
Return the smallest of two or more arguments.
- gt4py.cartesian.gtscript.mod(x, y) int32 | int64 | float32 | float64[source]¶
returns the first argument modulo the second one
- gt4py.cartesian.gtscript.round(x) int32 | int64 | float32 | float64[source]¶
Computes the nearest integer value to x, rounding halfway cases to even numbers.
Examples: -0.5 -> -0.0, 0.5 -> 0.0, 1.5 -> 2.0, 2.5 -> 2.0
This is in alignment with the IEEE754 standard python’s built-in round() function.
In contrast, round_away_from_zero() splits ties away from zero e.g. 2.5 will round to 3.0 and -0.5 will round to -1.0.
- gt4py.cartesian.gtscript.round_away_from_zero(x) int32 | int64 | float32 | float64[source]¶
Computes the nearest integer value to x, rounding halfway cases away from zero.
Examples: -0.5 -> -1.0, 0.5 -> 0.0, 1.5 -> 2.0, 2.5 -> 3.0
This is in alignment with C(++) and FORTRAN standard round functions that round away from zero by default.
In contrast, round() implements “Banker’s rounding” and splits ties to the nearest even integer, e.g. 1.5 and 2.5 both round to 2.0.
- gt4py.cartesian.gtscript.sin(x) int32 | int64 | float32 | float64[source]¶
Return the sine of x radians
- gt4py.cartesian.gtscript.sinh(x) int32 | int64 | float32 | float64[source]¶
Return the hyperbolic sine of x radians
- gt4py.cartesian.gtscript.sqrt(x) int32 | int64 | float32 | float64[source]¶
Return the square root of x.
- gt4py.cartesian.gtscript.stencil(backend, definition=None, *, build_info=None, dtypes=None, externals=None, format_source=True, name=None, rebuild=False, cache_settings=None, raise_if_not_cached=False, literal_int_precision=64, literal_float_precision=64, **kwargs)[source]¶
Generate an implementation of the stencil definition with the specified backend.
It can be used as a parametrized function decorator or as a regular function.
- Parameters:
backend (str) – Name of the implementation backend.
definition (None when used as a decorator, otherwise a function or a :class:`gt4py.StencilObject) – Function object defining the stencil.
build_info (dict, optional) – Dictionary used to store information about the stencil generation. (None by default). Possible key-value pairs include: - ‘symbol_info’: (Dict[str, SymbolInfo]) Dictionary of SymbolInfo objects - ‘parse_time’: (float) Frontend run time, e.g., parsing GTScript in seconds - ‘module_time’: (float) Python module generation time in seconds - ‘codegen_time’” (float) Backend-specific code generation time in seconds - ‘build_time’: (float) Compilation time, i.e., for non-Python backends in seconds - ‘load_time’: (float) Module load time for cached stencils in seconds
dtypes (dict`[`str, dtype_definition], optional) – Specify dtypes for string keys in the argument annotations.
externals (dict, optional) – Specify values for otherwise unbound symbols.
format_source (bool, optional) – Format generated sources when possible (True by default).
name (str, optional) – The fully qualified name of the generated
StencilObject. If None, it will be set to the qualified name of the definition function. (None by default).rebuild (bool, optional) – Force rebuild of the
gt4py.StencilObjecteven if it is found in the cache. (False by default).raise_if_not_cached (bool, optional) – If this is True, the call will raise an exception if the stencil does not exist in the cache, or if the cache is inconsistent. (False by default).
cache_settings (dict, optional) – Dictionary to configure cache (directory) settings (see
gt4py.cartesian.config.cache_settings). Possible key-value pairs: - root_path: (str) - dir_name: (str)literal_int_precision (int optional) – Value to define the precision of generic int casts. (System literal precision by default).
literal_float_precision (int optional) – Value to define the precision of generic float casts. (System literal precision by default).
**kwargs (dict, optional) – Extra backend-specific options. Check the specific backend documentation for further information.
- Returns:
Properly initialized instance of a dynamically-generated subclass of
gt4py.StencilObject.- Return type:
gridtools.StencilObject- Raises:
ValueError – If inconsistent arguments are specified.
Examples
TODO
- gt4py.cartesian.gtscript.tan(x) int32 | int64 | float32 | float64[source]¶
Return the tangent of x radians.
gt4py.cartesian.gtscript_imports module¶
GTScript import machinery.
Usage Example¶
from gt4py.cartesian import gtscript_imports
# simple usage
gtscript_imports.enable() # for allowing .gt.py everywhere in sys.path
# advanced usage
gtscript_imports.enable(
search_path=[<path1>, <path2>, ...], # for allowing only in search_path
generate_path=<mybuildpath>, # for generating python modules in a specific dir
in_source=False, # set True to generate python modules next to gtscript files
)
# scoped usage
with gtscript_imports.enabled():
import ...
- class gt4py.cartesian.gtscript_imports.GtsFinder(search_path: List[str | Path] | None = None, generate_path: str | Path | None = None, in_source: bool = False)[source]¶
Bases:
MetaPathFinderImplements the
importlib.abc.PathFinderprotocol.This finder is responsible for finding GTScript files within a set of search paths.
- Parameters:
search_path – Search path for gtscript sources, defaults to sys.path
generate_path – Path to generate py modules in. use a temp dir by default
in_source – If True, py modules are built next to the gtscript files (generate_path is ignored).
- _abc_impl = <_abc._abc_data object>¶
- find_spec(fullname: str, path=None, target=None) ModuleSpec | None[source]¶
Create a module spec for the first matching source file path.
- get_generate_path(src_file_path: Path) Path[source]¶
Find the out-of-source or in-source generate directory.
- iter_search_candidates(fullname: str, path: List[Path] | None) Generator[Path, None, None][source]¶
Iterate possible source file paths.
- load_module(fullname: str, path=None, target=None) ModuleType[source]¶
- class gt4py.cartesian.gtscript_imports.GtsLoader(fullname: str, path: Path, generate_at: Path)[source]¶
Bases:
SourceFileLoaderExtend
importlib.machinery.SourceFileLoaderfor GTScript files.Generate a python module for a GTScript file and use the super class to load that instead.
- create_module(spec: ModuleSpec) ModuleType[source]¶
Use default semantics for module creation.
- get_filename(fullname: str | None = None) str[source]¶
Generate a py module if an up to date one doesn’t exist yet.
Create the generation directory if necessary. Use file stats to check if the module needs to be updated.
- Parameters:
fullname (str, optional) – Dotted name corresponding to the gtscript module.
- Return type:
The file path of the generated py module as a string
- gt4py.cartesian.gtscript_imports._add_extension(path: Path, extension: str) Path[source]¶
Add an extension to the filename of a path.
gt4py.cartesian.lazy_stencil module¶
Stencil Object that allows for deferred building.
- class gt4py.cartesian.lazy_stencil.LazyStencil(builder: StencilBuilder)[source]¶
Bases:
objectA stencil object which defers compilation until it is needed.
Usually obtained using the
gt4py.gtscript.lazy_stencil()decorator, not directly instantiated. This is done by keeping a reference to agt4py.stencil_builder.StencilBuilderinstance.Compilation happens implicitly on first access to the implementation property. Low-level build utilities are accessible through the public
builderattribute.- __call__(*args: Any, **kwargs: Any) None[source]¶
Execute the stencil, building the stencil if necessary.
- property field_info: Dict[str, Any]¶
Access the compiled stencil object’s field_info attribute.
Triggers a build if necessary.
- implementation¶
Expose the compiled backend-specific python callable which executes the stencil.
Compilation happens at first access, the result is cached and should consecutively be accessible without overhead (not rigorously tested / benchmarked).
gt4py.cartesian.loader module¶
Implementation of stencil functions defined with symbolic Python functions.
This module contains functions to generate callable objects implementing a high-level stencil function definition using a specific code generating backend.
- gt4py.cartesian.loader.gtscript_loader(definition_func: StencilFunc, backend: str, build_options: BuildOptions, externals: dict[str, Any], dtypes: dict[type, type]) StencilObject[source]¶
- gt4py.cartesian.loader.load_stencil(frontend_name: str, backend_name: str, definition_func: StencilFunc, externals: dict[str, Any], dtypes: dict[type, type], build_options: BuildOptions) type[StencilObject][source]¶
Generate a new class object implementing the provided definition.
gt4py.cartesian.stencil_builder module¶
- class gt4py.cartesian.stencil_builder.StencilBuilder(definition_func: AnyStencilFunc, *, backend: str | type[BackendType] | None = None, options: BuildOptions | None = None, frontend: type[FrontendType] | None = None)[source]¶
Bases:
objectOrchestrates code generation and compilation.
- Parameters:
definition_func – Stencil definition function, before or after annotation.
backend – Backend class to be instantiated for this build
options – Build options, defaults to name and module of the
definition_funcfrontend – Frontend class to be used
Notes
Backends can use the
with_backend_data()method and thebackend_data()property to set and retrieve backend specific information for use in later steps.- build() type[StencilObject][source]¶
Generate, compile and/or load everything necessary to provide a usable stencil class.
- classmethod default_options_dict(definition_func: StencilFunc | AnnotatedStencilFunc) dict[str, Any][source]¶
- property definition: AnnotatedStencilFunc¶
- property gtir_pipeline: GtirPipeline¶
- classmethod name_to_options_args(name: str | None) dict[str, str][source]¶
Check for qualified name, extract also module option in that case.
- property stencil_source: str¶
Read the stencil source from the written module file.
- Raises:
FileNotFoundError – if the file has not been written yet
- with_backend(backend_name: str) StencilBuilder[source]¶
Fluidly set the backend type from backend name.
- Parameters:
backend_name – Name of the backend type.
Notes
Resets all cached build data.
- with_caching(caching_strategy_name: str, *args: Any, **kwargs: Any) StencilBuilder[source]¶
Fluidly set the caching strategy from the name.
- Parameters:
caching_strategy_name – Name of the caching strategy to be passed to the factory.
args – Passed through to the caching strategy factory
kwargs – Passed through to the caching strategy factory
Notes
Resets all cached build data.
- with_externals(externals: dict[str, Any]) StencilBuilder[source]¶
Fluidly set externals for this build.
Resets all cached build data.
- with_options(*, name: str, module: str, **kwargs: Any) StencilBuilder[source]¶
Fluidly set the build options.
- Parameters:
name – Name of the stencil
module – qualified module name of the stencil’s module
kwargs – passed through to the options instance
- with_root_pkg_name(name: str) StencilBuilder[source]¶
gt4py.cartesian.stencil_object module¶
- class gt4py.cartesian.stencil_object.ArgsInfo(device: 'str', array: 'FieldType', original_object: 'Any | None' = None, origin: 'tuple[int, ...] | None' = None, dimensions: 'tuple[str, ...] | None' = None)[source]¶
Bases:
object- array: FieldType¶
- class gt4py.cartesian.stencil_object.FrozenStencil(stencil_object: StencilObject, origin: dict[str, tuple[int, ...]], domain: tuple[int, ...])[source]¶
Bases:
objectStencil with pre-computed domain and origin for each field argument.
- stencil_object: StencilObject¶
- class gt4py.cartesian.stencil_object.StencilObject(*args, **kwargs)[source]¶
Bases:
ABCGeneric singleton implementation of a stencil callable.
This class is used as base class for specific subclass generated at run-time for any stencil definition and a unique set of external symbols. Instances of this class do not contain state and thus it is implemented as a singleton: only one instance per subclass is actually allocated (and it is immutable).
The callable interface is the same of the stencil definition function, with some extra keyword arguments.
- Keyword Arguments:
domain (Sequence of int, optional) – Shape of the computation domain. If None, it will be used the largest feasible domain according to the provided input fields and origin values (None by default).
origin ([int * ndims] or {‘field_name’: [int * ndims]}, optional) – If a single offset is passed, it will be used for all fields. If a dict is passed, there could be an entry for each field. A special key ‘_all_’ will represent the value to be used for all the fields not explicitly defined. If None is passed or it is not possible to assign a value to some field according to the previous rule, the value will be inferred from the boundary attribute of the field_info dict. Note that the function checks if the origin values are at least equal to the boundary attribute of that field, so a 0-based origin will only be acceptable for fields with a 0-area support region.
exec_info (dict, optional) – Dictionary used to store information about the stencil execution. (None by default). If the dictionary contains the magic key ‘__aggregate_data’ and it evaluates to True, the dictionary is populated with a nested dictionary per class containing different performance statistics. These include the stencil calls count, the cumulative time spent in all stencil calls, and the actual time spent in carrying out the computations.
- _abc_impl = <_abc._abc_data object>¶
- _call_run(field_args: dict[str, FieldType], parameter_args: dict[str, Any], domain: tuple[int, ...] | None, origin: OriginType | None, *, validate_args: bool = True, exec_info: dict[str, Any] | None = None) None[source]¶
Check and preprocess the provided arguments (called by
StencilObjectsubclasses).Note that this function will always try to expand simple parameter values to complete data structures by repeating the same value as many times as needed.
- Parameters:
field_args (dict) – Mapping from field names to actually passed data arrays. This parameter encapsulates *args in the actual stencil subclass by doing: {input_name[i]: arg for i, arg in enumerate(args)}
parameter_args (dict) – Mapping from parameter names to actually passed parameter values. This parameter encapsulates **kwargs in the actual stencil subclass by doing: {name: value for name, value in kwargs.items()}
Check
StencilObjectfor a full specification of the domain, origin and exec_info keyword arguments.- Return type:
None
- Raises:
ValueError – If invalid data or inconsistent options are specified.
- _domain_origin_cache: ClassVar[dict[int, tuple[tuple[int, ...], dict[str, tuple[int, ...]]]]]¶
Stores domain/origin pairs that have been used by hash.
- static _get_max_domain(array_infos: dict[str, ArgsInfo | None], domain_infos: DomainInfo, field_infos: dict[str, FieldInfo], origin: dict[str, tuple[int, ...]], *, squeeze: bool = True) Shape[source]¶
Return the maximum domain size possible.
- Parameters:
field_args – Mapping from field names to actually passed data arrays.
origin – The origin for each field.
squeeze – Convert non-used domain dimensions to singleton dimensions.
- Returns:
`Shape`
- Return type:
the maximum domain size.
- static _make_origin_dict(origin: dict[str, tuple[int, ...]] | tuple[int, ...] | int | None) dict[str, tuple[int, ...]][source]¶
- static _normalize_origins(array_infos: dict[str, ArgsInfo | None], field_infos: dict[str, FieldInfo], origin: tuple[int, int, int] | dict[str, tuple[int, ...]] | None) dict[str, tuple[int, ...]][source]¶
- _validate_args(arg_infos: dict[str, ArgsInfo | None], param_args: dict[str, Any], domain: tuple[int, ...], origin: dict[str, tuple[int, ...]]) None[source]¶
Validate input arguments to _call_run.
- Raises:
ValueError – If invalid data or inconsistent options are specified.
TypeError – If an incorrect field or parameter data type is passed.
- abstract property domain_info: DomainInfo¶
- freeze(*, origin: dict[str, tuple[int, ...]], domain: tuple[int, ...]) FrozenStencil[source]¶
Return a StencilObject wrapper with a fixed domain and origin for each argument.
- Parameters:
origin (dict) – The origin for each Field argument.
domain (Sequence of int) – The compute domain shape for the frozen stencil.
Notes
Both origin and domain arguments should be compatible with the domain and origin specification defined in
StencilObject.- Returns:
The stencil wrapper. This should be called with the regular stencil arguments, but the field origins and domain cannot be changed. Note, no checking of origin or domain occurs at call time so it is the users responsibility to ensure correct usage.
- Return type:
FrozenStencil
- abstract property parameter_info: dict[str, ParameterInfo]¶
- gt4py.cartesian.stencil_object._compute_domain_origin_cache_key(field_args_info: dict[str, ArgsInfo | None], parameter_args: dict[str, Number | None], domain: tuple[int, ...] | None, origin: tuple[int, int, int] | dict[str, tuple[int, ...]] | None) int[source]¶
gt4py.cartesian.type_hints module¶
Module contents¶
Python API to develop performance portable applications for weather and climate.
- class gt4py.cartesian.StencilObject(*args, **kwargs)[source]¶
Bases:
ABCGeneric singleton implementation of a stencil callable.
This class is used as base class for specific subclass generated at run-time for any stencil definition and a unique set of external symbols. Instances of this class do not contain state and thus it is implemented as a singleton: only one instance per subclass is actually allocated (and it is immutable).
The callable interface is the same of the stencil definition function, with some extra keyword arguments.
- Keyword Arguments:
domain (Sequence of int, optional) – Shape of the computation domain. If None, it will be used the largest feasible domain according to the provided input fields and origin values (None by default).
origin ([int * ndims] or {‘field_name’: [int * ndims]}, optional) – If a single offset is passed, it will be used for all fields. If a dict is passed, there could be an entry for each field. A special key ‘_all_’ will represent the value to be used for all the fields not explicitly defined. If None is passed or it is not possible to assign a value to some field according to the previous rule, the value will be inferred from the boundary attribute of the field_info dict. Note that the function checks if the origin values are at least equal to the boundary attribute of that field, so a 0-based origin will only be acceptable for fields with a 0-area support region.
exec_info (dict, optional) – Dictionary used to store information about the stencil execution. (None by default). If the dictionary contains the magic key ‘__aggregate_data’ and it evaluates to True, the dictionary is populated with a nested dictionary per class containing different performance statistics. These include the stencil calls count, the cumulative time spent in all stencil calls, and the actual time spent in carrying out the computations.
- _abc_impl = <_abc._abc_data object>¶
- _call_run(field_args: dict[str, FieldType], parameter_args: dict[str, Any], domain: tuple[int, ...] | None, origin: OriginType | None, *, validate_args: bool = True, exec_info: dict[str, Any] | None = None) None[source]¶
Check and preprocess the provided arguments (called by
StencilObjectsubclasses).Note that this function will always try to expand simple parameter values to complete data structures by repeating the same value as many times as needed.
- Parameters:
field_args (dict) – Mapping from field names to actually passed data arrays. This parameter encapsulates *args in the actual stencil subclass by doing: {input_name[i]: arg for i, arg in enumerate(args)}
parameter_args (dict) – Mapping from parameter names to actually passed parameter values. This parameter encapsulates **kwargs in the actual stencil subclass by doing: {name: value for name, value in kwargs.items()}
Check
StencilObjectfor a full specification of the domain, origin and exec_info keyword arguments.- Return type:
None
- Raises:
ValueError – If invalid data or inconsistent options are specified.
- _domain_origin_cache: ClassVar[dict[int, tuple[tuple[int, ...], dict[str, tuple[int, ...]]]]]¶
Stores domain/origin pairs that have been used by hash.
- static _get_max_domain(array_infos: dict[str, ArgsInfo | None], domain_infos: DomainInfo, field_infos: dict[str, FieldInfo], origin: dict[str, tuple[int, ...]], *, squeeze: bool = True) Shape[source]¶
Return the maximum domain size possible.
- Parameters:
field_args – Mapping from field names to actually passed data arrays.
origin – The origin for each field.
squeeze – Convert non-used domain dimensions to singleton dimensions.
- Returns:
`Shape`
- Return type:
the maximum domain size.
- static _make_origin_dict(origin: dict[str, tuple[int, ...]] | tuple[int, ...] | int | None) dict[str, tuple[int, ...]][source]¶
- static _normalize_origins(array_infos: dict[str, ArgsInfo | None], field_infos: dict[str, FieldInfo], origin: tuple[int, int, int] | dict[str, tuple[int, ...]] | None) dict[str, tuple[int, ...]][source]¶
- _validate_args(arg_infos: dict[str, ArgsInfo | None], param_args: dict[str, Any], domain: tuple[int, ...], origin: dict[str, tuple[int, ...]]) None[source]¶
Validate input arguments to _call_run.
- Raises:
ValueError – If invalid data or inconsistent options are specified.
TypeError – If an incorrect field or parameter data type is passed.
- abstract property domain_info: DomainInfo¶
- freeze(*, origin: dict[str, tuple[int, ...]], domain: tuple[int, ...]) FrozenStencil[source]¶
Return a StencilObject wrapper with a fixed domain and origin for each argument.
- Parameters:
origin (dict) – The origin for each Field argument.
domain (Sequence of int) – The compute domain shape for the frozen stencil.
Notes
Both origin and domain arguments should be compatible with the domain and origin specification defined in
StencilObject.- Returns:
The stencil wrapper. This should be called with the regular stencil arguments, but the field origins and domain cannot be changed. Note, no checking of origin or domain occurs at call time so it is the users responsibility to ensure correct usage.
- Return type:
FrozenStencil
- abstract property parameter_info: dict[str, ParameterInfo]¶