nd2py.core package

Contents

nd2py.core package#

nd2py.core.no_copy_value()[source]#
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_operands of the concrete subclass. Non-symbol scalar values are automatically wrapped as Number symbols.

  • 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 by infer_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 None if 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.

nd2py.core.aggr#

alias of Aggr

class nd2py.core.Csch(*operands, nettype: Literal['node', 'edge', 'scalar'] | Set[Literal['node', 'edge', 'scalar']] | None = None)[source]#

Bases: Symbol

n_operands = 1#
nd2py.core.pow2#

alias of Pow2

nd2py.core.cos#

alias of Cos

nd2py.core.log#

alias of Log

class nd2py.core.SplitByMul[source]#

Bases: Visitor

generic_visit(node: Symbol, *args, **kwargs) _Type[source]#
visit_Mul(node: Mul, *args, **kwargs) _Type[source]#
visit_Div(node: Div, *args, **kwargs) _Type[source]#
merge_coefficients(items: List[Symbol], *args, **kwargs) List[Symbol][source]#

Merge coefficients from the symbols.

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 None if 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.

nd2py.core.get_copy_value()[source]#
nd2py.core.no_nettype_inference()[source]#
class nd2py.core.Csc(*operands, nettype: Literal['node', 'edge', 'scalar'] | Set[Literal['node', 'edge', 'scalar']] | None = None)[source]#

Bases: Symbol

n_operands = 1#
nd2py.core.maximum(*operands)[source]#
class nd2py.core.Cot(*operands, nettype: Literal['node', 'edge', 'scalar'] | Set[Literal['node', 'edge', 'scalar']] | None = None)[source]#

Bases: Symbol

n_operands = 1#
nd2py.core.set_fitable()[source]#
nd2py.core.phi_s#

alias of Sour

nd2py.core.sinh#

alias of Sinh

nd2py.core.min#

alias of Min

nd2py.core.regular#

alias of Regular

class nd2py.core.Add(*operands, nettype: Literal['node', 'edge', 'scalar'] | Set[Literal['node', 'edge', 'scalar']] | None = None)[source]#

Bases: Symbol

n_operands = 2#
nd2py.core.no_set_fitable()[source]#
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

nd2py.core.minimum(*operands)[source]#
class nd2py.core.Sec(*operands, nettype: Literal['node', 'edge', 'scalar'] | Set[Literal['node', 'edge', 'scalar']] | None = None)[source]#

Bases: Symbol

n_operands = 1#
nd2py.core.cosh#

alias of Cosh

nd2py.core.sigmoid#

alias of Sigmoid

class nd2py.core.Identity(*operands, nettype: Literal['node', 'edge', 'scalar'] | Set[Literal['node', 'edge', 'scalar']] | None = None)[source]#

Bases: Symbol

n_operands = 1#
nd2py.core.div#

alias of Div

class nd2py.core.Cosh(*operands, nettype: Literal['node', 'edge', 'scalar'] | Set[Literal['node', 'edge', 'scalar']] | None = None)[source]#

Bases: Symbol

n_operands = 1#
nd2py.core.reg#

alias of Regular

nd2py.core.pow#

alias of Pow

class nd2py.core.FoldConstant(fold_fitable: bool = True, fold_constant: bool = True)[source]#

Bases: Visitor

访问器,用于将表达式中不含 Number 的子表达式折叠为 Constant。

__init__(fold_fitable: bool = True, fold_constant: bool = True)[source]#
generic_visit(node, *args, **kwargs)[source]#
visit_Empty(node: Symbol, *args, **kwargs)[source]#
visit_Number(node: Number, *args, **kwargs)[source]#
visit_Variable(node: Variable, *args, **kwargs)[source]#
class nd2py.core.TreePrinter[source]#

Bases: Visitor

generic_visit(node: Symbol, *args, **kwargs) _Type[source]#
visit_Empty(node: Symbol, *args, **kwargs) _Type[source]#
visit_Number(node: Number, *args, **kwargs) _Type[source]#
visit_Variable(node: Variable, *args, **kwargs) _Type[source]#
visit_Add(node: Add, *args, **kwargs) _Type[source]#
visit_Mul(node: Mul, *args, **kwargs) _Type[source]#
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.arcsin#

alias of Arcsin

nd2py.core.tanh#

alias of Tanh

nd2py.core.parse(expression: str, variables: Dict[str, Symbol] = None, callables: Dict[str, callable] = None) Symbol[source]#
nd2py.core.rgga#

alias of Rgga

nd2py.core.max#

alias of Max

nd2py.core.pow3#

alias of Pow3

nd2py.core.add#

alias of Add

nd2py.core.mul#

alias of Mul

nd2py.core.neg#

alias of Neg

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.logabs#

alias of LogAbs

nd2py.core.phi_t#

alias of Targ

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 that from package import OptionalClass works 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"),
})
nd2py.core.sub#

alias of Sub

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 None if 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.set_copy_value(value: bool)[source]#
nd2py.core.variables(vars, *args, **kwargs)[source]#

一个工厂函数,返回一个或多个 Variable 对象。 如果 vars 中包含空格,则认为是多个变量的名字,并返回一个列表;否则认为是单个变量的名字,并返回一个 Variable 对象。

nd2py.core.csc#

alias of Csc

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_operands of the concrete subclass. Non-symbol scalar values are automatically wrapped as Number symbols.

  • 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 by infer_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 None if 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 值域,并在首次调用时缓存到类属性中。

nd2py.core.targ#

alias of Targ

class nd2py.core.NumpyCalc[source]#

Bases: Visitor

generic_visit(node: Symbol, *args, **kwargs)[source]#
visit_Empty(node: Empty, *args, **kwargs)[source]#
visit_Number(node: Number, *args, **kwargs)[source]#
visit_Variable(node: Variable, *args, **kwargs)[source]#
visit_Add(node: Add, x1, x2, *args, **kwargs)[source]#
visit_Sub(node: Sub, x1, x2, *args, **kwargs)[source]#
visit_Mul(node: Mul, x1, x2, *args, **kwargs)[source]#
visit_Div(node: Div, x1, x2, *args, **kwargs)[source]#
visit_Pow(node: Pow, x1, x2, *args, **kwargs)[source]#
visit_Max(node: Max, x1, x2, *args, **kwargs)[source]#
visit_Min(node: Min, x1, x2, *args, **kwargs)[source]#
visit_Identity(node: Identity, x, *args, **kwargs)[source]#
visit_Sin(node: Sin, x, *args, **kwargs)[source]#
visit_Cos(node: Cos, x, *args, **kwargs)[source]#
visit_Tan(node: Tan, x, *args, **kwargs)[source]#
visit_Sec(node: Sec, x, *args, **kwargs)[source]#
visit_Csc(node: Csc, x, *args, **kwargs)[source]#
visit_Cot(node: Cot, x, *args, **kwargs)[source]#
visit_Log(node: Log, x, *args, **kwargs)[source]#
visit_LogAbs(node: LogAbs, x, *args, **kwargs)[source]#
visit_Exp(node: Exp, x, *args, **kwargs)[source]#
visit_Abs(node: Abs, x, *args, **kwargs)[source]#
visit_Neg(node: Neg, x, *args, **kwargs)[source]#
visit_Inv(node: Inv, x, *args, **kwargs)[source]#
visit_Sqrt(node: Sqrt, x, *args, **kwargs)[source]#
visit_SqrtAbs(node: SqrtAbs, x, *args, **kwargs)[source]#
visit_Pow2(node: Pow2, x, *args, **kwargs)[source]#
visit_Pow3(node: Pow3, x, *args, **kwargs)[source]#
visit_Arcsin(node: Arcsin, x, *args, **kwargs)[source]#
visit_Arccos(node: Arccos, x, *args, **kwargs)[source]#
visit_Arctan(node: Arctan, x, *args, **kwargs)[source]#
visit_Sinh(node: Sinh, x, *args, **kwargs)[source]#
visit_Cosh(node: Cosh, x, *args, **kwargs)[source]#
visit_Tanh(node: Tanh, x, *args, **kwargs)[source]#
visit_Sech(node: Sech, x, *args, **kwargs)[source]#
visit_Csch(node: Csch, x, *args, **kwargs)[source]#
visit_Coth(node: Coth, x, *args, **kwargs)[source]#
visit_Sigmoid(node: Sigmoid, x, *args, **kwargs)[source]#
visit_Regular(node: Regular, x1, x2, *args, **kwargs)[source]#
visit_Sour(node: Sour, x, *args, **kwargs)[source]#

(, n_nodes or 1) -> (, n_edges or 1)

visit_Targ(node: Targ, x, *args, **kwargs)[source]#

(, n_nodes or 1) -> (, n_edges or 1)

visit_Aggr(node: Aggr, x, *args, **kwargs)[source]#

(, n_edges or 1) -> (, n_nodes)

visit_Rgga(node: Rgga, x, *args, **kwargs)[source]#

(, n_edges or 1) -> (, n_nodes)

visit_Readout(node: Readout, x, *args, **kwargs)[source]#

(, n_nodes or n_edges or 1) -> (, 1)

nd2py.core.readout#

alias of Readout

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_operands of the concrete subclass. Non-symbol scalar values are automatically wrapped as Number symbols.

  • 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 by infer_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 parent links, so it can be safely inserted into a different expression tree.

Returns:

A deep copy of the current symbol.

Return type:

Symbol

get_numbers(fitable_only: bool = False, float_only: bool = False, scalar_only: bool = False) List[Number][source]#

Collect all Number nodes 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 from Number nodes.

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 params are consumed in the same order as produced by get_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 params does 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 None if 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

__init__(expression: Symbol, edge_list=None, num_nodes=None, use_eps=1e-08, method='BFGS', tol=1e-06, options=None, fold_constant=False)[source]#
fit(X, y=None)[source]#
predict(X)[source]#

用拟合好的 expression 去计算新的 X 上的输出。

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_operands of the concrete subclass. Non-symbol scalar values are automatically wrapped as Number symbols.

  • 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 by infer_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 None if 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 值域,并在首次调用时缓存到类属性中。

nd2py.core.arccos#

alias of Arccos

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.prod(*operands)[source]#
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.Simplify[source]#

Bases: Visitor

generic_visit(node: Symbol, *args, **kwargs) _Type[source]#
remove_nested_unary(node: Symbol, *args, **kwargs) _Type[source]#
visit_Sin(node: Symbol, *args, **kwargs) _Type#
visit_Cos(node: Symbol, *args, **kwargs) _Type#
visit_Tanh(node: Symbol, *args, **kwargs) _Type#
visit_Sigmoid(node: Symbol, *args, **kwargs) _Type#
visit_Sqrt(node: Symbol, *args, **kwargs) _Type#
visit_SqrtAbs(node: Symbol, *args, **kwargs) _Type#
visit_Exp(node: Symbol, *args, **kwargs) _Type#
visit_Log(node: Symbol, *args, **kwargs) _Type#
visit_LogAbs(node: Symbol, *args, **kwargs) _Type#
visit_Readout(node: Readout, *args, **kwargs) _Type[source]#
visit_Number(node: Number, *args, **kwargs) _Type[source]#
visit_Variable(node: Variable, *args, **kwargs) _Type[source]#
visit_Add(node: Add, *args, **kwargs) _Type[source]#
visit_Sub(node: Add, *args, **kwargs) _Type#
visit_Mul(node: Mul, *args, **kwargs) _Type[source]#
visit_Div(node: Mul, *args, **kwargs) _Type#
visit_Neg(node: Neg, *args, **kwargs) _Type[source]#
visit_Inv(node: Inv, *args, **kwargs) _Type[source]#
visit_Aggr(node: Aggr, *args, **kwargs) _Type[source]#
class nd2py.core.Sqrt(*operands, nettype: Literal['node', 'edge', 'scalar'] | Set[Literal['node', 'edge', 'scalar']] | None = None)[source]#

Bases: Symbol

n_operands = 1#
nd2py.core.set_nettype_inference(value: bool)[source]#
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#
nd2py.core.no_warn()[source]#

Context manager to suppress warnings temporarily

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 None if 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#
nd2py.core.cot#

alias of Cot

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.StringPrinter[source]#

Bases: Visitor

generic_visit(node: Symbol, *args, **kwargs) _Type[source]#
visit_Empty(node: Empty, *args, **kwargs) _Type[source]#
visit_Number(node: Number, *args, **kwargs) _Type[source]#
visit_Variable(node: Variable, *args, **kwargs) _Type[source]#
visit_Add(node: Add, *args, **kwargs) _Type[source]#
visit_Sub(node: Sub, *args, **kwargs) _Type[source]#
visit_Mul(node: Mul, *args, **kwargs) _Type[source]#
visit_Div(node: Div, *args, **kwargs) _Type[source]#
visit_Pow(node: Pow, *args, **kwargs) _Type[source]#
visit_Neg(node: Neg, *args, **kwargs) _Type[source]#
visit_Inv(node: Inv, *args, **kwargs) _Type[source]#
visit_Pow2(node: Pow2, *args, **kwargs) _Type[source]#
visit_Pow3(node: Pow3, *args, **kwargs) _Type[source]#
visit_Sour(node: Sour, *args, **kwargs) _Type[source]#
visit_Targ(node: Targ, *args, **kwargs) _Type[source]#
visit_Aggr(node: Aggr, *args, **kwargs) _Type[source]#
visit_Rgga(node: Rgga, *args, **kwargs) _Type[source]#
nd2py.core.nettype_inference()[source]#
class nd2py.core.Max(*operands, nettype: Literal['node', 'edge', 'scalar'] | Set[Literal['node', 'edge', 'scalar']] | None = None)[source]#

Bases: Symbol

n_operands = 2#
nd2py.core.sum(*operands)[source]#
nd2py.core.sqrtabs#

alias of SqrtAbs

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#
nd2py.core.tan#

alias of Tan

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_Number(node: Number, *args, **kwargs) _Type[source]#
visit_Variable(node: Variable, *args, **kwargs) _Type[source]#
visit_BinaryOp(node, *args, **kwargs) _Type[source]#
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_Aggr(node, *args, **kwargs) _Type[source]#
visit_Rgga(node, *args, **kwargs) _Type#
visit_Sour(node, *args, **kwargs) _Type[source]#
visit_Targ(node, *args, **kwargs) _Type#
visit_Readout(node, *args, **kwargs) _Type[source]#
fix_nettype(node: Symbol, *args, **kwargs) Symbol[source]#
edge_to_node(node: Symbol, *args, **kwargs) Symbol[source]#
node_to_edge(node: Symbol, *args, **kwargs) Symbol[source]#
edge_to_scalar(node: Symbol, *args, **kwargs) Symbol[source]#
node_to_scalar(node: Symbol, *args, **kwargs) Symbol[source]#
scalar_to_node(node: Symbol, *args, **kwargs) Symbol[source]#
scalar_to_edge(node: Symbol, *args, **kwargs) Symbol[source]#
nd2py.core.sin#

alias of Sin

nd2py.core.sec#

alias of Sec

class nd2py.core.Sigmoid(*operands, nettype: Literal['node', 'edge', 'scalar'] | Set[Literal['node', 'edge', 'scalar']] | None = None)[source]#

Bases: Symbol

n_operands = 1#
nd2py.core.exp#

alias of Exp

nd2py.core.rho#

alias of Aggr

class nd2py.core.Mul(*operands, nettype: Literal['node', 'edge', 'scalar'] | Set[Literal['node', 'edge', 'scalar']] | None = None)[source]#

Bases: Symbol

n_operands = 2#
nd2py.core.sour#

alias of Sour

nd2py.core.sech#

alias of Sech

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.inv#

alias of Inv

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.

nd2py.core.abs#

alias of Abs

nd2py.core.sqrt#

alias of Sqrt

nd2py.core.csch#

alias of Csch

class nd2py.core.SplitByAdd[source]#

Bases: Visitor

generic_visit(node: Symbol, *args, **kwargs) _Type[source]#
visit_Add(node: Add, *args, **kwargs) _Type[source]#
visit_Sub(node: Sub, *args, **kwargs) _Type[source]#
visit_Mul(node: Mul, *args, **kwargs) _Type[source]#
visit_Div(node: Div, *args, **kwargs) _Type[source]#
visit_Neg(node: Neg, *args, **kwargs) _Type[source]#
visit_Sour(node: Sour, *args, **kwargs) _Type[source]#
visit_Targ(node: Targ, *args, **kwargs) _Type[source]#
visit_Aggr(node: Aggr, *args, **kwargs) _Type[source]#
visit_Rgga(node: Rgga, *args, **kwargs) _Type[source]#
visit_Readout(node: Readout, *args, **kwargs) _Type[source]#
merge_bias(items: List[Symbol], *args, **kwargs) List[Symbol][source]#

Merge bias terms in the node.

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#
nd2py.core.arctan#

alias of Arctan

Subpackages#

Submodules#

nd2py.core.base_visitor module#

nd2py.core.base_visitor.yield_nothing()[source]#

A generator that yields nothing, used as a placeholder for methods that do not yield.

class nd2py.core.base_visitor.Visitor[source]#

Bases: ABC

abstractmethod generic_visit(node: Symbol, *args, **kwargs)[source]#

nd2py.core.symbol_api module#

class nd2py.core.symbol_api.SymbolAPIMixin[source]#

Bases: object

Symbol 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 StringPrinter and 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 ab instead of a*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 Add and Mul nodes 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.ndarray objects. 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_list when 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.Tensor objects. 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_list when 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 - b becomes [a, -b]. Defaults to False.

  • expand_mul (bool, optional) – If True, expand Mul nodes before splitting. Defaults to False.

  • expand_div (bool, optional) – If True, expand Div nodes 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 Readout inside additions, so that for example Readout(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 / b is 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:

Symbol

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 Readout nodes 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:

Symbol