<commit_before>import ROOT
ROOT.RooMsgService.instance().setGlobalKillBelow(5)
import itertools  # for fast looping
import time  # for timing loop


def sample_func_histogram(shape_function, n_events=1, n_bins=10, range_low=0, range_high=1, hist_name='data_hist'):
    """
    Sample a function. create an pdf from it, then histogram it

    Args:
        shape_function (TF1): The mathematical form of the function to be sampled
        n_events (int): The number of points to sample
        range_low (int, float): The lower bound on the sampling range
        range_high (int, float): The upper bound on the sampling range
        n_bins (int): The number of bins in the generated histogram
        hist_name (str): The name of the histogram object
    Returns:
        hist (TH1): The generated histogram of n_events
    """
    x = ROOT.RooRealVar('x', 'x', range_low, range_high)
    # Get the formula string of the TF1 with the parameters evaluated
    formula = str(shape_function.GetFormula().GetExpFormula("P"))
    pdf = ROOT.RooGenericPdf('mypdf', 'mypdf', formula, ROOT.RooArgList(x))
    data = pdf.generate(ROOT.RooArgSet(x), n_events)

    roo_data_hist = ROOT.RooDataHist(hist_name, "", ROOT.RooArgSet(x), data)
    hist = roo_data_hist.createHistogram(
        hist_name, x, ROOT.RooFit.Binning(n_bins, range_low, range_high))
    hist.Sumw2(False)
    hist.Sumw2()
    return hist


def make_sample(sample_name="sample", sample_histogram=None, uncertainty_down=None, uncertainty_up=None,
                shape_up_hist=None, shape_down_hist=None, has_theory_norm=False):
    """
    Construct a HistFactory.Sample()

    Args:
        sample_name (str): The name of the signal sample
        sample_histogram: A TH1 object that encodes the shape of the sample
        uncertainty_down (float): The downward normalisation systematic uncertainty (1.0 - uncertainty_down)
        uncertainty_up (float): The upward normalisation systematic uncertainty (1.0 + uncertainty_up)
        shape_up_hist: A TH1 object that encodes the updward sample shape uncertainty
        shape_down_hist: A TH1 object that encodes the downward sample shape uncertainty
        has_theory_norm (bool): Is the sample normalized by theory or not. Default is False.
    Returns:
        sample (HistFactory.Sample()): The constructed sample. Ex: signal sample, background sample
    """
    sample = ROOT.RooStats.HistFactory.Sample(sample_name)
    sample.SetNormalizeByTheory(has_theory_norm)
    sample.SetHisto(sample_histogram)
    #
    sample.AddNormFactor("SigXsecOverSM", 1, 0, 3)
    # Add normalisation systematic uncertainty
    if uncertainty_down and uncertainty_up:
        sample.AddOverallSys(sample_name + "_uncertainty",
                             1.0 - uncertainty_down, 1.0 + uncertainty_up)
    # Add signal shape systematic uncertainty
    if shape_up_hist and shape_down_hist:
        shape_systematic = ROOT.RooStats.HistFactory.HistoSys(
            sample_name + "_shape_sys")
        shape_systematic.SetHistoHigh(shape_up_hist)
        shape_systematic.SetHistoLow(shape_down_hist)
        sample.AddHistoSys(shape_systematic)
    return sample


def make_channel(channel_name="channel", channel_data=None, channel_samples=None):
    """
    Make a channel with data and associated samples

    Args:
        channel_name (str): The name of the channel.
            Example: If this channel represents a signal region, the name might be "SR"
        channel_data (TH1): The data histogram that describes the channel
        channel_samples (list of HistFactory.Sample()): The samples associated with the channel that describe
                                                        the model for the channel

    Returns:
        channel (HistFactor.Channel()): The channel object
    """
    channel = ROOT.RooStats.HistFactory.Channel(channel_name)
    channel.SetData(channel_data)
    channel.SetStatErrorConfig(0.05, "Poisson")
    if channel_samples:
        for sample in channel_samples:
            channel.AddSample(sample)
    return channel


def make_model(n_evnets, n_bins, channels, POI, workspace_name=None, workspace_save_path=None):
    """
    Args:
        n_events: The number of events
        n_bins: The numbe of bins
        channels (dictionary of HistFactory.Channel()): The channels in the model with associated samples
        # n_sig_comp: The number of signal components (automatically determined from the channels)
        # n_bkg_comp: The number of background components (automatically
        # determined from the channels)
        POI (list of str): The parameters of interest
        # n_nuisance: The number of nuisance parameters (automatically
        # determined from the samples)
        workspace_name (str): The name of the resulting RooStats.RooWorkspace()
        workspace_save_path (str): The path and filename (sans ".root") to save the workspace
    Returns:
        workspace (RooStats.RooWorkspace): The workspace for the measruement
        model (RooStats.RooSimultaneous): The model generated from the workspace
    """
    measurement = ROOT.RooStats.HistFactory.Measurement(
        "measurement", "measurement")
    for parameter in POI:
        measurement.SetPOI(parameter)
    # Set luminosity (arbitrary choices for now, which can be set later once
    # working)
    measurement.SetLumi(1.0)
    measurement.SetLumiRelErr(0.02)<commit_msg>Add ROOT.SetOwnership(variable_name, False) to avoid ownership issues<commit_after>import ROOT
ROOT.RooMsgService.instance().setGlobalKillBelow(5)
import itertools  # for fast looping
import time  # for timing loop


def sample_func_histogram(shape_function, n_events=1, n_bins=10, range_low=0, range_high=1, hist_name='data_hist'):
    """
    Sample a function. create an pdf from it, then histogram it

    Args:
        shape_function (TF1): The mathematical form of the function to be sampled
        n_events (int): The number of points to sample
        range_low (int, float): The lower bound on the sampling range
        range_high (int, float): The upper bound on the sampling range
        n_bins (int): The number of bins in the generated histogram
        hist_name (str): The name of the histogram object
    Returns:
        hist (TH1): The generated histogram of n_events
    """
    x = ROOT.RooRealVar('x', 'x', range_low, range_high)
    # Get the formula string of the TF1 with the parameters evaluated
    formula = str(shape_function.GetFormula().GetExpFormula("P"))
    pdf = ROOT.RooGenericPdf('mypdf', 'mypdf', formula, ROOT.RooArgList(x))
    data = pdf.generate(ROOT.RooArgSet(x), n_events)

    roo_data_hist = ROOT.RooDataHist(hist_name, "", ROOT.RooArgSet(x), data)
    hist = roo_data_hist.createHistogram(
        hist_name, x, ROOT.RooFit.Binning(n_bins, range_low, range_high))
    hist.Sumw2(False)
    hist.Sumw2()
    return hist


def make_sample(sample_name="sample", sample_histogram=None, uncertainty_down=None, uncertainty_up=None,
                shape_up_hist=None, shape_down_hist=None, has_theory_norm=False):
    """
    Construct a HistFactory.Sample()

    Args:
        sample_name (str): The name of the signal sample
        sample_histogram: A TH1 object that encodes the shape of the sample
        uncertainty_down (float): The downward normalisation systematic uncertainty (1.0 - uncertainty_down)
        uncertainty_up (float): The upward normalisation systematic uncertainty (1.0 + uncertainty_up)
        shape_up_hist: A TH1 object that encodes the updward sample shape uncertainty
        shape_down_hist: A TH1 object that encodes the downward sample shape uncertainty
        has_theory_norm (bool): Is the sample normalized by theory or not. Default is False.
    Returns:
        sample (HistFactory.Sample()): The constructed sample. Ex: signal sample, background sample
    """
    sample = ROOT.RooStats.HistFactory.Sample(sample_name)
    ROOT.SetOwnership(sample, False)
    sample.SetNormalizeByTheory(has_theory_norm)
    sample.SetHisto(sample_histogram)
    #
    sample.AddNormFactor("SigXsecOverSM", 1, 0, 3)
    # Add normalisation systematic uncertainty
    if uncertainty_down and uncertainty_up:
        sample.AddOverallSys(sample_name + "_uncertainty",
                             1.0 - uncertainty_down, 1.0 + uncertainty_up)
    # Add signal shape systematic uncertainty
    if shape_up_hist and shape_down_hist:
        shape_systematic = ROOT.RooStats.HistFactory.HistoSys(
            sample_name + "_shape_sys")
        shape_systematic.SetHistoHigh(shape_up_hist)
        shape_systematic.SetHistoLow(shape_down_hist)
        sample.AddHistoSys(shape_systematic)
    return sample


def make_channel(channel_name="channel", channel_data=None, channel_samples=None):
    """
    Make a channel with data and associated samples

    Args:
        channel_name (str): The name of the channel.
            Example: If this channel represents a signal region, the name might be "SR"
        channel_data (TH1): The data histogram that describes the channel
        channel_samples (list of HistFactory.Sample()): The samples associated with the channel that describe
                                                        the model for the channel

    Returns:
        channel (HistFactor.Channel()): The channel object
    """
    channel = ROOT.RooStats.HistFactory.Channel(channel_name)
    ROOT.SetOwnership(channel, False)
    channel.SetData(channel_data)
    channel.SetStatErrorConfig(0.05, "Poisson")
    if channel_samples:
        for sample in channel_samples:
            channel.AddSample(sample)
    return channel


def make_model(n_evnets, n_bins, channels, POI, workspace_name=None, workspace_save_path=None):
    """
    Args:
        n_events: The number of events
        n_bins: The numbe of bins
        channels (dictionary of HistFactory.Channel()): The channels in the model with associated samples
        # n_sig_comp: The number of signal components (automatically determined from the channels)
        # n_bkg_comp: The number of background components (automatically
        # determined from the channels)
        POI (list of str): The parameters of interest
        # n_nuisance: The number of nuisance parameters (automatically
        # determined from the samples)
        workspace_name (str): The name of the resulting RooStats.RooWorkspace()
        workspace_save_path (str): The path and filename (sans ".root") to save the workspace
    Returns:
        workspace (RooStats.RooWorkspace): The workspace for the measruement
        model (RooStats.RooSimultaneous): The model generated from the workspace
    """
    measurement = ROOT.RooStats.HistFactory.Measurement(
        "measurement", "measurement")
    ROOT.SetOwnership(measurement, False)
    for parameter in POI:
        measurement.SetPOI(parameter)
    # Set luminosity (arbitrary choices for now, which can be set later once
    # working)
    measurement.SetLumi(1.0)
    measurement.SetLumiRelErr(0.02)
{'fraction_non_alphanumeric': 0.07545116532148363, 'fraction_numerical': 0.006166681781082797, 'mean_word_length': 3.3094958968347012, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 6, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7368313', 'n_tokens_mistral': 3150, 'n_tokens_neox': 3069, 'n_words': 977}