@@ -212,6 +212,10 @@ def replace(self, old, new):
212212 """Replace specified operand/operator."""
213213 raise NotImplementedError ()
214214
215+ def replace_dict (self , subs ):
216+ """Replace specified operands/operators according to a dictionary."""
217+ raise NotImplementedError ()
218+
215219 def sym_diff (self , var ):
216220 """Symbolically differentiate with respect to specified operand."""
217221 raise NotImplementedError ()
@@ -284,9 +288,8 @@ def frechet_differential(self, variables, perturbations, backgrounds=None):
284288 # Compute differential
285289 epsilon = Field (dist = dist , dtype = dtype )
286290 # d/dε F(X0 + ε*X1)
287- diff = self
288- for var , pert in zip (variables , perturbations ):
289- diff = diff .replace (var , var + epsilon * pert )
291+ subs = {var : var + epsilon * pert for var , pert in zip (variables , perturbations )}
292+ diff = self .replace_dict (subs )
290293 diff = diff .sym_diff (epsilon )
291294 # ε -> 0
292295 if diff :
@@ -295,8 +298,8 @@ def frechet_differential(self, variables, perturbations, backgrounds=None):
295298 # Replace variables with backgrounds, if specified
296299 if diff :
297300 if backgrounds :
298- for var , bg in zip (variables , backgrounds ):
299- diff = diff .replace ( var , bg )
301+ subs = { var : bg for var , bg in zip (variables , backgrounds )}
302+ diff = diff .replace_dict ( subs )
300303 return diff
301304
302305 @property
@@ -378,6 +381,13 @@ def replace(self, old, new):
378381 else :
379382 return self
380383
384+ def replace_dict (self , subs ):
385+ """Replace specified operands/operators according to a dictionary."""
386+ if self in subs :
387+ return subs [self ]
388+ else :
389+ return self
390+
381391 def sym_diff (self , var ):
382392 """Symbolically differentiate with respect to specified operand."""
383393 if self == var :
0 commit comments