code: def fold_global_tape(circuit, scale_factor):
      r"""
      This is the internal tape transform to be used with :func:`~.pennylane.transforms.mitigate_with_zne`.
      For the user-facing function see :func:`~.pennylane.transforms.fold_global`.
  
      Args:
          circuit (QuantumTape): the circuit to be folded
          scale_factor (float): Scale factor :math:`\lambda` determining :math:`n` and :math:`s`
  
      Returns:
          QuantumTape: Folded circuit
  
      """
  
      # TODO: simplify queing via qfunc(op) - currently just a workaround, to solve the problem of ownership when tape contains adjoint(op)
      # https://github.com/PennyLaneAI/pennylane/pull/2766 already touched on the issue, future work
      # in Q3 2022 should make it possible to substantially simplify this.
      def qfunc(op):
          copy(op).queue()
  
      # Generate base_circuit without measurements
      # Treat all circuits as lists of operations, build new tape in the end
  
      base_ops = circuit.expand().copy(copy_operations=True).operations
  
      num_global_folds, fraction_scale = _divmod(scale_factor - 1, 2)
  
      n_ops = len(base_ops)
      num_to_fold = int(round(fraction_scale * n_ops / 2))
  
      # Create new_circuit from folded list
      with AnnotatedQueue() as new_circuit_q:
          # Original U
          for op in base_ops:
              qfunc(op)
  
          # Folding U => U (U^H U)**n.
          for _ in range(int(num_global_folds)):
              for op in base_ops[::-1]:
                  adjoint(qfunc)(op)
  
              for op in base_ops:
                  qfunc(op)
  
          # Remainder folding U => U (U^H U)**n (L_d^H .. L_s^H) (L_s .. L_d)
          for i in range(n_ops - 1, n_ops - num_to_fold - 1, -1):
              adjoint(qfunc)(base_ops[i])
  
          for i in range(n_ops - num_to_fold, n_ops):
              qfunc(base_ops[i])
  
          # Append measurements
          for meas in circuit.measurements:
              apply(meas)
  
      return QuantumScript.from_queue(new_circuit_q)
  
file_path: pennylane/pennylane/transforms/mitigate.py
imports: from copy import copy
  from typing import Any, Dict, Optional, Sequence, Callable
  from pennylane import apply, adjoint
  from pennylane.math import mean, shape, round
  from pennylane.queuing import AnnotatedQueue
  from pennylane.tape import QuantumTape, QuantumScript
  from pennylane.transforms import transform
  import pennylane
label_desc: Use image node_id 3 for calling a global function with example usage: fold_global_tape(circuit, scale_factor) and returns: QuantumScript