def per_cycle_depth(df):
        """This function is applied per cycle_depth in the following groupby aggregation."""
        fid_lsq = df['numerator'].sum() / df['denominator'].sum()
        # Note: both df['denominator'] and df['x'] are constants.
        # Var[f] = Var[df['numerator']] / (sum df['denominator'])^2
        #           = sum (df['x']^2 * df['var_m_u']) / (sum df['denominator'])^2
        var_fid = (df['var_m_u'] * df['x'] ** 2).sum() / df['denominator'].sum() ** 2
        ret = {'fidelity': fid_lsq, 'fidelity_variance': var_fid}

        def _try_keep(k):
            """If all the values for a key `k` are the same in this group, we can keep it."""
            if k not in df.columns:
                return  # pragma: no cover
            vals = df[k].unique()
            if len(vals) == 1:
                ret[k] = vals[0]
            else:  # pragma: no cover
                raise AssertionError(
                    f"When computing per-cycle-depth fidelity, multiple "
                    f"values for {k} were grouped together: {vals}"
                )

        _try_keep('pair')
        return pd.Series(ret)
This function is applied per cycle_depth in the following groupby aggregation.
cirq-core/cirq/experiments/xeb_fitting.py