Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-12-02 09:15:17

0001 import gzip
0002 import os
0003 import re
0004 
0005 import awkward as ak
0006 import click
0007 import numpy as np
0008 import uproot
0009 from bokeh.events import DocumentReady
0010 from bokeh.io import curdoc
0011 from bokeh.models import ColumnDataSource
0012 from bokeh.plotting import output_file, save
0013 from bokeh.resources import Resources
0014 from hist import Hist
0015 from scipy.stats import PermutationMethod, anderson_ksamp, kstest
0016 
0017 from ..util import integer_axis_range, skip_common_prefix
0018 
0019 # Line color, width, dash and hatch pattern for the histogram of each input
0020 # file, in order. Consumed client-side when rendering the plots. Dashes are
0021 # given as explicit patterns (solid, dashed, dotted), as Bokeh resolves them in
0022 # Python; BokehJS draws the named patterns differently.
0023 _VIS_PARAMS = [
0024     ("green", 1.5, [], " "),
0025     ("red", 3, [6], ","),
0026     ("blue", 2, [2, 4], "."),
0027 ]
0028 
0029 # Cap Anderson-Darling sample size to keep runtime bounded on
0030 # high-multiplicity collections.
0031 _AD_MAX_N = 10_000
0032 
0033 
0034 def _ad_rng(key):
0035     """Return a deterministic RNG seeded from the leaf key.
0036 
0037     Using a per-leaf seed (rather than a shared module-level RNG) makes each
0038     leaf's subsample independent of the number and order of previously
0039     processed leaves, so AD p-values stay reproducible when the set of
0040     processed collections changes (e.g. under different match/unmatch
0041     filters).
0042     """
0043     import hashlib
0044     digest = hashlib.blake2b(key.encode("utf-8"), digest_size=8).digest()
0045     return np.random.default_rng(int.from_bytes(digest, "little"))
0046 
0047 
0048 
0049 def _is_leaf(obj):
0050     """Check if an uproot branch/field object is a leaf (has no sub-branches/sub-fields).
0051 
0052     Supports both TTree TBranch objects (which use `.branches`) and
0053     RNTuple RField objects (which use `.fields`).
0054     """
0055     if hasattr(obj, 'branches'):
0056         return len(obj.branches) == 0
0057     if hasattr(obj, 'fields'):
0058         return len(obj.fields) == 0
0059     return True
0060 
0061 
0062 def _normalize_key(key):
0063     """Normalize uproot key format between TTree and RNTuple styles.
0064 
0065     TTree EDM4hep keys follow 'CollectionName/CollectionName.fieldPath' pattern.
0066     RNTuple EDM4hep keys follow 'CollectionName.fieldPath' pattern.
0067     This function converts TTree-style keys to the RNTuple-style format so that
0068     the same physics quantity has the same key regardless of the input file format.
0069 
0070     TTree keys for fixed-size array branches include a trailing '[N]' size
0071     annotation (e.g. 'covariance.covariance[21]') which is absent in RNTuple
0072     keys; this suffix is stripped so the two formats match.
0073 
0074     >>> _normalize_key('MCParticles/MCParticles.momentum.x')
0075     'MCParticles.momentum.x'
0076     >>> _normalize_key('MCParticles.momentum.x')
0077     'MCParticles.momentum.x'
0078     >>> _normalize_key('EventHeader/EventHeader.eventNumber')
0079     'EventHeader.eventNumber'
0080     >>> _normalize_key('CentralCKFTrackParameters/CentralCKFTrackParameters.covariance.covariance[21]')
0081     'CentralCKFTrackParameters.covariance.covariance'
0082     """
0083     if "/" in key:
0084         _, field_part = key.split("/", 1)
0085     else:
0086         field_part = key
0087     return re.sub(r'\[\d+\]$', '', field_part)
0088 
0089 
0090 def match_filter(key, match, unmatch):
0091     accept = True
0092     if match:
0093         accept = False
0094         for regex in match:
0095             if regex.match(key):
0096                 accept = True
0097     for regex in unmatch:
0098         if regex.match(key):
0099             accept = False
0100     return accept
0101 
0102 
0103 @click.command()
0104 @click.argument("files", type=click.File('rb'), nargs=-1)
0105 @click.option(
0106     "-m", "--match", multiple=True,
0107     help="Only include collections with names matching a regex"
0108 )
0109 @click.option(
0110     "-M", "--unmatch", multiple=True,
0111     help="Exclude collections with names matching a regex"
0112 )
0113 @click.option(
0114     "--serve", is_flag=True,
0115     default=False,
0116     help="Run a local HTTP server to view the report"
0117 )
0118 def bara(files, match, unmatch, serve):
0119     arr = {}
0120 
0121     match = list(map(re.compile, match))
0122     unmatch = list(map(re.compile, unmatch))
0123 
0124     for _file in files:
0125         tree = uproot.open(_file)["events"]
0126 
0127         sort_by_evtnum = None
0128         for evtnum_key in ["EventHeader/EventHeader.eventNumber", "EventHeader.eventNumber"]:
0129             if evtnum_key in tree.keys(recursive=True):
0130                 evtnum = tree[evtnum_key].array()
0131                 sort_by_evtnum = ak.argsort(ak.flatten(evtnum))
0132                 break
0133 
0134         for key in tree.keys(recursive=True):
0135             if not key.startswith("PARAMETERS") and _is_leaf(tree[key]):
0136                 normalized = _normalize_key(key)
0137                 if match_filter(normalized, match, unmatch):
0138                     val = tree[key].array()
0139                     if sort_by_evtnum is not None:
0140                         val = val[sort_by_evtnum]
0141                     arr.setdefault(normalized, {})[_file] = val
0142 
0143     paths = skip_common_prefix([_file.name.split("/") for _file in files])
0144     paths = skip_common_prefix([reversed(list(path)) for path in paths])
0145     labels = ["/".join(reversed(list(reversed_path))) for reversed_path in paths]
0146 
0147     collection_plots = {}
0148     collection_with_diffs = {}
0149     collection_ks_pvalue = {}
0150     collection_ad_pvalue = {}
0151     collection_matching_count = {}
0152 
0153     for key in sorted(arr.keys()):
0154         if any("string" in str(ak.type(a)) for a in arr[key].values()):
0155             click.echo(f"String value detected for key \"{key}\". Skipping...")
0156             continue
0157         if any("bool" in str(ak.type(a)) for a in arr[key].values()):
0158             click.echo(f"Bool value detected for key \"{key}\". Skipping...")
0159             continue
0160         if any(a.layout.minmax_depth[0] < 2 for a in arr[key].values()):
0161             # Not possible for PODIO, here for general ROOT file support
0162             print(f"Skipping non-array branch \"{key}\"")
0163             continue
0164 
0165         x_min = min(filter(
0166             lambda v: v is not None,
0167             map(lambda a: ak.min(ak.mask(a, np.isfinite(a))), arr[key].values())
0168         ), default=None)
0169         if x_min is None:
0170             continue
0171         nbins = 10
0172 
0173         if (any("* uint" in str(ak.type(a)) for a in arr[key].values())
0174            or any("* int" in str(ak.type(a)) for a in arr[key].values())):
0175             x_max = max(filter(
0176                 lambda v: v is not None,
0177                 map(lambda a: ak.max(ak.mask(a, np.isfinite(a))), arr[key].values())
0178             ), default=None)
0179             x_range = integer_axis_range(x_min, x_max)
0180             nbins = int(min(100, x_range))
0181         else:
0182             x_range = max(filter(
0183                 lambda v: v is not None,
0184                 map(lambda a: ak.max(ak.mask(a - x_min, np.isfinite(a))), arr[key].values())
0185             ), default=None)
0186             x_range = x_range * 1.1
0187 
0188         if x_range == 0:
0189             x_range = 1
0190 
0191         if "." in key:
0192             branch_name = key.split(".", 1)[0]
0193             leaf_name = key
0194         else:
0195             branch_name = key
0196             leaf_name = key
0197 
0198         # Plots are stored as compact histogram data and rendered client-side
0199         # by buildCollectionLayout() in index.html. Serializing full Bokeh
0200         # documents instead made the per-collection files ~10x larger.
0201         plot = {"x_axis_label": leaf_name, "x_min": float(x_min), "x_width": float(x_range), "series": []}
0202         if x_range < 1.:
0203             plot["x_format"] = "%.2g"
0204         collection_plots.setdefault(branch_name, []).append(plot)
0205         y_max = 0
0206 
0207         prev_file_arr = None
0208 
0209         leaf_min_pvalue = 1.0
0210         if set(arr[key].keys()) != set(files):
0211             # not every file has the key
0212             collection_with_diffs[branch_name] = 0.0
0213             leaf_min_pvalue = 0.0
0214 
0215         for file_index, (_file, label) in enumerate(zip(files, labels)):
0216             if file_index >= len(_VIS_PARAMS):
0217                 break
0218             if _file not in arr[key]:
0219                 continue
0220             file_arr = arr[key][_file]
0221 
0222             # diff, KS and Anderson-Darling k-sample tests
0223             pvalue = None
0224             ks_pvalue = None
0225             ad_pvalue = None
0226             if prev_file_arr is not None:
0227                 if ((ak.num(file_arr, axis=0) != ak.num(prev_file_arr, axis=0))
0228                    or ak.any(ak.num(file_arr, axis=1)
0229                              != ak.num(prev_file_arr, axis=1))
0230                    or ak.any(ak.nan_to_none(file_arr)
0231                              != ak.nan_to_none(prev_file_arr))):
0232                     if (ak.num(ak.flatten(file_arr, axis=None), axis=0) > 0 and
0233                         ak.num(ak.flatten(prev_file_arr, axis=None), axis=0) > 0):
0234                         # We can only apply the tests on non-empty arrays
0235                         flat_a = ak.to_numpy(ak.flatten(file_arr, axis=None))
0236                         flat_b = ak.to_numpy(ak.flatten(prev_file_arr, axis=None))
0237                         # Fast path: identical flattened contents
0238                         if (flat_a.shape == flat_b.shape
0239                                 and np.array_equal(flat_a, flat_b)):
0240                             ks_pvalue = 1.0
0241                             ad_pvalue = 1.0
0242                         else:
0243                             ks_pvalue = kstest(flat_a, flat_b).pvalue
0244                             # AD cost grows ~linearly with sample size and
0245                             # dominates the total runtime for high-multiplicity
0246                             # collections. Subsample above _AD_MAX_N per side:
0247                             # AD at N=1e4 already resolves p-values well below
0248                             # any threshold we colour on, so larger samples buy
0249                             # no useful sensitivity.
0250                             rng = _ad_rng(key)
0251                             ad_a, ad_b = flat_a, flat_b
0252                             if len(ad_a) > _AD_MAX_N:
0253                                 ad_a = rng.choice(ad_a, _AD_MAX_N, replace=False)
0254                             if len(ad_b) > _AD_MAX_N:
0255                                 ad_b = rng.choice(ad_b, _AD_MAX_N, replace=False)
0256                             try:
0257                                 # anderson_ksamp fails if all samples are
0258                                 # identical or if there are too few distinct
0259                                 # values.
0260                                 ad_result = anderson_ksamp(
0261                                     [ad_a, ad_b],
0262                                     # n_resamples sets p-value resolution;
0263                                     # batch bounds peak memory (permutations
0264                                     # are otherwise materialized all at once,
0265                                     # which OOMs on large samples).
0266                                     # Seed the permutation RNG from the same
0267                                     # per-key stream used for subsampling so
0268                                     # the reported p-value is reproducible.
0269                                     method=PermutationMethod(n_resamples=999, batch=200, rng=rng),
0270                                     variant="midrank",
0271                                 )
0272                                 ad_pvalue = float(ad_result.pvalue)
0273                             except (ValueError, TypeError):
0274                                 ad_pvalue = None
0275                         if ad_pvalue is None:
0276                             pvalue = ks_pvalue
0277                         else:
0278                             pvalue = min(ks_pvalue, ad_pvalue)
0279                     else:
0280                         ks_pvalue = 0
0281                         ad_pvalue = 0
0282                         pvalue = 0
0283                     print(key)
0284                     print(f"p_KS = {ks_pvalue:.3f}",
0285                           f"p_AD = {ad_pvalue:.3f}" if ad_pvalue is not None else "p_AD = n/a")
0286                     print(prev_file_arr)
0287                     print(file_arr)
0288                     collection_with_diffs[branch_name] = min(pvalue, collection_with_diffs.get(branch_name, 1.))
0289                     collection_ks_pvalue[branch_name] = min(ks_pvalue, collection_ks_pvalue.get(branch_name, 1.))
0290                     if ad_pvalue is not None:
0291                         collection_ad_pvalue[branch_name] = min(ad_pvalue, collection_ad_pvalue.get(branch_name, 1.))
0292                     leaf_min_pvalue = min(leaf_min_pvalue, pvalue)
0293 
0294             # Figure
0295             h = (
0296                 Hist.new
0297                 .Reg(nbins, 0, x_range, name="x", label=key)
0298                 .Int64()
0299             )
0300             h.fill(x=ak.flatten(file_arr - x_min, axis=None))
0301 
0302             ys, _ = h.to_numpy()
0303             y0 = np.concatenate([ys, [ys[-1]]])
0304             legend_parts = [label]
0305             if ks_pvalue is not None:
0306                 legend_parts.append(f"{100*ks_pvalue:.0f}%CL KS")
0307             if ad_pvalue is not None:
0308                 legend_parts.append(f"{100*ad_pvalue:.0f}%CL AD")
0309             plot["series"].append({
0310                 "style": file_index,
0311                 "legend_label": "\n".join(legend_parts),
0312                 "counts": ys.tolist(),
0313             })
0314 
0315             y_max = max(y_max, np.max(y0 + np.sqrt(y0)))
0316             prev_file_arr = file_arr
0317 
0318         if leaf_min_pvalue == 1.0:
0319             collection_matching_count[branch_name] = collection_matching_count.get(branch_name, 0) + 1
0320 
0321         x_bounds = (x_min - 0.05 * x_range, x_min + 1.05 * x_range)
0322         y_bounds = (- 0.05 * y_max, 1.05 * y_max)
0323         # Set y range for histograms
0324         if np.all(np.isfinite(x_bounds)):
0325             plot["x_range"] = [float(v) for v in x_bounds]
0326         else:
0327             click.secho(f"overflow while calculating x bounds for \"{key}\"", fg="red", err=True)
0328         if np.all(np.isfinite(y_bounds)):
0329             plot["y_range"] = [float(v) for v in y_bounds]
0330         else:
0331             click.secho(f"overflow while calculating y bounds for \"{key}\"", fg="red", err=True)
0332 
0333     def to_filename(branch_name):
0334         return branch_name.replace("#", "__pound__").replace("/", "__underscore__")
0335 
0336     def option_key(item):
0337         collection_name, figs = item
0338         key = ""
0339         if collection_name in collection_with_diffs:
0340             if collection_with_diffs[collection_name] > 0.99:
0341                 key += " 0.99"
0342             elif collection_with_diffs[collection_name] > 0.95:
0343                 key += " 0.95"
0344             elif collection_with_diffs[collection_name] > 0.67:
0345                 key += " 0.67"
0346             else:
0347                 key += " 0.00"
0348         key += collection_name.lstrip("_")
0349         return key
0350 
0351     options = [("", "")]
0352     for collection_name, figs in sorted(collection_plots.items(), key=option_key):
0353         marker = ""
0354         if collection_name in collection_with_diffs:
0355             if collection_with_diffs[collection_name] > 0.99:
0356                 marker = " (*)"
0357             elif collection_with_diffs[collection_name] > 0.95:
0358                 marker = " (**)"
0359             elif collection_with_diffs[collection_name] > 0.67:
0360                 marker = " (***)"
0361             else:
0362                 marker = " (****)"
0363         options.append((to_filename(collection_name), collection_name + marker))
0364 
0365     from bokeh.models import CustomJS, Select, DataTable, TableColumn, HTMLTemplateFormatter, NumberFormatter, StringFormatter
0366     from bokeh.models.comparisons import CustomJSCompare
0367 
0368     # BokehJS creates the comparator as new Function("x", "y", ..., code),
0369     # so the cell values are available as `x` and `y` in the snippet.
0370     _ks_sorter = CustomJSCompare(code="""
0371         if (x === '' && y === '') return 0;
0372         if (x === '') return 1;
0373         if (y === '') return -1;
0374         const nx = parseFloat(x), ny = parseFloat(y);
0375         return nx < ny ? -1 : nx > ny ? 1 : 0;
0376     """)
0377 
0378     _ad_sorter = CustomJSCompare(code="""
0379         if (x === '' && y === '') return 0;
0380         if (x === '') return 1;
0381         if (y === '') return -1;
0382         if (x === 'n/a' && y === 'n/a') return 0;
0383         if (x === 'n/a') return 1;
0384         if (y === 'n/a') return -1;
0385         const nx = parseFloat(x), ny = parseFloat(y);
0386         return nx < ny ? -1 : nx > ny ? 1 : 0;
0387     """)
0388 
0389     def mk_summary_table():
0390         rows = []
0391         for collection_name, figs in sorted(
0392             collection_plots.items(),
0393             key=lambda item: item[0].lstrip("_"),
0394         ):
0395             if collection_name in collection_with_diffs:
0396                 pvalue = collection_with_diffs[collection_name]
0397                 if pvalue > 0.99:
0398                     color = "#28a745"  # green
0399                 elif pvalue > 0.95:
0400                     color = "#ffc107"  # yellow
0401                 elif pvalue > 0.67:
0402                     color = "#fd7e14"  # orange
0403                 else:
0404                     color = "#dc3545"  # red
0405                 ks_str = (f"{collection_ks_pvalue[collection_name]:.3f}"
0406                           if collection_name in collection_ks_pvalue else "")
0407                 ad_str = (f"{collection_ad_pvalue[collection_name]:.3f}"
0408                           if collection_name in collection_ad_pvalue else "n/a")
0409             else:
0410                 color = "transparent"
0411                 ks_str = ""
0412                 ad_str = ""
0413             n_total = len(figs)
0414             n_match = collection_matching_count.get(collection_name, 0)
0415             n_diff = n_total - n_match
0416             rows.append((collection_name, color, ks_str, ad_str, n_match, n_diff, n_total))
0417 
0418         source = ColumnDataSource({
0419             "collection": [r[0] for r in rows],
0420             "filename":   [to_filename(r[0]) for r in rows],
0421             "color":      [r[1] for r in rows],
0422             "ks_pvalue":  [r[2] for r in rows],
0423             "ad_pvalue":  [r[3] for r in rows],
0424             "nmatch":     [r[4] for r in rows],
0425             "ndiff":      [r[5] for r in rows],
0426             "nplots":     [r[6] for r in rows],
0427         })
0428         square_style = (
0429             'display:inline-block;width:0.9em;height:0.9em;'
0430             'margin-right:6px;vertical-align:middle;'
0431             'border:1px solid #999;background-color:<%= color %>;'
0432         )
0433         link_fmt = HTMLTemplateFormatter(
0434             template=f'<span style="{square_style}"></span>'
0435                      '<a href="#<%= filename %>"><%= value %></a>'
0436         )
0437         right_str = StringFormatter(text_align="right")
0438         right_num = NumberFormatter(text_align="right")
0439         columns = [
0440             TableColumn(field="collection", title="Collection", formatter=link_fmt, width=500),
0441             TableColumn(field="ks_pvalue", title="min KS p-value", formatter=right_str, width=120, sorter=_ks_sorter),
0442             TableColumn(field="ad_pvalue", title="min AD p-value", formatter=right_str, width=120, sorter=_ad_sorter),
0443             TableColumn(field="nmatch", title="# matching", formatter=right_num, width=80),
0444             TableColumn(field="ndiff", title="# differing", formatter=right_num, width=80),
0445             TableColumn(field="nplots", title="# plots", formatter=right_num, width=80),
0446         ]
0447         table = DataTable(
0448             source=source,
0449             columns=columns,
0450             width=800,
0451             sizing_mode="stretch_height",
0452             index_position=None,
0453             sortable=True,
0454             selectable=True,
0455             name="summary_table",
0456         )
0457         source.selected.js_on_change("indices", CustomJS(args={"source": source}, code="""
0458           const idx = cb_obj.indices;
0459           if (idx.length > 0) {
0460             // Meta/ctrl/shift-click is meant to open the row's link in a new
0461             // tab; don't also navigate this tab via the row-selection handler.
0462             if (window._lastClickModified) {
0463               source.selected.indices = [];
0464               return;
0465             }
0466             // The hashchange handler in index.html loads the collection page.
0467             window.location.hash = "#" + source.data["filename"][idx[0]];
0468           }
0469         """))
0470         return table
0471 
0472     def mk_dropdown(value=""):
0473         dropdown = Select(title="Select branch (**** < 67% CL, ..., * > 99% CL stat. equiv.):", value=value, options=options)
0474         dropdown.js_on_change("value", CustomJS(code="""
0475           console.log('dropdown: ' + this.value, this.toString())
0476           if (this.value != "") {
0477             // The hashchange handler in index.html loads the collection page.
0478             window.location.hash = "#" + this.value;
0479           } else {
0480             // Empty option selected: navigate back to the index page.
0481             window.location.hash = "";
0482           }
0483         """))
0484         return dropdown
0485 
0486 
0487     from bokeh.layouts import column
0488     import json
0489 
0490     os.makedirs("capybara-reports", exist_ok=True)
0491 
0492     for collection_name, plots in collection_plots.items():
0493         with gzip.open(f"capybara-reports/{to_filename(collection_name)}.json.gz", "wt") as fp:
0494             json.dump({"collection": collection_name, "plots": plots}, fp, separators=(',', ':'))
0495 
0496     curdoc().js_on_event(DocumentReady, CustomJS(args={"all_options": options, "vis_params": _VIS_PARAMS}, code="""
0497       window._bokehSelectOptions = all_options;
0498 
0499       // Build the layout for one collection page from its compact .json.gz
0500       // data: a branch dropdown above a grid of histograms (one per leaf, one
0501       // step line with a sqrt(N) error band per input file).
0502       function buildCollectionLayout(item, location) {
0503         const {figure, gridplot} = Bokeh.Plotting;
0504         const figs = item.plots.map(function(plot) {
0505           const opts = {x_axis_label: plot.x_axis_label, y_axis_label: "Entries"};
0506           if (plot.x_range) {
0507             opts.x_range = new Bokeh.Range1d({start: plot.x_range[0], end: plot.x_range[1], bounds: plot.x_range});
0508           }
0509           if (plot.y_range) {
0510             opts.y_range = new Bokeh.Range1d({start: plot.y_range[0], end: plot.y_range[1], bounds: plot.y_range});
0511           }
0512           const fig = figure(opts);
0513           if (plot.x_format) {
0514             fig.xaxis.formatter = new Bokeh.PrintfTickFormatter({format: plot.x_format});
0515           }
0516           for (const series of plot.series) {
0517             const [color, line_width, line_dash, hatch_pattern] = vis_params[series.style];
0518             // Bin edges plus a repeated last count so that the final bin is
0519             // drawn by the "after" step mode.
0520             const nbins = series.counts.length;
0521             const x = new Float64Array(nbins + 1);
0522             const y = new Float64Array(nbins + 1);
0523             const y1 = new Float64Array(nbins + 1);
0524             const y2 = new Float64Array(nbins + 1);
0525             for (let i = 0; i <= nbins; i++) {
0526               const n = series.counts[Math.min(i, nbins - 1)];
0527               x[i] = plot.x_min + plot.x_width * (i / nbins);
0528               y[i] = n;
0529               y1[i] = n - Math.sqrt(n);
0530               y2[i] = n + Math.sqrt(n);
0531             }
0532             const source = new Bokeh.ColumnDataSource({data: {x, y, y1, y2}});
0533             const step_r = fig.step({
0534               x: {field: "x"}, y: {field: "y"}, mode: "after", source,
0535               legend_label: series.legend_label,
0536               line_color: color, line_width, line_dash,
0537             });
0538             step_r.nonselection_glyph = step_r.glyph;
0539             const varea_r = fig.varea_step({
0540               x: {field: "x"}, y1: {field: "y1"}, y2: {field: "y2"}, step_mode: "after", source,
0541               legend_label: series.legend_label,
0542               fill_color: hatch_pattern == " " ? color : null,
0543               fill_alpha: 0.25,
0544               hatch_color: color, hatch_alpha: 0.5, hatch_pattern,
0545             });
0546             varea_r.nonselection_glyph = varea_r.glyph;
0547           }
0548           if (plot.series.length > 0) {
0549             fig.legend.background_fill_alpha = 0.5; // make legend more transparent
0550             fig.legend.location = "top_left"; // left-align so glyph markers stay inside the canvas
0551           }
0552           return fig;
0553         });
0554         const dropdown = new Bokeh.Widgets.Select({
0555           title: "Select branch (**** < 67% CL, ..., * > 99% CL stat. equiv.):",
0556           value: location,
0557           options: window._bokehSelectOptions,
0558         });
0559         dropdown.on_change(dropdown.properties.value, function() {
0560           if (dropdown.value != "") {
0561             // onhashchange loads the collection page.
0562             window.location.hash = "#" + dropdown.value;
0563           } else {
0564             // Empty option selected: navigate back to the index page.
0565             window.location.hash = "";
0566           }
0567         });
0568         return new Bokeh.Column({children: [
0569           dropdown,
0570           gridplot(figs, {ncols: 3, width: 400, height: 300}),
0571         ]});
0572       }
0573 
0574       // Record whether a modifier key was held for the most recent click so the
0575       // table row-selection handler can tell a plain click (navigate this tab)
0576       // from a meta/ctrl/shift-click (open the link in a new tab only).
0577       document.addEventListener('mousedown', function(e) {
0578         window._lastClickModified = e.metaKey || e.ctrlKey || e.shiftKey;
0579       }, true);
0580 
0581       function fetchAndReplaceBokehDocument(location) {
0582         fetch(location + '.json.gz')
0583           .then(async function(response) {
0584             if (!response.ok) {
0585                 throw new Error('Network response was not ok');
0586             }
0587 
0588             const ds = new DecompressionStream('gzip');
0589             const decompressedStream = response.body.pipeThrough(ds);
0590             const decompressedResponse = new Response(decompressedStream);
0591             const item = await decompressedResponse.json();
0592 
0593             const doc = Bokeh.documents[0];
0594             doc.clear();
0595             doc.add_root(buildCollectionLayout(item, location));
0596           })
0597           .catch(function(error) {
0598             console.error('Fetch or decompression failed:', error);
0599           });
0600       }
0601 
0602       // The hash encodes both the current page and the index table's sort state
0603       // as "#<filename>?sort=<field>:<asc|desc>;...". Keeping the sort in the
0604       // hash lets it survive the full-page reload that happens when navigating
0605       // back to the (regenerated) index page.
0606       function parseHash() {
0607         var raw = window.location.hash.replace(/^#/, "");
0608         var qi = raw.indexOf("?");
0609         if (qi < 0) {
0610           return { location: raw, query: "" };
0611         }
0612         return { location: raw.slice(0, qi), query: raw.slice(qi + 1) };
0613       }
0614 
0615       function parseSort(query) {
0616         var s = new URLSearchParams(query).get("sort");
0617         if (!s) {
0618           return [];
0619         }
0620         return s.split(";").map(function(tok) {
0621           var parts = tok.split(":");
0622           return { field: parts[0], sortAsc: parts[1] !== "desc" };
0623         }).filter(function(c) { return c.field; });
0624       }
0625 
0626       function encodeSort(cols) {
0627         if (!cols || cols.length === 0) {
0628           return "";
0629         }
0630         return cols.map(function(c) {
0631           return c.field + ":" + (c.sortAsc ? "asc" : "desc");
0632         }).join(";");
0633       }
0634 
0635       // Set or clear a single parameter of the hash query, keeping the current
0636       // page and the other parameters intact. Uses replaceState so that
0637       // re-sorting/scrolling does not pile up history entries.
0638       function updateHashParam(key, value) {
0639         var h = parseHash();
0640         var params = new URLSearchParams(h.query);
0641         if (value === null || value === "") {
0642           params.delete(key);
0643         } else {
0644           params.set(key, value);
0645         }
0646         var q = params.toString();
0647         history.replaceState(null, "", "#" + h.location + (q ? "?" + q : ""));
0648       }
0649 
0650       function getSummaryTableView() {
0651         try {
0652           return Bokeh.index.query_one(function(v) {
0653             return v.model && v.model.name === "summary_table" && v.grid != null;
0654           });
0655         } catch (e) {
0656           return null;
0657         }
0658       }
0659 
0660       function applySortToTable(cols, attempt) {
0661         attempt = attempt || 0;
0662         var view = getSummaryTableView();
0663         if (view == null) {
0664           if (attempt < 40) {
0665             setTimeout(function() { applySortToTable(cols, attempt + 1); }, 50);
0666           }
0667           return;
0668         }
0669         var byField = {};
0670         view.grid.getColumns().forEach(function(gc) { byField[gc.field] = gc; });
0671         var slickSort = [], dataSort = [];
0672         cols.forEach(function(c) {
0673           var gc = byField[c.field];
0674           if (gc) {
0675             slickSort.push({ columnId: gc.id, sortAsc: c.sortAsc });
0676             dataSort.push({ sortCol: gc, sortAsc: c.sortAsc });
0677           }
0678         });
0679         view.grid.setSortColumns(slickSort);
0680         view.data.sort(dataSort);
0681         view.grid.invalidate();
0682         view.grid.render();
0683         view.model.update_sort_columns(dataSort);
0684       }
0685 
0686       function setupSortPersistence(attempt) {
0687         attempt = attempt || 0;
0688         var view = getSummaryTableView();
0689         if (view == null) {
0690           if (attempt < 40) {
0691             setTimeout(function() { setupSortPersistence(attempt + 1); }, 50);
0692           }
0693           return;
0694         }
0695         var query = parseHash().query;
0696         var initial = parseSort(query);
0697         if (initial.length > 0) {
0698           applySortToTable(initial);
0699         }
0700         view.grid.onSort.subscribe(function(_event, args) {
0701           var cols = (args.sortCols || []).map(function(sc) {
0702             return { field: sc.sortCol.field, sortAsc: sc.sortAsc };
0703           });
0704           updateHashParam("sort", encodeSort(cols) || null);
0705         });
0706 
0707         // The vertical scroll position lives in the SlickGrid viewport, which is
0708         // recreated (and reset) by the full-page reload on back navigation.
0709         // Persist it in the hash too so it survives the round trip.
0710         function viewport() {
0711           return view.shadow_el ? view.shadow_el.querySelector(".slick-viewport") : null;
0712         }
0713         var savedScroll = parseInt(new URLSearchParams(query).get("scroll") || "0", 10);
0714         if (savedScroll > 0) {
0715           setTimeout(function() {
0716             var vp = viewport();
0717             if (vp) { vp.scrollTop = savedScroll; }
0718           }, 150);
0719         }
0720         var scrollTimer = null;
0721         view.grid.onScroll.subscribe(function() {
0722           if (scrollTimer) { clearTimeout(scrollTimer); }
0723           scrollTimer = setTimeout(function() {
0724             // Guard against a late-firing timer writing to a collection page's
0725             // hash if the user navigated away right after scrolling.
0726             if (parseHash().location !== "") { return; }
0727             var vp = viewport();
0728             var y = vp ? Math.round(vp.scrollTop) : 0;
0729             updateHashParam("scroll", y > 0 ? String(y) : null);
0730           }, 150);
0731         });
0732       }
0733 
0734       window.onhashchange = function() {
0735         var location = parseHash().location;
0736         if (location == "") {
0737           // No page in the hash: return to the index page. Since there is no
0738           // index.json.gz, just reload the page to get a fresh index.html (the
0739           // sort is restored from the hash by setupSortPersistence).
0740           if (typeof window.current_location !== 'undefined') {
0741             window.location.reload();
0742           }
0743           return;
0744         }
0745         if ((typeof current_location === 'undefined') || (current_location != location)) {
0746           fetchAndReplaceBokehDocument(location);
0747           window.current_location = location;
0748         }
0749       }
0750       window.onhashchange();
0751       setupSortPersistence();
0752     """))
0753     # bokeh-api provides the BokehJS plotting API used by buildCollectionLayout()
0754     resources = Resources(mode="cdn", components=[*Resources._default_components, "bokeh-api"])
0755     output_file(filename="capybara-reports/index.html", title="ePIC capybara report", mode="cdn")
0756     save(column(
0757         mk_dropdown(),
0758         mk_summary_table(),
0759         sizing_mode="stretch_height",
0760     ), resources=resources)
0761 
0762     if serve:
0763         os.chdir("capybara-reports/")
0764         from http.server import SimpleHTTPRequestHandler
0765         from socketserver import TCPServer
0766         with TCPServer(("127.0.0.1", 24535), SimpleHTTPRequestHandler) as httpd:
0767             print("Serving report at http://127.0.0.1:24535")
0768             try:
0769                 httpd.serve_forever()
0770             except KeyboardInterrupt:
0771                 pass