Skip to content

Universe

A class to help with running the analysis of a single universe contained within a multiverse analysis.

Attributes:

Name Type Description
run_no

The run number of the multiverse analysis.

universe_id

The id of the universe.

universe

The universe settings.

output_dir

The directory to which the output should be written.

metrics

A dictionary containing the metrics to be computed.

fairness_metrics

A dictionary containing the fairness metrics to be computed.

ts_start

The timestamp of the start of the analysis.

ts_end

The timestamp of the end of the analysis.

Source code in multiversum/universe.py
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
class Universe:
    """
    A class to help with running the analysis of a single universe contained
    within a multiverse analysis.

    Attributes:
        run_no: The run number of the multiverse analysis.
        universe_id: The id of the universe.
        universe: The universe settings.
        output_dir: The directory to which the output should be written.
        metrics: A dictionary containing the metrics to be computed.
        fairness_metrics: A dictionary containing the fairness metrics to be
            computed.
        ts_start: The timestamp of the start of the analysis.
        ts_end: The timestamp of the end of the analysis.
    """

    metrics = None
    fairness_metrics = None
    ts_start = None
    ts_end = None

    def __init__(
        self,
        settings: Union[str, Dict[str, Any]],
        metrics: Optional[Dict[str, Callable]] = None,
        fairness_metrics: Optional[Dict[str, Callable]] = None,
        expand_dicts: bool = False,
        set_seed: bool = True,
    ) -> None:
        """
        Initialize the Universe class.

        The arguments should be passed in from the larger multiverse analysis.

        Args:
            settings: The settings for the universe analysis. This can usually
                just be passed along from the multiverse analysis. You only need
                to specify this yourself when developing / trying out an
                analysis. Possible keys in the dictionary are:
                - dimensions: The specified universe dimensions. This is the
                    only required information.
                - run_no: The run number of the multiverse analysis.
                - seed: The seed to use for analyses.
                - universe_id: The id of the universe.
                output_dir: The directory to which the output should be written.
            metrics: A dictionary containing the metrics to be computed.
                Pass an empty dictionary to not compute any.
            fairness_metrics: A dictionary containing the fairness metrics to be
                computed. (These are cumputed with awareness of groups.)
                Pass an empty dictionary to not compute any.
            expand_dicts: Whether to expand dictionaries in the dimensions i.e.
                if there are any dictionaries in the dimensions, expand them into
                separate dimensions of their own. Defaults to False.
            set_seed: Whether to use the seed provided in the settings.
                Defaults to True. Please note, that this only sets the seed in
                the Python random module and numpy.
        """
        self.ts_start = time.time()

        # Check whether global overrides are present
        global_overwrite_settings = search_in_parent_frames(
            SCRIPT_GLOBAL_OVERWRITE_NAME
        )
        if global_overwrite_settings is not None:
            print(
                f"Detected {SCRIPT_GLOBAL_OVERWRITE_NAME}, the settings argument will be ignored."
            )
            settings = global_overwrite_settings

        # Extract settings
        parsed_settings = (
            json.loads(settings) if isinstance(settings, str) else settings
        )

        self.run_no = parsed_settings["run_no"] if "run_no" in parsed_settings else 0
        self.universe_id = (
            parsed_settings["universe_id"]
            if "universe_id" in parsed_settings
            else "no-universe-id-provided"
        )
        self.dimensions = parsed_settings["dimensions"]
        if expand_dicts:
            # Create a new dictionary to store expanded dimensions
            expanded_dimensions = {}
            # Process each key-value pair in dimensions
            for key, value in self.dimensions.items():
                if isinstance(value, dict):
                    # For dictionary values, add all key-value pairs to root level
                    # but don't expand nested dictionaries further
                    expanded_dimensions.update(value)
                else:
                    # For non-dictionary values, keep them as is
                    expanded_dimensions[key] = value
            self.dimensions = expanded_dimensions

        self.seed = parsed_settings["seed"] if "seed" in parsed_settings else 0
        self.output_dir = (
            Path(parsed_settings["output_dir"])
            if "output_dir" in parsed_settings
            else Path("./output")
        )

        self.metrics = metrics
        self.fairness_metrics = fairness_metrics

        if self.dimensions is None:
            warnings.warn("No dimensions specified for universe analysis.")

        if set_seed:
            print(f"Setting seed to {self.seed} (in: [random, numpy.random]).")
            random.seed(self.seed)
            np.random.seed(self.seed)

    def get_execution_time(self) -> float:
        """
        Gets the execution time of the universe analysis.

        Returns:
            float: The execution time in seconds.
        """
        if self.ts_end is None:
            print("Stopping execution_time clock.")
            self.ts_end = time.time()
        return self.ts_end - self.ts_start

    def _add_universe_info(
        self, data: pd.DataFrame, overwrite_dimensions: Optional[dict] = None
    ) -> pd.DataFrame:
        """
        Add general universe / run info to the dataframe.

        Args:
            data: The dataframe to which the info should be added.
            overwrite_dimensions: A dictionary containing dimensions to overwrite. (optional)

        Returns:
            The dataframe with the added info.
        """
        return add_universe_info_to_df(
            data=data,
            universe_id=self.universe_id,
            run_no=self.run_no,
            dimensions=self.dimensions
            if overwrite_dimensions is None
            else overwrite_dimensions,
            execution_time=self.get_execution_time(),
        )

    def save_data(self, data: pd.DataFrame, add_info: bool = True) -> None:
        """
        Save the data to the appropriate file for this Universe.

        Args:
            data: The dataframe to be saved.
            add_info: Whether to add universe info to the dataframe. (optional)

        Returns:
            None
        """
        # Add universe data to the dataframe
        if add_info:
            data = self._add_universe_info(data=data)

        # Path management
        target_dir = self.output_dir / "runs" / str(self.run_no) / "data"
        # Make sure the directory exists
        target_dir.mkdir(parents=True, exist_ok=True)
        filename = f"d_{str(self.run_no)}_{self.universe_id}.csv"
        filepath = target_dir / filename
        if filepath.exists():
            warnings.warn(f"File {filepath} already exists. Overwriting it.")
        # Write the file
        data.to_csv(filepath, index=False)

    def compute_sub_universe_metrics(
        self,
        sub_universe: Dict,
        y_pred_prob: pd.Series,
        y_test: pd.Series,
        org_test: pd.DataFrame,
    ) -> Tuple[dict, dict]:
        """
        Computes a set of metrics for a given sub-universe.

        Args:
            sub_universe: A dictionary containing the parameters for the
                sub-universe.
            y_pred_prob: A pandas series containing the predicted
                probabilities.
            y_test: A pandas series containing the true labels.
            org_test: A pandas dataframe containing the test data, including
                variables that were not used as features.

        Returns:
            A tuple containing two dics: explicit fairness metrics and
                performance metrics split by fairness groups.
        """
        # Determine cutoff for predictions
        cutoff_type, cutoff_value = sub_universe["cutoff"].split("_")
        cutoff_value = float(cutoff_value)

        if cutoff_type == "raw":
            threshold = cutoff_value
        elif cutoff_type == "quantile":
            probabilities_true = y_pred_prob[:, 1]
            threshold = np.quantile(probabilities_true, cutoff_value)

        fairness_grouping = sub_universe["eval_fairness_grouping"]
        if fairness_grouping == "majority-minority":
            fairness_group_column = "majmin"
        elif fairness_grouping == "race-all":
            fairness_group_column = "RAC1P"

        y_pred = predict_w_threshold(y_pred_prob, threshold)

        try:
            from fairlearn.metrics import (
                MetricFrame,
                count,
                demographic_parity_difference,
                demographic_parity_ratio,
                equalized_odds_difference,
                equalized_odds_ratio,
                false_negative_rate,
                false_positive_rate,
                selection_rate,
            )
            from sklearn.metrics import (
                accuracy_score,
                balanced_accuracy_score,
                f1_score,
                precision_score,
            )

            metrics = (
                {
                    "accuracy": accuracy_score,
                    "balanced accuracy": balanced_accuracy_score,
                    "f1": f1_score,
                    "precision": precision_score,
                    "false positive rate": false_positive_rate,
                    "false negative rate": false_negative_rate,
                    "selection rate": selection_rate,
                    "count": count,
                }
                if self.metrics is None
                else self.metrics
            )

            fairness_metrics = (
                {
                    "equalized_odds_difference": equalized_odds_difference,
                    "equalized_odds_ratio": equalized_odds_ratio,
                    "demographic_parity_difference": demographic_parity_difference,
                    "demographic_parity_ratio": demographic_parity_ratio,
                }
                if self.fairness_metrics is None
                else self.fairness_metrics
            )

            # Compute fairness metrics
            fairness_dict = {
                name: metric(
                    y_true=y_test,
                    y_pred=y_pred,
                    sensitive_features=org_test[fairness_group_column],
                )
                for name, metric in fairness_metrics.items()
            }

            # Compute "normal" metrics (but split by fairness column)
            metric_frame = MetricFrame(
                metrics=metrics,
                y_true=y_test,
                y_pred=y_pred,
                sensitive_features=org_test[fairness_group_column],
            )

            return (fairness_dict, metric_frame)
        except ImportError:
            raise ImportError(
                "Packages fairlearn and scikit-learn are required for computing metrics."
            )

    def visit_sub_universe(
        self,
        sub_universe: Dict[str, Any],
        y_pred_prob: pd.Series,
        y_test: pd.Series,
        org_test: pd.Series,
        filter_data: Callable,
    ) -> pd.DataFrame:
        """
        Visit a sub-universe and compute the metrics for it.

        Sub-universes correspond to theoretically distinct universes of
        decisions, which can be computed without re-fitting a model. The
        distinction has only been made to improve performance by not having to
        compute these universes from scratch.

        Args:
            sub_universe: A dictionary containing the parameters for the
                sub-universe.
            y_pred_prob: A pandas series containing the predicted
                probabilities.
            y_test: A pandas series containing the true labels.
            org_test: A pandas dataframe containing the test data, including
                variables that were not used as features.
            filter_data: A function that filters data for each sub-universe.
                The function is called for each sub-universe with its
                respective settings and expected to return a pandas Series
                of booleans.

        Returns:
            A pandas dataframe containing the metrics for the sub-universe.
        """
        final_output = self._add_universe_info(
            data=pd.DataFrame(index=[self.universe_id]),
            overwrite_dimensions=sub_universe,
        )

        data_mask = filter_data(sub_universe=sub_universe, org_test=org_test)
        final_output["test_size_n"] = data_mask.sum()
        final_output["test_size_frac"] = data_mask.sum() / len(data_mask)

        # Compute metrics for majority-minority split
        fairness_dict, metric_frame = self.compute_sub_universe_metrics(
            sub_universe,
            y_pred_prob[data_mask],
            y_test[data_mask],
            org_test[data_mask],
        )

        # Add main fairness metrics to final_output
        final_output = add_dict_to_df(final_output, fairness_dict, prefix="fair_main_")
        final_output = add_dict_to_df(
            final_output, dict(metric_frame.overall), prefix="perf_ovrl_"
        )

        # Add group metrics to final output
        final_output = add_dict_to_df(
            final_output, flatten_dict(metric_frame.by_group), prefix="perf_grp_"
        )

        return final_output

    def generate_sub_universes(self) -> List[dict]:
        """
        Generate the sub-universes for the given universe settings.

        Returns:
            A list of dictionaries containing the sub-universes.
        """
        # Wrap all non-lists in the universe to make them work with generate_multiverse_grid
        universe_all_lists = {k: list_wrap(v) for k, v in self.dimensions.items()}

        # Within-Universe variation
        return generate_multiverse_grid(universe_all_lists)

    def compute_final_metrics(
        self,
        y_pred_prob: pd.Series,
        y_test: pd.Series,
        org_test: pd.Series,
        filter_data: Callable,
        save: bool = True,
    ) -> pd.DataFrame:
        """
        Generate the final output for the given universe settings.

        Args:
            y_pred_prob: A pandas series containing the predicted
                probabilities.
            y_test: A pandas series containing the true labels.
            org_test: A pandas dataframe containing the test data, including
                variables that were not used as features.
            filter_data: A function that filters data for each sub-universe.
                The function is called for each sub-universe with its
                respective settings and expected to return a pandas Series
                of booleans.
            save: Whether to save the output to a file. (optional)

        Returns:
            A pandas dataframe containing the final output.
        """
        # Within-Universe variation
        sub_universes = self.generate_sub_universes()

        final_outputs = list()
        for sub_universe in sub_universes:
            final_outputs.append(
                self.visit_sub_universe(
                    sub_universe=sub_universe,
                    y_pred_prob=y_pred_prob,
                    y_test=y_test,
                    org_test=org_test,
                    filter_data=filter_data,
                ).reset_index(drop=True)
            )
        final_output = pd.concat(final_outputs)

        # Write the final output file
        if save:
            self.save_data(final_output, add_info=False)

        return final_output

__init__(settings, metrics=None, fairness_metrics=None, expand_dicts=False, set_seed=True)

Initialize the Universe class.

The arguments should be passed in from the larger multiverse analysis.

Parameters:

Name Type Description Default
settings Union[str, Dict[str, Any]]

The settings for the universe analysis. This can usually just be passed along from the multiverse analysis. You only need to specify this yourself when developing / trying out an analysis. Possible keys in the dictionary are: - dimensions: The specified universe dimensions. This is the only required information. - run_no: The run number of the multiverse analysis. - seed: The seed to use for analyses. - universe_id: The id of the universe. output_dir: The directory to which the output should be written.

required
metrics Optional[Dict[str, Callable]]

A dictionary containing the metrics to be computed. Pass an empty dictionary to not compute any.

None
fairness_metrics Optional[Dict[str, Callable]]

A dictionary containing the fairness metrics to be computed. (These are cumputed with awareness of groups.) Pass an empty dictionary to not compute any.

None
expand_dicts bool

Whether to expand dictionaries in the dimensions i.e. if there are any dictionaries in the dimensions, expand them into separate dimensions of their own. Defaults to False.

False
set_seed bool

Whether to use the seed provided in the settings. Defaults to True. Please note, that this only sets the seed in the Python random module and numpy.

True
Source code in multiversum/universe.py
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
def __init__(
    self,
    settings: Union[str, Dict[str, Any]],
    metrics: Optional[Dict[str, Callable]] = None,
    fairness_metrics: Optional[Dict[str, Callable]] = None,
    expand_dicts: bool = False,
    set_seed: bool = True,
) -> None:
    """
    Initialize the Universe class.

    The arguments should be passed in from the larger multiverse analysis.

    Args:
        settings: The settings for the universe analysis. This can usually
            just be passed along from the multiverse analysis. You only need
            to specify this yourself when developing / trying out an
            analysis. Possible keys in the dictionary are:
            - dimensions: The specified universe dimensions. This is the
                only required information.
            - run_no: The run number of the multiverse analysis.
            - seed: The seed to use for analyses.
            - universe_id: The id of the universe.
            output_dir: The directory to which the output should be written.
        metrics: A dictionary containing the metrics to be computed.
            Pass an empty dictionary to not compute any.
        fairness_metrics: A dictionary containing the fairness metrics to be
            computed. (These are cumputed with awareness of groups.)
            Pass an empty dictionary to not compute any.
        expand_dicts: Whether to expand dictionaries in the dimensions i.e.
            if there are any dictionaries in the dimensions, expand them into
            separate dimensions of their own. Defaults to False.
        set_seed: Whether to use the seed provided in the settings.
            Defaults to True. Please note, that this only sets the seed in
            the Python random module and numpy.
    """
    self.ts_start = time.time()

    # Check whether global overrides are present
    global_overwrite_settings = search_in_parent_frames(
        SCRIPT_GLOBAL_OVERWRITE_NAME
    )
    if global_overwrite_settings is not None:
        print(
            f"Detected {SCRIPT_GLOBAL_OVERWRITE_NAME}, the settings argument will be ignored."
        )
        settings = global_overwrite_settings

    # Extract settings
    parsed_settings = (
        json.loads(settings) if isinstance(settings, str) else settings
    )

    self.run_no = parsed_settings["run_no"] if "run_no" in parsed_settings else 0
    self.universe_id = (
        parsed_settings["universe_id"]
        if "universe_id" in parsed_settings
        else "no-universe-id-provided"
    )
    self.dimensions = parsed_settings["dimensions"]
    if expand_dicts:
        # Create a new dictionary to store expanded dimensions
        expanded_dimensions = {}
        # Process each key-value pair in dimensions
        for key, value in self.dimensions.items():
            if isinstance(value, dict):
                # For dictionary values, add all key-value pairs to root level
                # but don't expand nested dictionaries further
                expanded_dimensions.update(value)
            else:
                # For non-dictionary values, keep them as is
                expanded_dimensions[key] = value
        self.dimensions = expanded_dimensions

    self.seed = parsed_settings["seed"] if "seed" in parsed_settings else 0
    self.output_dir = (
        Path(parsed_settings["output_dir"])
        if "output_dir" in parsed_settings
        else Path("./output")
    )

    self.metrics = metrics
    self.fairness_metrics = fairness_metrics

    if self.dimensions is None:
        warnings.warn("No dimensions specified for universe analysis.")

    if set_seed:
        print(f"Setting seed to {self.seed} (in: [random, numpy.random]).")
        random.seed(self.seed)
        np.random.seed(self.seed)

_add_universe_info(data, overwrite_dimensions=None)

Add general universe / run info to the dataframe.

Parameters:

Name Type Description Default
data DataFrame

The dataframe to which the info should be added.

required
overwrite_dimensions Optional[dict]

A dictionary containing dimensions to overwrite. (optional)

None

Returns:

Type Description
DataFrame

The dataframe with the added info.

Source code in multiversum/universe.py
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
def _add_universe_info(
    self, data: pd.DataFrame, overwrite_dimensions: Optional[dict] = None
) -> pd.DataFrame:
    """
    Add general universe / run info to the dataframe.

    Args:
        data: The dataframe to which the info should be added.
        overwrite_dimensions: A dictionary containing dimensions to overwrite. (optional)

    Returns:
        The dataframe with the added info.
    """
    return add_universe_info_to_df(
        data=data,
        universe_id=self.universe_id,
        run_no=self.run_no,
        dimensions=self.dimensions
        if overwrite_dimensions is None
        else overwrite_dimensions,
        execution_time=self.get_execution_time(),
    )

compute_final_metrics(y_pred_prob, y_test, org_test, filter_data, save=True)

Generate the final output for the given universe settings.

Parameters:

Name Type Description Default
y_pred_prob Series

A pandas series containing the predicted probabilities.

required
y_test Series

A pandas series containing the true labels.

required
org_test Series

A pandas dataframe containing the test data, including variables that were not used as features.

required
filter_data Callable

A function that filters data for each sub-universe. The function is called for each sub-universe with its respective settings and expected to return a pandas Series of booleans.

required
save bool

Whether to save the output to a file. (optional)

True

Returns:

Type Description
DataFrame

A pandas dataframe containing the final output.

Source code in multiversum/universe.py
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
def compute_final_metrics(
    self,
    y_pred_prob: pd.Series,
    y_test: pd.Series,
    org_test: pd.Series,
    filter_data: Callable,
    save: bool = True,
) -> pd.DataFrame:
    """
    Generate the final output for the given universe settings.

    Args:
        y_pred_prob: A pandas series containing the predicted
            probabilities.
        y_test: A pandas series containing the true labels.
        org_test: A pandas dataframe containing the test data, including
            variables that were not used as features.
        filter_data: A function that filters data for each sub-universe.
            The function is called for each sub-universe with its
            respective settings and expected to return a pandas Series
            of booleans.
        save: Whether to save the output to a file. (optional)

    Returns:
        A pandas dataframe containing the final output.
    """
    # Within-Universe variation
    sub_universes = self.generate_sub_universes()

    final_outputs = list()
    for sub_universe in sub_universes:
        final_outputs.append(
            self.visit_sub_universe(
                sub_universe=sub_universe,
                y_pred_prob=y_pred_prob,
                y_test=y_test,
                org_test=org_test,
                filter_data=filter_data,
            ).reset_index(drop=True)
        )
    final_output = pd.concat(final_outputs)

    # Write the final output file
    if save:
        self.save_data(final_output, add_info=False)

    return final_output

compute_sub_universe_metrics(sub_universe, y_pred_prob, y_test, org_test)

Computes a set of metrics for a given sub-universe.

Parameters:

Name Type Description Default
sub_universe Dict

A dictionary containing the parameters for the sub-universe.

required
y_pred_prob Series

A pandas series containing the predicted probabilities.

required
y_test Series

A pandas series containing the true labels.

required
org_test DataFrame

A pandas dataframe containing the test data, including variables that were not used as features.

required

Returns:

Type Description
Tuple[dict, dict]

A tuple containing two dics: explicit fairness metrics and performance metrics split by fairness groups.

Source code in multiversum/universe.py
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
def compute_sub_universe_metrics(
    self,
    sub_universe: Dict,
    y_pred_prob: pd.Series,
    y_test: pd.Series,
    org_test: pd.DataFrame,
) -> Tuple[dict, dict]:
    """
    Computes a set of metrics for a given sub-universe.

    Args:
        sub_universe: A dictionary containing the parameters for the
            sub-universe.
        y_pred_prob: A pandas series containing the predicted
            probabilities.
        y_test: A pandas series containing the true labels.
        org_test: A pandas dataframe containing the test data, including
            variables that were not used as features.

    Returns:
        A tuple containing two dics: explicit fairness metrics and
            performance metrics split by fairness groups.
    """
    # Determine cutoff for predictions
    cutoff_type, cutoff_value = sub_universe["cutoff"].split("_")
    cutoff_value = float(cutoff_value)

    if cutoff_type == "raw":
        threshold = cutoff_value
    elif cutoff_type == "quantile":
        probabilities_true = y_pred_prob[:, 1]
        threshold = np.quantile(probabilities_true, cutoff_value)

    fairness_grouping = sub_universe["eval_fairness_grouping"]
    if fairness_grouping == "majority-minority":
        fairness_group_column = "majmin"
    elif fairness_grouping == "race-all":
        fairness_group_column = "RAC1P"

    y_pred = predict_w_threshold(y_pred_prob, threshold)

    try:
        from fairlearn.metrics import (
            MetricFrame,
            count,
            demographic_parity_difference,
            demographic_parity_ratio,
            equalized_odds_difference,
            equalized_odds_ratio,
            false_negative_rate,
            false_positive_rate,
            selection_rate,
        )
        from sklearn.metrics import (
            accuracy_score,
            balanced_accuracy_score,
            f1_score,
            precision_score,
        )

        metrics = (
            {
                "accuracy": accuracy_score,
                "balanced accuracy": balanced_accuracy_score,
                "f1": f1_score,
                "precision": precision_score,
                "false positive rate": false_positive_rate,
                "false negative rate": false_negative_rate,
                "selection rate": selection_rate,
                "count": count,
            }
            if self.metrics is None
            else self.metrics
        )

        fairness_metrics = (
            {
                "equalized_odds_difference": equalized_odds_difference,
                "equalized_odds_ratio": equalized_odds_ratio,
                "demographic_parity_difference": demographic_parity_difference,
                "demographic_parity_ratio": demographic_parity_ratio,
            }
            if self.fairness_metrics is None
            else self.fairness_metrics
        )

        # Compute fairness metrics
        fairness_dict = {
            name: metric(
                y_true=y_test,
                y_pred=y_pred,
                sensitive_features=org_test[fairness_group_column],
            )
            for name, metric in fairness_metrics.items()
        }

        # Compute "normal" metrics (but split by fairness column)
        metric_frame = MetricFrame(
            metrics=metrics,
            y_true=y_test,
            y_pred=y_pred,
            sensitive_features=org_test[fairness_group_column],
        )

        return (fairness_dict, metric_frame)
    except ImportError:
        raise ImportError(
            "Packages fairlearn and scikit-learn are required for computing metrics."
        )

generate_sub_universes()

Generate the sub-universes for the given universe settings.

Returns:

Type Description
List[dict]

A list of dictionaries containing the sub-universes.

Source code in multiversum/universe.py
472
473
474
475
476
477
478
479
480
481
482
483
def generate_sub_universes(self) -> List[dict]:
    """
    Generate the sub-universes for the given universe settings.

    Returns:
        A list of dictionaries containing the sub-universes.
    """
    # Wrap all non-lists in the universe to make them work with generate_multiverse_grid
    universe_all_lists = {k: list_wrap(v) for k, v in self.dimensions.items()}

    # Within-Universe variation
    return generate_multiverse_grid(universe_all_lists)

get_execution_time()

Gets the execution time of the universe analysis.

Returns:

Name Type Description
float float

The execution time in seconds.

Source code in multiversum/universe.py
239
240
241
242
243
244
245
246
247
248
249
def get_execution_time(self) -> float:
    """
    Gets the execution time of the universe analysis.

    Returns:
        float: The execution time in seconds.
    """
    if self.ts_end is None:
        print("Stopping execution_time clock.")
        self.ts_end = time.time()
    return self.ts_end - self.ts_start

save_data(data, add_info=True)

Save the data to the appropriate file for this Universe.

Parameters:

Name Type Description Default
data DataFrame

The dataframe to be saved.

required
add_info bool

Whether to add universe info to the dataframe. (optional)

True

Returns:

Type Description
None

None

Source code in multiversum/universe.py
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
def save_data(self, data: pd.DataFrame, add_info: bool = True) -> None:
    """
    Save the data to the appropriate file for this Universe.

    Args:
        data: The dataframe to be saved.
        add_info: Whether to add universe info to the dataframe. (optional)

    Returns:
        None
    """
    # Add universe data to the dataframe
    if add_info:
        data = self._add_universe_info(data=data)

    # Path management
    target_dir = self.output_dir / "runs" / str(self.run_no) / "data"
    # Make sure the directory exists
    target_dir.mkdir(parents=True, exist_ok=True)
    filename = f"d_{str(self.run_no)}_{self.universe_id}.csv"
    filepath = target_dir / filename
    if filepath.exists():
        warnings.warn(f"File {filepath} already exists. Overwriting it.")
    # Write the file
    data.to_csv(filepath, index=False)

visit_sub_universe(sub_universe, y_pred_prob, y_test, org_test, filter_data)

Visit a sub-universe and compute the metrics for it.

Sub-universes correspond to theoretically distinct universes of decisions, which can be computed without re-fitting a model. The distinction has only been made to improve performance by not having to compute these universes from scratch.

Parameters:

Name Type Description Default
sub_universe Dict[str, Any]

A dictionary containing the parameters for the sub-universe.

required
y_pred_prob Series

A pandas series containing the predicted probabilities.

required
y_test Series

A pandas series containing the true labels.

required
org_test Series

A pandas dataframe containing the test data, including variables that were not used as features.

required
filter_data Callable

A function that filters data for each sub-universe. The function is called for each sub-universe with its respective settings and expected to return a pandas Series of booleans.

required

Returns:

Type Description
DataFrame

A pandas dataframe containing the metrics for the sub-universe.

Source code in multiversum/universe.py
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
def visit_sub_universe(
    self,
    sub_universe: Dict[str, Any],
    y_pred_prob: pd.Series,
    y_test: pd.Series,
    org_test: pd.Series,
    filter_data: Callable,
) -> pd.DataFrame:
    """
    Visit a sub-universe and compute the metrics for it.

    Sub-universes correspond to theoretically distinct universes of
    decisions, which can be computed without re-fitting a model. The
    distinction has only been made to improve performance by not having to
    compute these universes from scratch.

    Args:
        sub_universe: A dictionary containing the parameters for the
            sub-universe.
        y_pred_prob: A pandas series containing the predicted
            probabilities.
        y_test: A pandas series containing the true labels.
        org_test: A pandas dataframe containing the test data, including
            variables that were not used as features.
        filter_data: A function that filters data for each sub-universe.
            The function is called for each sub-universe with its
            respective settings and expected to return a pandas Series
            of booleans.

    Returns:
        A pandas dataframe containing the metrics for the sub-universe.
    """
    final_output = self._add_universe_info(
        data=pd.DataFrame(index=[self.universe_id]),
        overwrite_dimensions=sub_universe,
    )

    data_mask = filter_data(sub_universe=sub_universe, org_test=org_test)
    final_output["test_size_n"] = data_mask.sum()
    final_output["test_size_frac"] = data_mask.sum() / len(data_mask)

    # Compute metrics for majority-minority split
    fairness_dict, metric_frame = self.compute_sub_universe_metrics(
        sub_universe,
        y_pred_prob[data_mask],
        y_test[data_mask],
        org_test[data_mask],
    )

    # Add main fairness metrics to final_output
    final_output = add_dict_to_df(final_output, fairness_dict, prefix="fair_main_")
    final_output = add_dict_to_df(
        final_output, dict(metric_frame.overall), prefix="perf_ovrl_"
    )

    # Add group metrics to final output
    final_output = add_dict_to_df(
        final_output, flatten_dict(metric_frame.by_group), prefix="perf_grp_"
    )

    return final_output