Source code for experimental_experiment.xbuilder.expression_dimension
importastfromtypingimportAny,Dict,Optional
[docs]classExpression:""" A formula using dimension. """def__init__(self,expr:str,parsed:Optional[ast.Expression]=None):self.expr=exprself.parsed=parseddef__repr__(self):returnf"{self.__class__.__name__}({self.expr!r})"
[docs]defparse_expression_tokens(expr:str):""" Extracts the token from an expression. """tokens=[]try:st=ast.parse(expr,mode="eval")exceptTypeErrorase:raiseTypeError(f"Unable to compile expression {expr!r} (type is {type(expr)})")fromefornodeinast.walk(st):ifisinstance(node,ast.Name):tokens.append(node.id)returnset(tokens)
[docs]defparse_expression(expr:str,context:Optional[Dict[str,Any]]=None,exc:bool=True,)->Expression:""" Parses an expression involving dimensions. :param expr: an expression :param exc: raises an exception if it fails :param context: known variables (or dimensions) :return: an expression """ifhasattr(expr,"__sym_float__"):# torch.SymIntreturnparse_expression(expr.node,context=context,exc=exc)ifhasattr(expr,"_expr"):# torch.fx.experimental.sym_node.SymNodereturnparse_expression(str(expr._expr),context=context,exc=exc)assertisinstance(expr,str),f"Unexpected type {type(expr)} for expr={expr!r} and context={context}"assertexc,"parse_expression not implemented when exc is False"ifcontextisNone:context={}st=ast.parse(expr,mode="eval")fornodeinast.walk(st):ifisinstance(node,ast.Name):sds=[]ford_incontext.values():# WrapSymd=d_.symifhasattr(d_,"sym")elsed_try:sd=str(d)exceptAttributeErrorase:ifhasattr(d,"node")andisinstance(d.node,str):sd=d.nodeelse:raiseAssertionError(f"Unable to convert type {type(d)} into string")fromesds.append(sd)assertcontextisNoneornode.idincontextornode.idinset(sds),(f"Unable to find name {node.id!r} from expression {expr!r}, "f"context is {sorted(context)}")returnExpression(expr,parsed=st)