def linearize(expr):
 expr = Constant.cast_to_const(expr)
 if expr.is_affine():
  return expr
 else:
  tangent = expr.value
  if (tangent is None):
   raise ValueError('Cannot linearize non-affine expression with missing variable values.')
  grad_map = expr.grad
  for var in expr.variables():
   if (grad_map[var] is None):
    return None
   elif var.is_matrix():
    flattened = (Constant(grad_map[var]).T * vec((var - var.value)))
    tangent = (tangent + reshape(flattened, *expr.size))
   else:
    tangent = (tangent + (Constant(grad_map[var]).T * (var - var.value)))
  return tangent

def linearize ( expr ) : expr = Constant . cast_to_const ( expr ) if expr . is_affine ( ) : return expr else : tangent = expr . value if ( tangent is None ) : raise ValueError ( 'Cannot linearize non-affine expression with missing variable values.' ) grad_map = expr . grad for var in expr . variables ( ) : if ( grad_map [ var ] is None ) : return None elif var . is_matrix ( ) : flattened = ( Constant ( grad_map [ var ] ) . T * vec ( ( var - var . value ) ) ) tangent = ( tangent + reshape ( flattened , * expr . size ) ) else : tangent = ( tangent + ( Constant ( grad_map [ var ] ) . T * ( var - var . value ) ) ) return tangent
returns the tangent approximation to the expression .