code: def rewrite_graph(
      graph: Union[Variable, Sequence[Variable], FunctionGraph],
      include: Sequence[str] = ("canonicalize",),
      custom_rewrite: Optional["GraphRewriter"] = None,
      clone: bool = False,
      **kwargs,
  ) -> Union[Variable, Sequence[Variable], FunctionGraph]:
      """Easily apply rewrites to a graph.
  
      Parameters
      ----------
      graph
          A `FunctionGraph` or `Variable` to be rewritten.
      include
          String names of the rewrites to be queried, via a
          `RewriteDatabaseQuery` instance, and applied.  The default rewrite
          query string is ``"canonicalization"``.
      custom_rewrite
          A custom `Rewriter` to also be applied.
      clone
          Whether or not to clone the input graph before rewriting.
      **kwargs
          Keyword arguments passed to a `RewriteDatabaseQuery` object.
      """
      from pytensor.compile import optdb
  
      return_fgraph = False
      if isinstance(graph, FunctionGraph):
          fgraph = graph
          return_fgraph = True
      else:
          if isinstance(graph, (list, tuple)):
              outputs = graph
          else:
              assert isinstance(graph, Variable)
              outputs = [graph]
  
          fgraph = FunctionGraph(outputs=outputs, clone=clone)
  
      query_rewrites = optdb.query(
          RewriteDatabaseQuery(include=include, **kwargs)
      )
      _ = query_rewrites.rewrite(fgraph)
  
      if custom_rewrite:
          custom_rewrite.rewrite(fgraph)
  
      if return_fgraph:
          return fgraph
      else:
          if isinstance(graph, (list, tuple)):
              return fgraph.outputs
          else:
              return fgraph.outputs[0]
  
file_path: pytensor/pytensor/graph/rewriting/utils.py
imports: import copy
  from collections.abc import Generator, Sequence
  from typing import TYPE_CHECKING, Optional, Union, cast
  import pytensor
  from pytensor.graph.basic import Apply, Variable, equal_computations, graph_inputs, vars_between
  from pytensor.graph.fg import FunctionGraph
  from pytensor.graph.rewriting.db import RewriteDatabaseQuery
label_desc: Use image node_id 1 for calling a global function with example usage: rewrite_graph(graph, include, custom_rewrite, clone) and returns: fgraph, fgraph, fgraph