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
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
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
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,
        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.
            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()

        # 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"]
        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:
            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
            from sklearn.metrics import (
                accuracy_score,
                precision_score,
                balanced_accuracy_score,
                f1_score,
            )
            from fairlearn.metrics import (
                false_positive_rate,
                false_negative_rate,
                selection_rate,
                count,
            )
            from fairlearn.metrics import (
                equalized_odds_difference,
                equalized_odds_ratio,
                demographic_parity_difference,
                demographic_parity_ratio,
            )

            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, 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
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
117
118
119
120
121
122
123
124
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
def __init__(
    self,
    settings: Union[str, Dict[str, Any]],
    metrics: Optional[Dict[str, Callable]] = None,
    fairness_metrics: Optional[Dict[str, Callable]] = None,
    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.
        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()

    # 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"]
    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:
        random.seed(self.seed)
        np.random.seed(self.seed)

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
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
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
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
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
        from sklearn.metrics import (
            accuracy_score,
            precision_score,
            balanced_accuracy_score,
            f1_score,
        )
        from fairlearn.metrics import (
            false_positive_rate,
            false_negative_rate,
            selection_rate,
            count,
        )
        from fairlearn.metrics import (
            equalized_odds_difference,
            equalized_odds_ratio,
            demographic_parity_difference,
            demographic_parity_ratio,
        )

        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
414
415
416
417
418
419
420
421
422
423
424
425
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
179
180
181
182
183
184
185
186
187
188
189
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
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
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
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
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