nd2py.core package#
- class nd2py.core.Empty(nettype: Literal['node', 'edge', 'scalar'] | None = None)[source]#
Bases:
Symbol- n_operands = 0#
- __init__(nettype: Literal['node', 'edge', 'scalar'] | None = None)[source]#
Initialize a Symbol node.
This constructor sets the nettype, sanitizes and attaches child operands, and then triggers a nettype inference pass on the whole expression tree.
- Parameters:
*operands – Child operands of this symbol. The number of operands must match
n_operandsof the concrete subclass. Non-symbol scalar values are automatically wrapped asNumbersymbols.nettype (Optional[NetType | Set[NetType]]) – Nettype constraint for this symbol, such as
"node","edge", or"scalar", or a set of allowed nettypes. If provided, it is propagated through the tree byinfer_nettype().
- map_nettype() Literal['node', 'edge', 'scalar'] | None[source]#
Default nettype mapping rule for symbol subclasses.
The default behavior enforces that
"node"and"edge"nettypes cannot be mixed. If only scalars are present, the result is"scalar"; otherwise it follows the presence of"node"or"edge".- Parameters:
*children_nettypes (NetType) – Nettypes of the child operands.
- Returns:
Inferred nettype for the parent symbol, or
Noneif the combination is invalid or cannot be determined.- Return type:
Optional[NetType]
- Raises:
ValueError – If the number of child nettypes does not match
cls.n_operands.
- class nd2py.core.Csch(*operands, nettype: Literal['node', 'edge', 'scalar'] | Set[Literal['node', 'edge', 'scalar']] | None = None)[source]#
Bases:
Symbol- n_operands = 1#
- class nd2py.core.Sour(*operands, nettype: Literal['node', 'edge', 'scalar'] | Set[Literal['node', 'edge', 'scalar']] | None = None)[source]#
Bases:
Symbol- n_operands = 1#
- classmethod map_nettype(*children_nettypes: Literal['node', 'edge', 'scalar']) Literal['node', 'edge', 'scalar'] | None[source]#
Default nettype mapping rule for symbol subclasses.
The default behavior enforces that
"node"and"edge"nettypes cannot be mixed. If only scalars are present, the result is"scalar"; otherwise it follows the presence of"node"or"edge".- Parameters:
*children_nettypes (NetType) – Nettypes of the child operands.
- Returns:
Inferred nettype for the parent symbol, or
Noneif the combination is invalid or cannot be determined.- Return type:
Optional[NetType]
- Raises:
ValueError – If the number of child nettypes does not match
cls.n_operands.
- class nd2py.core.Csc(*operands, nettype: Literal['node', 'edge', 'scalar'] | Set[Literal['node', 'edge', 'scalar']] | None = None)[source]#
Bases:
Symbol- n_operands = 1#
- class nd2py.core.Cot(*operands, nettype: Literal['node', 'edge', 'scalar'] | Set[Literal['node', 'edge', 'scalar']] | None = None)[source]#
Bases:
Symbol- n_operands = 1#
- class nd2py.core.Add(*operands, nettype: Literal['node', 'edge', 'scalar'] | Set[Literal['node', 'edge', 'scalar']] | None = None)[source]#
Bases:
Symbol- n_operands = 2#
- class nd2py.core.LogAbs(*operands, nettype: Literal['node', 'edge', 'scalar'] | Set[Literal['node', 'edge', 'scalar']] | None = None)[source]#
Bases:
Symbol- n_operands = 1#
- class nd2py.core.Rgga(*operands, nettype: Literal['node', 'edge', 'scalar'] | Set[Literal['node', 'edge', 'scalar']] | None = None)[source]#
Bases:
Aggr
- class nd2py.core.Sec(*operands, nettype: Literal['node', 'edge', 'scalar'] | Set[Literal['node', 'edge', 'scalar']] | None = None)[source]#
Bases:
Symbol- n_operands = 1#
- class nd2py.core.Identity(*operands, nettype: Literal['node', 'edge', 'scalar'] | Set[Literal['node', 'edge', 'scalar']] | None = None)[source]#
Bases:
Symbol- n_operands = 1#
- class nd2py.core.Cosh(*operands, nettype: Literal['node', 'edge', 'scalar'] | Set[Literal['node', 'edge', 'scalar']] | None = None)[source]#
Bases:
Symbol- n_operands = 1#
- class nd2py.core.FoldConstant(fold_fitable: bool = True, fold_constant: bool = True)[source]#
Bases:
Visitor访问器,用于将表达式中不含 Number 的子表达式折叠为 Constant。
- class nd2py.core.Min(*operands, nettype: Literal['node', 'edge', 'scalar'] | Set[Literal['node', 'edge', 'scalar']] | None = None)[source]#
Bases:
Symbol- n_operands = 2#
- nd2py.core.Constant(value, nettype: Literal['node', 'edge', 'scalar'] = 'scalar') Number[source]#
一个工厂函数,返回一个 fitable 为 False 的 Number 对象。
- nd2py.core.parse(expression: str, variables: Dict[str, Symbol] = None, callables: Dict[str, callable] = None) Symbol[source]#
- nd2py.core.warn_once(warn_name, maxsize=None)[source]#
This function is used to limit the number of times a warning is issued
- nd2py.core.setup_lazy_imports(module_name: str, import_mapping: Dict[str, Tuple[str, str]])[source]#
Set up lazy imports for a module’s
__init__.py.Returns
(__getattr__, __dir__, __all__)which should be assigned at the module level so thatfrom package import OptionalClassworks without importing the optional dependency until it is actually needed.- Parameters:
module_name – The
__name__of the calling module.import_mapping – A dict mapping attribute names to
(module_path, requires)tuples. module_path is a relative import path (e.g.".torch_calc") and requires is the optional-dependency group name (e.g."nn") shown in the error message when the dependency is missing.
Usage:
# __init__.py from .core import CoreClass from ..utils.lazy_loader import setup_lazy_imports if TYPE_CHECKING: from .optional import OptionalClass __getattr__, __dir__, __all__ = setup_lazy_imports(__name__, { "OptionalClass": (".optional", "nn"), })
- class nd2py.core.Inv(*operands, nettype: Literal['node', 'edge', 'scalar'] | Set[Literal['node', 'edge', 'scalar']] | None = None)[source]#
Bases:
Symbol- n_operands = 1#
- class nd2py.core.Aggr(*operands, nettype: Literal['node', 'edge', 'scalar'] | Set[Literal['node', 'edge', 'scalar']] | None = None)[source]#
Bases:
Symbol- n_operands = 1#
- classmethod map_nettype(*children_nettypes: Literal['node', 'edge', 'scalar']) Literal['node', 'edge', 'scalar'] | None[source]#
Default nettype mapping rule for symbol subclasses.
The default behavior enforces that
"node"and"edge"nettypes cannot be mixed. If only scalars are present, the result is"scalar"; otherwise it follows the presence of"node"or"edge".- Parameters:
*children_nettypes (NetType) – Nettypes of the child operands.
- Returns:
Inferred nettype for the parent symbol, or
Noneif the combination is invalid or cannot be determined.- Return type:
Optional[NetType]
- Raises:
ValueError – If the number of child nettypes does not match
cls.n_operands.
- class nd2py.core.Cos(*operands, nettype: Literal['node', 'edge', 'scalar'] | Set[Literal['node', 'edge', 'scalar']] | None = None)[source]#
Bases:
Symbol- n_operands = 1#
- class nd2py.core.Regular(*operands, nettype: Literal['node', 'edge', 'scalar'] | Set[Literal['node', 'edge', 'scalar']] | None = None)[source]#
Bases:
Symbol- n_operands = 2#
- class nd2py.core.Pow(*operands, nettype: Literal['node', 'edge', 'scalar'] | Set[Literal['node', 'edge', 'scalar']] | None = None)[source]#
Bases:
Symbol- n_operands = 2#
- nd2py.core.variables(vars, *args, **kwargs)[source]#
一个工厂函数,返回一个或多个 Variable 对象。 如果 vars 中包含空格,则认为是多个变量的名字,并返回一个列表;否则认为是单个变量的名字,并返回一个 Variable 对象。
- class nd2py.core.Number(value, nettype: Literal['node', 'edge', 'scalar'] = 'scalar', fitable=None)[source]#
Bases:
Symbol- n_operands = 0#
- __init__(value, nettype: Literal['node', 'edge', 'scalar'] = 'scalar', fitable=None)[source]#
Initialize a Symbol node.
This constructor sets the nettype, sanitizes and attaches child operands, and then triggers a nettype inference pass on the whole expression tree.
- Parameters:
*operands – Child operands of this symbol. The number of operands must match
n_operandsof the concrete subclass. Non-symbol scalar values are automatically wrapped asNumbersymbols.nettype (Optional[NetType | Set[NetType]]) – Nettype constraint for this symbol, such as
"node","edge", or"scalar", or a set of allowed nettypes. If provided, it is propagated through the tree byinfer_nettype().
- map_nettype() Literal['node', 'edge', 'scalar'] | None[source]#
Default nettype mapping rule for symbol subclasses.
The default behavior enforces that
"node"and"edge"nettypes cannot be mixed. If only scalars are present, the result is"scalar"; otherwise it follows the presence of"node"or"edge".- Parameters:
*children_nettypes (NetType) – Nettypes of the child operands.
- Returns:
Inferred nettype for the parent symbol, or
Noneif the combination is invalid or cannot be determined.- Return type:
Optional[NetType]
- Raises:
ValueError – If the number of child nettypes does not match
cls.n_operands.
- get_nettype_range() Set[Literal['node', 'edge', 'scalar']][source]#
获取此节点可能产生的所有 nettype 值域,并在首次调用时缓存到类属性中。
- property nettype_range: Set[Literal['node', 'edge', 'scalar']]#
获取此节点可能产生的所有 nettype 值域,并在首次调用时缓存到类属性中。
- class nd2py.core.Pow2(*operands, nettype: Literal['node', 'edge', 'scalar'] | Set[Literal['node', 'edge', 'scalar']] | None = None)[source]#
Bases:
Symbol- n_operands = 1#
- class nd2py.core.Neg(*operands, nettype: Literal['node', 'edge', 'scalar'] | Set[Literal['node', 'edge', 'scalar']] | None = None)[source]#
Bases:
Symbol- n_operands = 1#
- class nd2py.core.Div(*operands, nettype: Literal['node', 'edge', 'scalar'] | Set[Literal['node', 'edge', 'scalar']] | None = None)[source]#
Bases:
Symbol- n_operands = 2#
- class nd2py.core.Symbol(*operands, nettype: Literal['node', 'edge', 'scalar'] | Set[Literal['node', 'edge', 'scalar']] | None = None)[source]#
Bases:
NetTypeMixin,TreeMixin,SymbolAPIMixin- n_operands = None#
- __init__(*operands, nettype: Literal['node', 'edge', 'scalar'] | Set[Literal['node', 'edge', 'scalar']] | None = None)[source]#
Initialize a Symbol node.
This constructor sets the nettype, sanitizes and attaches child operands, and then triggers a nettype inference pass on the whole expression tree.
- Parameters:
*operands – Child operands of this symbol. The number of operands must match
n_operandsof the concrete subclass. Non-symbol scalar values are automatically wrapped asNumbersymbols.nettype (Optional[NetType | Set[NetType]]) – Nettype constraint for this symbol, such as
"node","edge", or"scalar", or a set of allowed nettypes. If provided, it is propagated through the tree byinfer_nettype().
- copy()[source]#
Return a deep copy of this symbol.
The copied symbol has the same tree structure and values as the original but does not share
parentlinks, so it can be safely inserted into a different expression tree.- Returns:
A deep copy of the current symbol.
- Return type:
- get_numbers(fitable_only: bool = False, float_only: bool = False, scalar_only: bool = False) List[Number][source]#
Collect all
Numbernodes contained in this symbol.Traverses the expression tree in preorder and returns all numeric nodes that satisfy the given filters.
- Parameters:
fitable_only (bool, optional) – If True, return only numbers marked as fitable (trainable) parameters. Defaults to False.
float_only (bool, optional) – If True, exclude integer-like values (for example exponents that should remain fixed). Defaults to False.
scalar_only (bool, optional) – If True, only consider scalar numbers (nettype
"scalar"). Defaults to False.
- Returns:
List of numeric symbol nodes that match the filters.
- Return type:
List[Number]
- get_parameters(fitable_only: bool = False, float_only: bool = False) List[float][source]#
Return numeric parameter values contained in this symbol.
This is a convenience wrapper over
get_numbers()that extracts the underlying scalar values fromNumbernodes.- Parameters:
fitable_only (bool, optional) – If True, return only parameters associated with fitable numbers. Defaults to False.
float_only (bool, optional) – If True, exclude integer-like parameters. Defaults to False.
- Returns:
Flat list of parameter values in traversal order.
- Return type:
List[float]
- set_parameters(params: List[float], fitable_only: bool = False, float_only: bool = False)[source]#
Assign new numeric parameter values to this symbol.
The values in
paramsare consumed in the same order as produced byget_parameters()with the same filter options.- Parameters:
params (List[float]) – New parameter values to assign.
fitable_only (bool, optional) – If True, only update fitable parameters and leave others unchanged. Defaults to False.
float_only (bool, optional) – If True, only update non-integer parameters. Defaults to False.
- Raises:
ValueError – If the length of
paramsdoes not match the number of parameters selected by the filters.
- classmethod map_nettype(*children_nettypes: Literal['node', 'edge', 'scalar']) Literal['node', 'edge', 'scalar'] | None[source]#
Default nettype mapping rule for symbol subclasses.
The default behavior enforces that
"node"and"edge"nettypes cannot be mixed. If only scalars are present, the result is"scalar"; otherwise it follows the presence of"node"or"edge".- Parameters:
*children_nettypes (NetType) – Nettypes of the child operands.
- Returns:
Inferred nettype for the parent symbol, or
Noneif the combination is invalid or cannot be determined.- Return type:
Optional[NetType]
- Raises:
ValueError – If the number of child nettypes does not match
cls.n_operands.
- class nd2py.core.BFGSFit(*args: Any, **kwargs: Any)[source]#
Bases:
BaseEstimator,RegressorMixin
- class nd2py.core.Variable(name, nettype: Literal['node', 'edge', 'scalar'] = 'scalar')[source]#
Bases:
Symbol- n_operands = 0#
- __init__(name, nettype: Literal['node', 'edge', 'scalar'] = 'scalar')[source]#
Initialize a Symbol node.
This constructor sets the nettype, sanitizes and attaches child operands, and then triggers a nettype inference pass on the whole expression tree.
- Parameters:
*operands – Child operands of this symbol. The number of operands must match
n_operandsof the concrete subclass. Non-symbol scalar values are automatically wrapped asNumbersymbols.nettype (Optional[NetType | Set[NetType]]) – Nettype constraint for this symbol, such as
"node","edge", or"scalar", or a set of allowed nettypes. If provided, it is propagated through the tree byinfer_nettype().
- map_nettype() Literal['node', 'edge', 'scalar'] | None[source]#
Default nettype mapping rule for symbol subclasses.
The default behavior enforces that
"node"and"edge"nettypes cannot be mixed. If only scalars are present, the result is"scalar"; otherwise it follows the presence of"node"or"edge".- Parameters:
*children_nettypes (NetType) – Nettypes of the child operands.
- Returns:
Inferred nettype for the parent symbol, or
Noneif the combination is invalid or cannot be determined.- Return type:
Optional[NetType]
- Raises:
ValueError – If the number of child nettypes does not match
cls.n_operands.
- get_nettype_range() Set[Literal['node', 'edge', 'scalar']][source]#
获取此节点可能产生的所有 nettype 值域,并在首次调用时缓存到类属性中。
- property nettype_range: Set[Literal['node', 'edge', 'scalar']]#
获取此节点可能产生的所有 nettype 值域,并在首次调用时缓存到类属性中。
- class nd2py.core.Sub(*operands, nettype: Literal['node', 'edge', 'scalar'] | Set[Literal['node', 'edge', 'scalar']] | None = None)[source]#
Bases:
Symbol- n_operands = 2#
- class nd2py.core.Arcsin(*operands, nettype: Literal['node', 'edge', 'scalar'] | Set[Literal['node', 'edge', 'scalar']] | None = None)[source]#
Bases:
Symbol- n_operands = 1#
- nd2py.core.from_postorder(nodes: List[Symbol | Type[Symbol]], **kwargs) Symbol[source]#
Construct a Symbol tree from a list of Symbols in postorder traversal order.
- class nd2py.core.Sqrt(*operands, nettype: Literal['node', 'edge', 'scalar'] | Set[Literal['node', 'edge', 'scalar']] | None = None)[source]#
Bases:
Symbol- n_operands = 1#
- class nd2py.core.SqrtAbs(*operands, nettype: Literal['node', 'edge', 'scalar'] | Set[Literal['node', 'edge', 'scalar']] | None = None)[source]#
Bases:
Symbol- n_operands = 1#
- class nd2py.core.Log(*operands, nettype: Literal['node', 'edge', 'scalar'] | Set[Literal['node', 'edge', 'scalar']] | None = None)[source]#
Bases:
Symbol- n_operands = 1#
- class nd2py.core.Arctan(*operands, nettype: Literal['node', 'edge', 'scalar'] | Set[Literal['node', 'edge', 'scalar']] | None = None)[source]#
Bases:
Symbol- n_operands = 1#
- class nd2py.core.Readout(*operands, nettype: Literal['node', 'edge', 'scalar'] | Set[Literal['node', 'edge', 'scalar']] | None = None)[source]#
Bases:
Symbol- n_operands = 1#
- classmethod map_nettype(*children_nettypes: Literal['node', 'edge', 'scalar']) Literal['node', 'edge', 'scalar'] | None[source]#
Default nettype mapping rule for symbol subclasses.
The default behavior enforces that
"node"and"edge"nettypes cannot be mixed. If only scalars are present, the result is"scalar"; otherwise it follows the presence of"node"or"edge".- Parameters:
*children_nettypes (NetType) – Nettypes of the child operands.
- Returns:
Inferred nettype for the parent symbol, or
Noneif the combination is invalid or cannot be determined.- Return type:
Optional[NetType]
- Raises:
ValueError – If the number of child nettypes does not match
cls.n_operands.
- class nd2py.core.Tanh(*operands, nettype: Literal['node', 'edge', 'scalar'] | Set[Literal['node', 'edge', 'scalar']] | None = None)[source]#
Bases:
Symbol- n_operands = 1#
- class nd2py.core.Sech(*operands, nettype: Literal['node', 'edge', 'scalar'] | Set[Literal['node', 'edge', 'scalar']] | None = None)[source]#
Bases:
Symbol- n_operands = 1#
- class nd2py.core.Max(*operands, nettype: Literal['node', 'edge', 'scalar'] | Set[Literal['node', 'edge', 'scalar']] | None = None)[source]#
Bases:
Symbol- n_operands = 2#
- class nd2py.core.Tan(*operands, nettype: Literal['node', 'edge', 'scalar'] | Set[Literal['node', 'edge', 'scalar']] | None = None)[source]#
Bases:
Symbol- n_operands = 1#
- class nd2py.core.Abs(*operands, nettype: Literal['node', 'edge', 'scalar'] | Set[Literal['node', 'edge', 'scalar']] | None = None)[source]#
Bases:
Symbol- n_operands = 1#
- class nd2py.core.Sinh(*operands, nettype: Literal['node', 'edge', 'scalar'] | Set[Literal['node', 'edge', 'scalar']] | None = None)[source]#
Bases:
Symbol- n_operands = 1#
- class nd2py.core.Arccos(*operands, nettype: Literal['node', 'edge', 'scalar'] | Set[Literal['node', 'edge', 'scalar']] | None = None)[source]#
Bases:
Symbol- n_operands = 1#
- class nd2py.core.FixNetType[source]#
Bases:
Visitor- generic_visit(node, *args, **kwargs) _Type[source]#
direction = ‘top-down’: 每个 node 的 nettype 由 kwargs[‘nettype’] 决定。 direction = ‘bottom-up’: 每个 node 的 nettype 由其 operands 决定。只保证每个 node 运算不会出错即可,不需要对 kwargs[‘nettype’] 负责
- visit_Add(node, *args, **kwargs) _Type#
- visit_Sub(node, *args, **kwargs) _Type#
- visit_Mul(node, *args, **kwargs) _Type#
- visit_Div(node, *args, **kwargs) _Type#
- visit_Pow(node, *args, **kwargs) _Type#
- visit_Max(node, *args, **kwargs) _Type#
- visit_Min(node, *args, **kwargs) _Type#
- visit_Rgga(node, *args, **kwargs) _Type#
- visit_Targ(node, *args, **kwargs) _Type#
- class nd2py.core.Sigmoid(*operands, nettype: Literal['node', 'edge', 'scalar'] | Set[Literal['node', 'edge', 'scalar']] | None = None)[source]#
Bases:
Symbol- n_operands = 1#
- class nd2py.core.Mul(*operands, nettype: Literal['node', 'edge', 'scalar'] | Set[Literal['node', 'edge', 'scalar']] | None = None)[source]#
Bases:
Symbol- n_operands = 2#
- class nd2py.core.Pow3(*operands, nettype: Literal['node', 'edge', 'scalar'] | Set[Literal['node', 'edge', 'scalar']] | None = None)[source]#
Bases:
Symbol- n_operands = 1#
- class nd2py.core.Exp(*operands, nettype: Literal['node', 'edge', 'scalar'] | Set[Literal['node', 'edge', 'scalar']] | None = None)[source]#
Bases:
Symbol- n_operands = 1#
- class nd2py.core.Targ(*operands, nettype: Literal['node', 'edge', 'scalar'] | Set[Literal['node', 'edge', 'scalar']] | None = None)[source]#
Bases:
Sour
- nd2py.core.from_preorder(nodes: List[Symbol | Type[Symbol]], **kwargs) Symbol[source]#
Construct a Symbol tree from a list of Symbols in preorder traversal order.
- class nd2py.core.Sin(*operands, nettype: Literal['node', 'edge', 'scalar'] | Set[Literal['node', 'edge', 'scalar']] | None = None)[source]#
Bases:
Symbol- n_operands = 1#
- class nd2py.core.Coth(*operands, nettype: Literal['node', 'edge', 'scalar'] | Set[Literal['node', 'edge', 'scalar']] | None = None)[source]#
Bases:
Symbol- n_operands = 1#
Subpackages#
- nd2py.core.basic package
- nd2py.core.calc package
NumpyCalcNumpyCalc.generic_visit()NumpyCalc.visit_Empty()NumpyCalc.visit_Number()NumpyCalc.visit_Variable()NumpyCalc.visit_Add()NumpyCalc.visit_Sub()NumpyCalc.visit_Mul()NumpyCalc.visit_Div()NumpyCalc.visit_Pow()NumpyCalc.visit_Max()NumpyCalc.visit_Min()NumpyCalc.visit_Identity()NumpyCalc.visit_Sin()NumpyCalc.visit_Cos()NumpyCalc.visit_Tan()NumpyCalc.visit_Sec()NumpyCalc.visit_Csc()NumpyCalc.visit_Cot()NumpyCalc.visit_Log()NumpyCalc.visit_LogAbs()NumpyCalc.visit_Exp()NumpyCalc.visit_Abs()NumpyCalc.visit_Neg()NumpyCalc.visit_Inv()NumpyCalc.visit_Sqrt()NumpyCalc.visit_SqrtAbs()NumpyCalc.visit_Pow2()NumpyCalc.visit_Pow3()NumpyCalc.visit_Arcsin()NumpyCalc.visit_Arccos()NumpyCalc.visit_Arctan()NumpyCalc.visit_Sinh()NumpyCalc.visit_Cosh()NumpyCalc.visit_Tanh()NumpyCalc.visit_Sech()NumpyCalc.visit_Csch()NumpyCalc.visit_Coth()NumpyCalc.visit_Sigmoid()NumpyCalc.visit_Regular()NumpyCalc.visit_Sour()NumpyCalc.visit_Targ()NumpyCalc.visit_Aggr()NumpyCalc.visit_Rgga()NumpyCalc.visit_Readout()
setup_lazy_imports()- Submodules
- nd2py.core.calc.numpy_calc module
unpack_operands()NumpyCalcNumpyCalc.generic_visit()NumpyCalc.visit_Empty()NumpyCalc.visit_Number()NumpyCalc.visit_Variable()NumpyCalc.visit_Add()NumpyCalc.visit_Sub()NumpyCalc.visit_Mul()NumpyCalc.visit_Div()NumpyCalc.visit_Pow()NumpyCalc.visit_Max()NumpyCalc.visit_Min()NumpyCalc.visit_Identity()NumpyCalc.visit_Sin()NumpyCalc.visit_Cos()NumpyCalc.visit_Tan()NumpyCalc.visit_Sec()NumpyCalc.visit_Csc()NumpyCalc.visit_Cot()NumpyCalc.visit_Log()NumpyCalc.visit_LogAbs()NumpyCalc.visit_Exp()NumpyCalc.visit_Abs()NumpyCalc.visit_Neg()NumpyCalc.visit_Inv()NumpyCalc.visit_Sqrt()NumpyCalc.visit_SqrtAbs()NumpyCalc.visit_Pow2()NumpyCalc.visit_Pow3()NumpyCalc.visit_Arcsin()NumpyCalc.visit_Arccos()NumpyCalc.visit_Arctan()NumpyCalc.visit_Sinh()NumpyCalc.visit_Cosh()NumpyCalc.visit_Tanh()NumpyCalc.visit_Sech()NumpyCalc.visit_Csch()NumpyCalc.visit_Coth()NumpyCalc.visit_Sigmoid()NumpyCalc.visit_Regular()NumpyCalc.visit_Sour()NumpyCalc.visit_Targ()NumpyCalc.visit_Aggr()NumpyCalc.visit_Rgga()NumpyCalc.visit_Readout()
- nd2py.core.calc.torch_calc module
unpack_operands()TorchCalcTorchCalc.generic_visit()TorchCalc.visit_Empty()TorchCalc.visit_Number()TorchCalc.visit_Variable()TorchCalc.visit_Add()TorchCalc.visit_Sub()TorchCalc.visit_Mul()TorchCalc.visit_Div()TorchCalc.visit_Pow()TorchCalc.visit_Max()TorchCalc.visit_Min()TorchCalc.visit_Sin()TorchCalc.visit_Cos()TorchCalc.visit_Tan()TorchCalc.visit_Sec()TorchCalc.visit_Csc()TorchCalc.visit_Cot()TorchCalc.visit_Log()TorchCalc.visit_LogAbs()TorchCalc.visit_Exp()TorchCalc.visit_Abs()TorchCalc.visit_Neg()TorchCalc.visit_Inv()TorchCalc.visit_Sqrt()TorchCalc.visit_SqrtAbs()TorchCalc.visit_Pow2()TorchCalc.visit_Pow3()TorchCalc.visit_Arcsin()TorchCalc.visit_Arccos()TorchCalc.visit_Arctan()TorchCalc.visit_Sinh()TorchCalc.visit_Cosh()TorchCalc.visit_Tanh()TorchCalc.visit_Sech()TorchCalc.visit_Csch()TorchCalc.visit_Coth()TorchCalc.visit_Sigmoid()TorchCalc.visit_Regular()TorchCalc.visit_Sour()TorchCalc.visit_Targ()TorchCalc.visit_Aggr()TorchCalc.visit_Rgga()TorchCalc.visit_Readout()
- nd2py.core.context package
- nd2py.core.converter package
- Submodules
- nd2py.core.converter.from_postorder module
- nd2py.core.converter.from_preorder module
- nd2py.core.converter.parser module
- nd2py.core.converter.string_printer module
StringPrinterStringPrinter.generic_visit()StringPrinter.visit_Empty()StringPrinter.visit_Number()StringPrinter.visit_Variable()StringPrinter.visit_Add()StringPrinter.visit_Sub()StringPrinter.visit_Mul()StringPrinter.visit_Div()StringPrinter.visit_Pow()StringPrinter.visit_Neg()StringPrinter.visit_Inv()StringPrinter.visit_Pow2()StringPrinter.visit_Pow3()StringPrinter.visit_Sour()StringPrinter.visit_Targ()StringPrinter.visit_Aggr()StringPrinter.visit_Rgga()
- nd2py.core.converter.tree_printer module
- nd2py.core.nettype package
- nd2py.core.symbols package
- Submodules
- nd2py.core.symbols.empty module
- nd2py.core.symbols.functions module
- nd2py.core.symbols.number module
- nd2py.core.symbols.operands module
- nd2py.core.symbols.symbol module
- nd2py.core.symbols.variable module
- nd2py.core.transform package
- Submodules
- nd2py.core.transform.bfgs_fit module
- nd2py.core.transform.fix_nettype module
FixNetTypeFixNetType.generic_visit()FixNetType.visit_Number()FixNetType.visit_Variable()FixNetType.visit_BinaryOp()FixNetType.visit_Add()FixNetType.visit_Sub()FixNetType.visit_Mul()FixNetType.visit_Div()FixNetType.visit_Pow()FixNetType.visit_Max()FixNetType.visit_Min()FixNetType.visit_Aggr()FixNetType.visit_Rgga()FixNetType.visit_Sour()FixNetType.visit_Targ()FixNetType.visit_Readout()FixNetType.fix_nettype()FixNetType.edge_to_node()FixNetType.node_to_edge()FixNetType.edge_to_scalar()FixNetType.node_to_scalar()FixNetType.scalar_to_node()FixNetType.scalar_to_edge()
- nd2py.core.transform.fold_constant module
- nd2py.core.transform.reduce module
- nd2py.core.transform.simplify module
SimplifySimplify.generic_visit()Simplify.remove_nested_unary()Simplify.visit_Sin()Simplify.visit_Cos()Simplify.visit_Tanh()Simplify.visit_Sigmoid()Simplify.visit_Sqrt()Simplify.visit_SqrtAbs()Simplify.visit_Exp()Simplify.visit_Log()Simplify.visit_LogAbs()Simplify.visit_Readout()Simplify.visit_Number()Simplify.visit_Variable()Simplify.visit_Add()Simplify.visit_Sub()Simplify.visit_Mul()Simplify.visit_Div()Simplify.visit_Neg()Simplify.visit_Inv()Simplify.visit_Aggr()
- nd2py.core.transform.split_by_add module
- nd2py.core.transform.split_by_mul module
- nd2py.core.tree package
Submodules#
nd2py.core.base_visitor module#
nd2py.core.symbol_api module#
- class nd2py.core.symbol_api.SymbolAPIMixin[source]#
Bases:
objectSymbol API Mixin.
该类集中管理 Symbol 对象对用户暴露的所有核心功能接口 (Facade)。 所有具体逻辑均由底层的 Visitor 类实现。
作为 Symbol 的父类混入,从而保证 symbols.py 的整洁与高可维护性。
- to_str(raw=False, latex=False, number_format='', omit_mul_sign=False, skeleton=False) str[source]#
Return a string representation of the symbol expression.
This is a thin wrapper around
StringPrinterand can produce raw, LaTeX, or skeleton forms of the expression.- Parameters:
raw (bool, optional) – If True, return the internal raw representation instead of a prettified one. Defaults to False.
latex (bool, optional) – If True, format the expression as LaTeX. Defaults to False.
number_format (str, optional) – Format specifier used to print numeric constants (for example
"0.2f"). Defaults to an empty string, which uses the default formatting.omit_mul_sign (bool, optional) – If True, omit explicit multiplication signs (for example render
abinstead ofa*b). Defaults to False.skeleton (bool, optional) – If True, ignore concrete numeric values and keep only the symbolic structure of the expression. Defaults to False.
- Returns:
String representation of the symbol expression.
- Return type:
str
- to_tree(number_format='', flat=False, skeleton=False) str[source]#
Return an ASCII tree representation of the expression.
- Parameters:
number_format (str, optional) – Format specifier used to print numeric constants (for example
"0.2f"). Defaults to an empty string, which uses the default formatting.flat (bool, optional) – If True, flatten nested
AddandMulnodes into a single level. Defaults to False.skeleton (bool, optional) – If True, ignore concrete numeric values and keep only the symbolic structure of the expression. Defaults to False.
- Returns:
Multi-line string visualising the expression tree.
- Return type:
str
- eval(vars: dict = {}, edge_list: Tuple[List[int], List[int]] = None, num_nodes: int = None, use_eps: float = 0.0)[source]#
Evaluate the expression numerically using NumPy.
- Parameters:
vars (dict, optional) – Mapping from variable names to their numerical values. Values can be scalars or
numpy.ndarrayobjects. Defaults to an empty dictionary.edge_list (Tuple[List[int], List[int]], optional) – Pair of integer lists
(sources, targets)describing directed edges in a graph. Node indices start from 0. If provided, this is used to parameterise graph-related symbols.num_nodes (int, optional) – Number of nodes in the underlying graph. If omitted, it may be inferred from
edge_listwhen possible.use_eps (float, optional) – Small positive value added in denominators or other potentially unstable operations to avoid division by zero and improve numerical stability. Defaults to 0.0.
- Returns:
Numerical evaluation result of the expression, whose shape depends on the symbol and inputs.
- Return type:
numpy.ndarray | float
- eval_torch(vars: dict = {}, edge_list: Tuple[List[int], List[int]] = None, num_nodes: int = None, use_eps: float = 0.0, device: str = 'cpu')[source]#
Evaluate the expression numerically using PyTorch.
- Parameters:
vars (dict, optional) – Mapping from variable names to their numerical values. Values can be scalars or
torch.Tensorobjects. Defaults to an empty dictionary.edge_list (Tuple[List[int], List[int]], optional) – Pair of integer lists
(sources, targets)describing directed edges in a graph. Node indices start from 0. If provided, this is used to parameterise graph-related symbols.num_nodes (int, optional) – Number of nodes in the underlying graph. If omitted, it may be inferred from
edge_listwhen possible.use_eps (float, optional) – Small positive value added in denominators or other potentially unstable operations to avoid division by zero and improve numerical stability. Defaults to 0.0.
device (str, optional) – Target device on which tensors are allocated and computations are performed, such as
"cpu"or"cuda". Defaults to"cpu".
- Returns:
Numerical evaluation result of the expression.
- Return type:
torch.Tensor
- split_by_add(split_by_sub: bool = False, expand_mul: bool = False, expand_div: bool = False, expand_aggr: bool = False, expand_rgga: bool = False, expand_sour: bool = False, expand_targ: bool = False, expand_readout: bool = False, remove_coefficients: bool = False, merge_bias: bool = False) List['Symbol'][source]#
Split an additive expression into its additive terms.
The current symbol is treated as the root. Depending on the flags, this can also expand multiplication, division, aggregation and readout nodes before splitting.
- Parameters:
split_by_sub (bool, optional) – If True, treat subtraction nodes as additions when splitting, so that
a - bbecomes[a, -b]. Defaults to False.expand_mul (bool, optional) – If True, expand
Mulnodes before splitting. Defaults to False.expand_div (bool, optional) – If True, expand
Divnodes before splitting. Defaults to False.expand_aggr (bool, optional) – If True, expand aggregation nodes (for example graph aggregators) before splitting. Defaults to False.
expand_rgga (bool, optional) – If True, expand RGGA-related nodes before splitting. Defaults to False.
expand_sour (bool, optional) – If True, expand source-related transformations before splitting. Defaults to False.
expand_targ (bool, optional) – If True, expand target-related transformations before splitting. Defaults to False.
expand_readout (bool, optional) – If True, push
Readoutinside additions, so that for exampleReadout(a + b)becomes[Readout(a), Readout(b)]. Defaults to False.remove_coefficients (bool, optional) – If True, drop scalar coefficients from the resulting symbols. Defaults to False.
merge_bias (bool, optional) – If True, merge additive bias terms into neighbouring symbols when appropriate. Defaults to False.
- Returns:
List of symbols corresponding to each additive term.
- Return type:
List[Symbol]
- split_by_mul(split_by_div: bool = False, merge_coefficients: bool = False) List['Symbol'][source]#
Split a multiplicative expression into its multiplicative factors.
The current symbol is treated as the root. Depending on the flags, this can also split divisions and optionally merge coefficients.
- Parameters:
split_by_div (bool, optional) – If True, split divisions so that an expression like
a / bis treated as having factors[a, b]. Defaults to False.merge_coefficients (bool, optional) – If True, merge scalar coefficients into a single factor instead of returning them as separate symbols. Defaults to False.
- Returns:
List of symbols corresponding to each multiplicative factor.
- Return type:
List[Symbol]
- fix_nettype(nettype: NetType = 'node', direction: Literal['bottom-up', 'top-down'] = 'top-down', edge_to_node=['remove_targ', 'remove_sour', 'add_aggr', 'add_rgga'], node_to_edge=['remove_aggr', 'remove_rgga', 'add_targ', 'add_sour'], edge_to_scalar=['remove_sour', 'remove_targ', 'add_readout'], node_to_scalar=['remove_aggr', 'remove_rgga', 'add_readout'], scalar_to_node=['keep'], scalar_to_edge=['keep'])[source]#
Normalize nettypes of all symbols in the expression.
This is useful in GP or LLM-based symbolic regression where equations are generated automatically and may contain inconsistent nettype annotations.
- Parameters:
nettype (NetType, optional) – Target nettype of the root symbol. Typical values include
"node","edge"and"scalar". Defaults to"node".direction (Literal["bottom-up", "top-down"], optional) – Direction in which the fix is propagated through the expression tree. Defaults to
"top-down".edge_to_node (List[str], optional) – Sequence of transformation rules applied when converting edge symbols to node symbols.
node_to_edge (List[str], optional) – Sequence of transformation rules applied when converting node symbols to edge symbols.
edge_to_scalar (List[str], optional) – Sequence of transformation rules applied when converting edge symbols to scalar symbols.
node_to_scalar (List[str], optional) – Sequence of transformation rules applied when converting node symbols to scalar symbols.
scalar_to_node (List[str], optional) – Sequence of transformation rules applied when converting scalar symbols to node symbols.
scalar_to_edge (List[str], optional) – Sequence of transformation rules applied when converting scalar symbols to edge symbols.
- Returns:
Root symbol of the expression with consistent nettypes.
- Return type:
- simplify(transform_constant_subtree: bool = True, remove_useless_readout: bool = True, remove_nested_sin: bool = False, remove_nested_cos: bool = False, remove_nested_tanh: bool = False, remove_nested_sigmoid: bool = False, remove_nested_sqrt: bool = False, remove_nested_sqrtabs: bool = False, remove_nested_exp: bool = False, remove_nested_log: bool = False, remove_nested_logabs: bool = False)[source]#
Apply algebraic simplifications to the expression.
Each flag controls whether a specific family of simplification rules is enabled. By default constant subtrees are folded and useless readout nodes are removed.
- Parameters:
transform_constant_subtree (bool, optional) – If True, evaluate and replace constant-only subtrees with their numerical result. Defaults to True.
remove_useless_readout (bool, optional) – If True, eliminate redundant
Readoutnodes that do not affect the result. Defaults to True.remove_nested_sin (bool, optional) – If True, simplify expressions containing nested sine functions when possible. Defaults to False.
remove_nested_cos (bool, optional) – If True, simplify expressions containing nested cosine functions when possible. Defaults to False.
remove_nested_tanh (bool, optional) – If True, simplify expressions containing nested hyperbolic tangent functions when possible. Defaults to False.
remove_nested_sigmoid (bool, optional) – If True, simplify expressions containing nested sigmoid functions when possible. Defaults to False.
remove_nested_sqrt (bool, optional) – If True, simplify nested square root expressions when possible. Defaults to False.
remove_nested_sqrtabs (bool, optional) – If True, simplify nested
sqrtabs-like expressions when possible. Defaults to False.remove_nested_exp (bool, optional) – If True, simplify nested exponential expressions when possible. Defaults to False.
remove_nested_log (bool, optional) – If True, simplify nested logarithm expressions when possible. Defaults to False.
remove_nested_logabs (bool, optional) – If True, simplify nested
logabs-like expressions when possible. Defaults to False.
- Returns:
A simplified version of the original symbol expression.
- Return type: