Skip to content

Apheris Statistics Reference🔗

apheris_stats.simple_stats🔗

corr(datasets, session, column_names, global_means=None, group_by=None, handle_outliers=PrivacyHandlingMethod.RAISE) 🔗

Computes the federated pearson correlation matrix for a given set of columns. Args: datasets: datasets that the computation shall be run on session: For remote runs, use a SimpleStatsSession that refers to a cluster of Compute Clients and an Aggregator. If you want to simulate a cluster locally, use a LocalDummySimpleStatsSession or LocalDebugSimpleStatsSession. column_names: set of columns global_means: means over all datasets for given column names. If global_means is None, it will be automatically determined in a separate pre-run group_by: mapping, label, or list of labels, used to group before aggregation. handle_outliers: Parameter of enum type PrivacyHandlingMethod which specifies the handling method in case of bounded privacy violations. The implemented options are:

      - `PrivacyHandlingMethod.FILTER`: filters out all groups that are violating
         privacy bound.
      - `PrivacyHandlingMethod.FILTER_DATASET`: removes out the entire dataset
         from the federated computation in case of privacy violations.
      - `PrivacyHandlingMethod.RAISE`: raises a PrivacyException if privacy bound
         was violated.

    Default is `PrivacyHandlingMethod.RAISE`.

Returns: statistical result as a pandas DataFrame with the correlation matrix of the specified columns.

Example
corr_matrix = simple_stats.corr(
    datasets=[transformations_dataset_essex, transformations_dataset_norfolk],
    column_names=['age', 'length of covid infection'],
    global_means={'age': 50, 'length of covid infection': 10},
    session=session
)
Source code in .env/lib/python3.10/site-packages/apheris_stats/simple_stats/_core/simple_stats.py
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
def corr(
    datasets: Union[Iterable[FederatedDataFrame], FederatedDataFrame],
    session: Union[
        SimpleStatsSession, LocalDummySimpleStatsSession, LocalDebugSimpleStatsSession
    ],
    column_names: Iterable[str],
    global_means: Dict[Union[str, Tuple], Union[int, float, numbers.Number]] = None,
    group_by: Union[Hashable, Iterable[Hashable]] = None,
    handle_outliers: Union[PrivacyHandlingMethod, str] = PrivacyHandlingMethod.RAISE,
):
    """
    Computes the federated pearson correlation matrix for a given set of columns.
    Args:
        datasets: datasets that the computation shall be run on
        session: For remote runs, use a `SimpleStatsSession` that refers to a cluster
            of Compute Clients and an Aggregator. If you want to simulate a cluster
            locally, use a `LocalDummySimpleStatsSession` or
            `LocalDebugSimpleStatsSession`.
        column_names: set of columns
        global_means: means over all datasets for given column names. If global_means is
            None, it will be automatically determined in a separate pre-run
        group_by: mapping, label, or list of labels, used to group before aggregation.
        handle_outliers:
            Parameter of enum type PrivacyHandlingMethod which specifies
            the handling method in case of bounded privacy violations.
            The implemented options are:

              - `PrivacyHandlingMethod.FILTER`: filters out all groups that are violating
                 privacy bound.
              - `PrivacyHandlingMethod.FILTER_DATASET`: removes out the entire dataset
                 from the federated computation in case of privacy violations.
              - `PrivacyHandlingMethod.RAISE`: raises a PrivacyException if privacy bound
                 was violated.

            Default is `PrivacyHandlingMethod.RAISE`.
    Returns:
        statistical result as a pandas DataFrame with the
        correlation matrix of the specified columns.

    Example:
        ```
        corr_matrix = simple_stats.corr(
            datasets=[transformations_dataset_essex, transformations_dataset_norfolk],
            column_names=['age', 'length of covid infection'],
            global_means={'age': 50, 'length of covid infection': 10},
            session=session
        )

        ```
    """

    handle_outliers = _get_locally_validated_handle_outliers(handle_outliers)

    computation_args = {
        "numerical_columns": column_names,
        "group_by": group_by,
    }

    computation2_args = {
        "column_names": column_names,
        "global_means": global_means,
        "group_by": group_by,
    }

    results = _run_simple_stats(
        datasets=datasets,
        computation="tableone_pre_statistics",
        computation_args=computation_args,
        aggregation="corr_pre_statistics_aggregation",
        aggregation_args={},
        computation_2="pairwise_joint_errors_by_columns",
        computation_args_2=computation2_args,
        aggregation_2="corr_aggregation",
        aggregation_args_2={},
        is_2step=True,
        handle_outliers=handle_outliers,
        session=session,
    )

    results = _unpack_stats_output(results)
    return results

cov(datasets, session, column_names, global_means=None, group_by=None, handle_outliers=PrivacyHandlingMethod.RAISE) 🔗

Computes the federated covariance matrix for a given set of columns. Args: datasets: datasets that the computation shall be run on session: For remote runs, use a SimpleStatsSession that refers to a cluster of Compute Clients and an Aggregator. If you want to simulate a cluster locally, use a LocalDummySimpleStatsSession or LocalDebugSimpleStatsSession. column_names: set of columns global_means: means over all datasets for given column names. If global_means is None, it will be automatically determined in a separate pre-run group_by: mapping, label, or list of labels, used to group before aggregation. handle_outliers: Parameter of enum type PrivacyHandlingMethod which specifies the handling method in case of bounded privacy violations. The implemented options are:

      - `PrivacyHandlingMethod.FILTER`: filters out all groups that are violating
         privacy bound.
      - `PrivacyHandlingMethod.FILTER_DATASET`: removes out the entire dataset
         from the federated computation in case of privacy violations.
      - `PrivacyHandlingMethod.RAISE`: raises a PrivacyException if privacy bound
         was violated.

    Default is `PrivacyHandlingMethod.RAISE`.

Returns: statistical result as a pandas DataFrame with the correlation matrix of the specified columns.

Example
coc_matrix = simple_stats.cov(
    datasets=[transformations_dataset_essex, transformations_dataset_norfolk],
    column_names=['age', 'length of covid infection'],
    global_means={'age': 50, 'length of covid infection': 10},
    session=session
)
Source code in .env/lib/python3.10/site-packages/apheris_stats/simple_stats/_core/simple_stats.py
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
def cov(
    datasets: Union[Iterable[FederatedDataFrame], FederatedDataFrame],
    session: Union[
        SimpleStatsSession, LocalDummySimpleStatsSession, LocalDebugSimpleStatsSession
    ],
    column_names: Iterable[str],
    global_means: Dict[Union[str, Tuple], Union[int, float, numbers.Number]] = None,
    group_by: Union[Hashable, Iterable[Hashable]] = None,
    handle_outliers: Union[PrivacyHandlingMethod, str] = PrivacyHandlingMethod.RAISE,
):
    """
    Computes the federated covariance matrix for a given set of columns.
    Args:
        datasets: datasets that the computation shall be run on
        session: For remote runs, use a `SimpleStatsSession` that refers to a cluster
            of Compute Clients and an Aggregator. If you want to simulate a cluster
            locally, use a `LocalDummySimpleStatsSession` or
            `LocalDebugSimpleStatsSession`.
        column_names: set of columns
        global_means: means over all datasets for given column names. If global_means is
            None, it will be automatically determined in a separate pre-run
        group_by: mapping, label, or list of labels, used to group before aggregation.
        handle_outliers:
            Parameter of enum type PrivacyHandlingMethod which specifies
            the handling method in case of bounded privacy violations.
            The implemented options are:

              - `PrivacyHandlingMethod.FILTER`: filters out all groups that are violating
                 privacy bound.
              - `PrivacyHandlingMethod.FILTER_DATASET`: removes out the entire dataset
                 from the federated computation in case of privacy violations.
              - `PrivacyHandlingMethod.RAISE`: raises a PrivacyException if privacy bound
                 was violated.

            Default is `PrivacyHandlingMethod.RAISE`.
    Returns:
        statistical result as a pandas DataFrame with the
        correlation matrix of the specified columns.

    Example:
        ```
        coc_matrix = simple_stats.cov(
            datasets=[transformations_dataset_essex, transformations_dataset_norfolk],
            column_names=['age', 'length of covid infection'],
            global_means={'age': 50, 'length of covid infection': 10},
            session=session
        )

        ```
    """

    handle_outliers = _get_locally_validated_handle_outliers(handle_outliers)

    computation_args = {
        "numerical_columns": column_names,
        "group_by": group_by,
    }

    computation2_args = {
        "column_names": column_names,
        "global_means": global_means,
        "group_by": group_by,
    }

    results = _run_simple_stats(
        datasets=datasets,
        computation="tableone_pre_statistics",
        computation_args=computation_args,
        aggregation="corr_pre_statistics_aggregation",
        aggregation_args={},
        computation_2="pairwise_joint_errors_by_columns",
        computation_args_2=computation2_args,
        aggregation_2="cov_aggregation",
        aggregation_args_2={},
        is_2step=True,
        handle_outliers=handle_outliers,
        session=session,
    )

    results = _unpack_stats_output(results)
    return results

count_column_value(datasets, session, column_name, value, aggregation=True, handle_outliers=PrivacyHandlingMethod.RAISE) 🔗

Returns how often value appears in a certain column of the datasets.

Parameters:

Name Type Description Default
datasets Union[Iterable[FederatedDataFrame], FederatedDataFrame]

list of FederatedDataFrames that define the pre-preprocessing of individual datasets

required
session Union[SimpleStatsSession, LocalDummySimpleStatsSession, LocalDebugSimpleStatsSession]

For remote runs, use a SimpleStatsSession that refers to a cluster of Compute Clients and an Aggregator. If you want to simulate a cluster locally, use a LocalDummySimpleStatsSession or LocalDebugSimpleStatsSession.

required
column_name str

Name of the column over which the function shall be calculated

required
value

This value will be counted

required
aggregation bool

Defines whether the counts should be aggregated over all datasets or whether the counts should be returned per dataset.

True
handle_outliers Union[PrivacyHandlingMethod, str]

Parameter of enum type PrivacyHandlingMethod which specifies the handling method in case of bounded privacy violations. The implemented options are:

- PrivacyHandlingMethod.FILTER_DATASET: removes out the entire dataset from the federated computation in case of privacy violations. - PrivacyHandlingMethod.ROUND: only valid for counts, rounds to the privacy bound or 0. - PrivacyHandlingMethod.RAISE: raises a PrivacyException if privacy bound was violated.

Default is PrivacyHandlingMethod.RAISE.

RAISE

Returns:

Type Description

statistical result

Source code in .env/lib/python3.10/site-packages/apheris_stats/simple_stats/_core/simple_stats.py
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
def count_column_value(
    datasets: Union[Iterable[FederatedDataFrame], FederatedDataFrame],
    session: Union[
        SimpleStatsSession, LocalDummySimpleStatsSession, LocalDebugSimpleStatsSession
    ],
    column_name: str,
    value,
    aggregation: bool = True,
    handle_outliers: Union[PrivacyHandlingMethod, str] = PrivacyHandlingMethod.RAISE,
):
    """
    Returns how often `value` appears in a certain column of the `datasets`.

    Args:
        datasets: list of FederatedDataFrames that define the pre-preprocessing of
            individual datasets
        session: For remote runs, use a `SimpleStatsSession` that refers to a cluster
            of Compute Clients and an Aggregator. If you want to simulate a cluster
            locally, use a `LocalDummySimpleStatsSession` or
            `LocalDebugSimpleStatsSession`.
        column_name: Name of the column over which the function shall be calculated
        value: This value will be counted
        aggregation: Defines whether the counts should be aggregated over
            all `datasets` or whether the counts should be returned per dataset.
        handle_outliers:
            Parameter of enum type PrivacyHandlingMethod which specifies
            the handling method in case of bounded privacy violations.
            The implemented options are:

              - `PrivacyHandlingMethod.FILTER_DATASET`: removes out the entire dataset
                 from the federated computation in case of privacy violations.
              - `PrivacyHandlingMethod.ROUND`: only valid for counts, rounds to the
                 privacy bound or 0.
              - `PrivacyHandlingMethod.RAISE`: raises a PrivacyException if privacy bound
                 was violated.

            Default is `PrivacyHandlingMethod.RAISE`.

    Returns:
        statistical result
    """
    handle_outliers = _get_locally_validated_handle_outliers(
        handle_outliers,
        allowed_methods=[
            PrivacyHandlingMethod.ROUND,
            PrivacyHandlingMethod.RAISE,
            PrivacyHandlingMethod.FILTER_DATASET,
        ],
    )

    results = _run_simple_stats(
        datasets=datasets,
        computation="count_column_value",
        computation_args={"column_name": column_name, "value": value},
        aggregation="sum_aggregation" if aggregation else None,
        aggregation_args={},
        handle_outliers=handle_outliers,
        session=session,
    )
    if not aggregation:
        return _unpack_stats_output(results, ignore_keys=True)
    else:
        return results

count_group_by(datasets, session, column_name, handle_outliers=PrivacyHandlingMethod.RAISE) 🔗

Function that counts categorical values of a table column.

Parameters:

Name Type Description Default
datasets Union[Iterable[FederatedDataFrame], FederatedDataFrame]

list of FederatedDataFrames that define the pre-preprocessing of individual datasets.

required
session Union[SimpleStatsSession, LocalDummySimpleStatsSession, LocalDebugSimpleStatsSession]

For remote runs, use a SimpleStatsSession that refers to a cluster of Compute Clients and an Aggregator. If you want to simulate a cluster locally, use a LocalDummySimpleStatsSession or LocalDebugSimpleStatsSession.

required
column_name str

name of the column for which the statistical query shall be computed

required
handle_outliers Union[PrivacyHandlingMethod, str]

Parameter of enum type PrivacyHandlingMethod which specifies the handling method in case of bounded privacy violations. The implemented options are:

- PrivacyHandlingMethod.FILTER: filters out all groups that are violating privacy bound. - PrivacyHandlingMethod.FILTER_DATASET: removes out the entire dataset from the federated computation in case of privacy violations. - PrivacyHandlingMethod.ROUND: only valid for counts, rounds to the privacy bound or 0. - PrivacyHandlingMethod.RAISE: raises a PrivacyException if privacy bound was violated.

Default is PrivacyHandlingMethod.RAISE.

RAISE

Returns:

Type Description

statistical result. Its result contains a pandas DataFrame with the counts summed over the datasets.

Source code in .env/lib/python3.10/site-packages/apheris_stats/simple_stats/_core/simple_stats.py
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
def count_group_by(
    datasets: Union[Iterable[FederatedDataFrame], FederatedDataFrame],
    session: Union[
        SimpleStatsSession, LocalDummySimpleStatsSession, LocalDebugSimpleStatsSession
    ],
    column_name: str,
    handle_outliers: Union[PrivacyHandlingMethod, str] = PrivacyHandlingMethod.RAISE,
):
    """
    Function that counts categorical values of a table column.

    Args:
        datasets: list of FederatedDataFrames that define the pre-preprocessing of
            individual datasets.
        session: For remote runs, use a `SimpleStatsSession` that refers to a cluster
            of Compute Clients and an Aggregator. If you want to simulate a cluster
            locally, use a `LocalDummySimpleStatsSession` or
            `LocalDebugSimpleStatsSession`.
        column_name: name of the column for which the statistical query shall be computed
        handle_outliers:
            Parameter of enum type PrivacyHandlingMethod which specifies
            the handling method in case of bounded privacy violations.
            The implemented options are:

              - `PrivacyHandlingMethod.FILTER`: filters out all groups that are violating
                 privacy bound.
              - `PrivacyHandlingMethod.FILTER_DATASET`: removes out the entire dataset
                 from the federated computation in case of privacy violations.
              - `PrivacyHandlingMethod.ROUND`: only valid for counts, rounds to the
                 privacy bound or 0.
              - `PrivacyHandlingMethod.RAISE`: raises a PrivacyException if privacy bound
                 was violated.

            Default is `PrivacyHandlingMethod.RAISE`.


    Returns:
        statistical result. Its result contains a pandas DataFrame with the
            counts summed over the datasets.
    """
    handle_outliers = _get_locally_validated_handle_outliers(
        handle_outliers,
        allowed_methods=[
            PrivacyHandlingMethod.ROUND,
            PrivacyHandlingMethod.FILTER,
            PrivacyHandlingMethod.RAISE,
            PrivacyHandlingMethod.FILTER_DATASET,
        ],
    )
    results = _run_simple_stats(
        datasets=datasets,
        computation="count_group_by",
        computation_args={"group_by": column_name},
        aggregation="sum_aggregation",
        aggregation_args={"ignore_keys": True},
        handle_outliers=handle_outliers,
        session=session,
    )
    return results

count_null(datasets, session, column_name, group_by=None, aggregation=True, handle_outliers=PrivacyHandlingMethod.RAISE) 🔗

Returns the number of occurrences of NA values (such as None or numpy.NaN) and the number of non-NA values in the datasets. NA are counted based on panda's isna() and notna() functions.

Parameters:

Name Type Description Default
datasets Union[Iterable[FederatedDataFrame], FederatedDataFrame]

list of FederatedDataFrames that define the pre-preprocessing of individual datasets

required
session Union[SimpleStatsSession, LocalDummySimpleStatsSession, LocalDebugSimpleStatsSession]

For remote runs, use a SimpleStatsSession that refers to a cluster of Compute Clients and an Aggregator. If you want to simulate a cluster locally, use a LocalDummySimpleStatsSession or LocalDebugSimpleStatsSession.

required
column_name str

name of the column over which the NA values shall be counted

required
group_by Union[Hashable, Iterable[Hashable]]

(optional) mapping, label, or list of labels, used to group before aggregation.

None
aggregation bool

defines whether the counts should be aggregated over all datasets or whether the counts should be returned per dataset.

True
handle_outliers Union[PrivacyHandlingMethod, str]

Parameter of enum type PrivacyHandlingMethod which specifies the handling method in case of bounded privacy violations. The implemented options are:

- PrivacyHandlingMethod.FILTER: filters out all groups that are violating privacy bound. - PrivacyHandlingMethod.FILTER_DATASET: removes out the entire dataset from the federated computation in case of privacy violations. - PrivacyHandlingMethod.ROUND: only valid for counts, rounds to the privacy bound or 0. - PrivacyHandlingMethod.RAISE: raises a PrivacyException if privacy bound was violated.

Default is PrivacyHandlingMethod.RAISE.

RAISE

Returns:

Type Description

statistical result

Source code in .env/lib/python3.10/site-packages/apheris_stats/simple_stats/_core/simple_stats.py
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
def count_null(
    datasets: Union[Iterable[FederatedDataFrame], FederatedDataFrame],
    session: Union[
        SimpleStatsSession, LocalDummySimpleStatsSession, LocalDebugSimpleStatsSession
    ],
    column_name: str,
    group_by: Union[Hashable, Iterable[Hashable]] = None,
    aggregation: bool = True,
    handle_outliers: Union[PrivacyHandlingMethod, str] = PrivacyHandlingMethod.RAISE,
):
    """
    Returns the number of occurrences of `NA values` (such as `None` or
    `numpy.NaN`) and the number of `non-NA values` in the datasets. NA are counted based
    on panda's `isna()` and `notna()` functions.

    Args:
        datasets: list of FederatedDataFrames that define the pre-preprocessing of
            individual datasets
        session: For remote runs, use a `SimpleStatsSession` that refers to a cluster
            of Compute Clients and an Aggregator. If you want to simulate a cluster
            locally, use a `LocalDummySimpleStatsSession` or
            `LocalDebugSimpleStatsSession`.
        column_name: name of the column over which the NA values shall be counted
        group_by: (optional) mapping, label, or list of labels, used to group before
                aggregation.
        aggregation: defines whether the counts should be aggregated over all `datasets`
            or whether the counts should be returned per dataset.
        handle_outliers:
            Parameter of enum type PrivacyHandlingMethod which specifies
            the handling method in case of bounded privacy violations.
            The implemented options are:

              - `PrivacyHandlingMethod.FILTER`: filters out all groups that are violating
                 privacy bound.
              - `PrivacyHandlingMethod.FILTER_DATASET`: removes out the entire dataset
                 from the federated computation in case of privacy violations.
              - `PrivacyHandlingMethod.ROUND`: only valid for counts, rounds to the
                 privacy bound or 0.
              - `PrivacyHandlingMethod.RAISE`: raises a PrivacyException if privacy bound
                 was violated.

            Default is `PrivacyHandlingMethod.RAISE`.

    Returns:
        statistical result
    """
    handle_outliers = _get_locally_validated_handle_outliers(
        handle_outliers,
        allowed_methods=[
            PrivacyHandlingMethod.ROUND,
            PrivacyHandlingMethod.RAISE,
            PrivacyHandlingMethod.FILTER,
            PrivacyHandlingMethod.FILTER_DATASET,
        ],
    )

    results = _run_simple_stats(
        datasets=datasets,
        computation="count_null",
        computation_args={"column_name": column_name, "group_by": group_by},
        aggregation="sum_aggregation" if aggregation else None,
        aggregation_args={},
        handle_outliers=handle_outliers,
        session=session,
    )
    if not aggregation:
        return _unpack_stats_output(results)
    else:
        return results

describe(datasets, session, handle_outliers=PrivacyHandlingMethod.RAISE) 🔗

Create a description of a dataset

Parameters:

Name Type Description Default
datasets Union[Iterable[FederatedDataFrame], FederatedDataFrame]

list of FederatedDataFrames that define the pre-preprocessing of individual datasets.

required
session Union[SimpleStatsSession, LocalDummySimpleStatsSession, LocalDebugSimpleStatsSession]

For remote runs, use a SimpleStatsSession that refers to a cluster of Compute Clients and an Aggregator. If you want to simulate a cluster locally, use a LocalDummySimpleStatsSession or LocalDebugSimpleStatsSession.

required
handle_outliers Union[PrivacyHandlingMethod, str]

Parameter of enum type PrivacyHandlingMethod which specifies the handling method in case of bounded privacy violations. The implemented options are:

- PrivacyHandlingMethod.FILTER: filters out all groups that are violating privacy bound. - PrivacyHandlingMethod.FILTER_DATASET: removes out the entire dataset from the federated computation in case of privacy violations. - PrivacyHandlingMethod.RAISE: raises a PrivacyException if privacy bound was violated.

Default is PrivacyHandlingMethod.RAISE.

RAISE

Returns:

Type Description

statistical description of datasets

Source code in .env/lib/python3.10/site-packages/apheris_stats/simple_stats/_core/simple_stats.py
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
def describe(
    datasets: Union[Iterable[FederatedDataFrame], FederatedDataFrame],
    session: Union[
        SimpleStatsSession, LocalDummySimpleStatsSession, LocalDebugSimpleStatsSession
    ],
    handle_outliers: Union[PrivacyHandlingMethod, str] = PrivacyHandlingMethod.RAISE,
):
    """
    Create a description of a dataset

    Args:
        datasets: list of FederatedDataFrames that define the pre-preprocessing of
            individual datasets.
        session: For remote runs, use a `SimpleStatsSession` that refers to a cluster
            of Compute Clients and an Aggregator. If you want to simulate a cluster
            locally, use a `LocalDummySimpleStatsSession` or
            `LocalDebugSimpleStatsSession`.
        handle_outliers:
            Parameter of enum type PrivacyHandlingMethod which specifies
            the handling method in case of bounded privacy violations.
            The implemented options are:

              - `PrivacyHandlingMethod.FILTER`: filters out all groups that are violating
                 privacy bound.
              - `PrivacyHandlingMethod.FILTER_DATASET`: removes out the entire dataset
                 from the federated computation in case of privacy violations.
              - `PrivacyHandlingMethod.RAISE`: raises a PrivacyException if privacy bound
                 was violated.

            Default is `PrivacyHandlingMethod.RAISE`.

    Returns:
        statistical description of datasets
    """
    handle_outliers = _get_locally_validated_handle_outliers(handle_outliers)

    results = _run_simple_stats(
        datasets=datasets,
        computation="describe",
        computation_args={},
        handle_outliers=handle_outliers,
        aggregation=None,
        aggregation_args={},
        session=session,
    )
    results = _unpack_stats_output(results)

    # Drop the `total` level of the multi-index to match expected output format
    return {
        i: {"results": df["results"].reset_index(level=0, drop=True)}
        for i, df in results.items()
    }

histogram(datasets, session, column_name, bins, group_by=None, aggregation=True, handle_outliers=PrivacyHandlingMethod.RAISE) 🔗

Returns a histogram for the given datasets

Parameters:

Name Type Description Default
datasets Union[Iterable[FederatedDataFrame], FederatedDataFrame]

list of FederatedDataFrames that define the pre-preprocessing of individual datasets.

required
session Union[SimpleStatsSession, LocalDummySimpleStatsSession, LocalDebugSimpleStatsSession]

For remote runs, use a SimpleStatsSession that refers to a cluster of Compute Clients and an Aggregator. If you want to simulate a cluster locally, use a LocalDummySimpleStatsSession or LocalDebugSimpleStatsSession.

required
column_name str

name of the column for which the histogram shall be generated

required
bins

int or sequence of scalars. If bins is an int, it defines the number of bins with equal width. If it is a sequence, its content defines the bin edges.

required
group_by Union[Hashable, Iterable[Hashable]]

mapping, label, or list of labels, used to group before aggregation.

None
aggregation bool

If True, the histogram is aggregated over all datasets. Otherwise, one histogram will be returned per dataset. Aggregation is only feasible, if bins is an Iterable which defines the bin edges.

True
handle_outliers Union[PrivacyHandlingMethod, str]

Parameter of enum type PrivacyHandlingMethod which specifies the handling method in case of bounded privacy violations. The implemented options are:

- PrivacyHandlingMethod.FILTER: filters out all groups that are violating privacy bound. - PrivacyHandlingMethod.FILTER_DATASET: removes out the entire dataset from the federated computation in case of privacy violations. - PrivacyHandlingMethod.ROUND: only valid for counts, rounds to the privacy bound or 0. - PrivacyHandlingMethod.RAISE: raises a PrivacyException if privacy bound was violated.

Default is PrivacyHandlingMethod.RAISE.

RAISE

Returns: statistical result

Source code in .env/lib/python3.10/site-packages/apheris_stats/simple_stats/_core/simple_stats.py
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
def histogram(
    datasets: Union[Iterable[FederatedDataFrame], FederatedDataFrame],
    session: Union[
        SimpleStatsSession, LocalDummySimpleStatsSession, LocalDebugSimpleStatsSession
    ],
    column_name: str,
    bins,
    group_by: Union[Hashable, Iterable[Hashable]] = None,
    aggregation: bool = True,
    handle_outliers: Union[PrivacyHandlingMethod, str] = PrivacyHandlingMethod.RAISE,
):
    """
    Returns a histogram for the given datasets

    Args:
        datasets: list of FederatedDataFrames that define the pre-preprocessing of
            individual datasets.
        session: For remote runs, use a `SimpleStatsSession` that refers to a cluster
            of Compute Clients and an Aggregator. If you want to simulate a cluster
            locally, use a `LocalDummySimpleStatsSession` or
            `LocalDebugSimpleStatsSession`.
        column_name: name of the column for which the histogram shall be generated
        bins: int or sequence of scalars. If bins is an int, it defines the number of
            bins with equal width. If it is a sequence, its content defines the bin edges.
        group_by: mapping, label, or list of labels, used to group before aggregation.
        aggregation: If True, the histogram is aggregated over all `datasets`. Otherwise,
            one histogram will be returned per dataset. Aggregation is only feasible, if
            `bins` is an Iterable which defines the bin edges.
        handle_outliers:
            Parameter of enum type PrivacyHandlingMethod which specifies
            the handling method in case of bounded privacy violations.
            The implemented options are:

              - `PrivacyHandlingMethod.FILTER`: filters out all groups that are violating
                 privacy bound.
              - `PrivacyHandlingMethod.FILTER_DATASET`: removes out the entire dataset
                 from the federated computation in case of privacy violations.
              - `PrivacyHandlingMethod.ROUND`: only valid for counts, rounds to the
                 privacy bound or 0.
              - `PrivacyHandlingMethod.RAISE`: raises a PrivacyException if privacy bound
                 was violated.

            Default is `PrivacyHandlingMethod.RAISE`.
    Returns:
        statistical result
    """

    # ToDo: apheris.datatools.simple_stats.statistics.histogram raises error  for
    #  `if aggregation and (len(datasets) >= 1):`

    handle_outliers = _get_locally_validated_handle_outliers(
        handle_outliers,
        allowed_methods=[
            PrivacyHandlingMethod.ROUND,
            PrivacyHandlingMethod.FILTER,
            PrivacyHandlingMethod.RAISE,
            PrivacyHandlingMethod.FILTER_DATASET,
        ],
    )

    if aggregation and (len(datasets) >= 1):
        if not isinstance(bins, Iterable):
            raise TypeError(
                "If `aggregation` is True, `bins` is expected to be an Iterable that "
                "defines the bin edges. This is required to align the bins edges over "
                "all remote computations on different datasets. We received `bins` of "
                f"type {type(bins)}."
            )

    results = _run_simple_stats(
        datasets=datasets,
        computation="histogram_continuous",
        computation_args={
            "column_name": column_name,
            "bins": bins,
            "group_by": group_by,
        },
        aggregation="sum_aggregation" if aggregation else None,
        aggregation_args={},
        handle_outliers=handle_outliers,
        session=session,
    )
    if not aggregation:
        return _unpack_stats_output(results)
    else:
        return results

iqr_column(datasets, session, column_name, global_min_max, group_by=None, n_bins=100, handle_outliers=PrivacyHandlingMethod.RAISE) 🔗

Function to approximate the interquartile range (IQR) over multiple datasets. Internally, first a histogram with a user-defined number of bins and user-defined upper and lower bounds is created over all datasets. Based on this histogram the IQR is approximated.

Parameters:

Name Type Description Default
datasets Union[Iterable[FederatedDataFrame], FederatedDataFrame]

list of FederatedDataFrames that define the pre-preprocessing of individual datasets.

required
session Union[SimpleStatsSession, LocalDummySimpleStatsSession, LocalDebugSimpleStatsSession]

For remote runs, use a SimpleStatsSession that refers to a cluster of Compute Clients and an Aggregator. If you want to simulate a cluster locally, use a LocalDummySimpleStatsSession or LocalDebugSimpleStatsSession.

required
column_name str

name of the column for which the histogram shall be generated

required
global_min_max Iterable[float]

a list that contains the global minimum and maximum values of the combined datasets. This needs to be computed separately, using for example the function min_column/max_column combined with min_aggregation/max_aggregation.

required
group_by Union[Hashable, Iterable[Hashable]]

mapping, label, or list of labels, used to group before aggregation.

None
n_bins int

number of bins for internal histogram

100
handle_outliers Union[PrivacyHandlingMethod, str]

Parameter of enum type PrivacyHandlingMethod which specifies the handling method in case of bounded privacy violations. The implemented options are:

- PrivacyHandlingMethod.FILTER: filters out all groups that are violating privacy bound. - PrivacyHandlingMethod.FILTER_DATASET: removes out the entire dataset from the federated computation in case of privacy violations. - PrivacyHandlingMethod.RAISE: raises a PrivacyException if privacy bound was violated.

Default is PrivacyHandlingMethod.RAISE.

RAISE

Returns:

Type Description

statistical result

Source code in .env/lib/python3.10/site-packages/apheris_stats/simple_stats/_core/simple_stats.py
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
def iqr_column(
    datasets: Union[Iterable[FederatedDataFrame], FederatedDataFrame],
    session: Union[
        SimpleStatsSession, LocalDummySimpleStatsSession, LocalDebugSimpleStatsSession
    ],
    column_name: str,
    global_min_max: Iterable[float],
    group_by: Union[Hashable, Iterable[Hashable]] = None,
    n_bins: int = 100,
    handle_outliers: Union[PrivacyHandlingMethod, str] = PrivacyHandlingMethod.RAISE,
):
    """
    Function to approximate the interquartile range (IQR) over multiple
    datasets. Internally, first a histogram with a user-defined number of bins and
    user-defined upper and lower bounds is created over all datasets. Based on this
    histogram the IQR is approximated.


    Args:
        datasets: list of FederatedDataFrames that define the pre-preprocessing of
            individual datasets.
        session: For remote runs, use a `SimpleStatsSession` that refers to a cluster
            of Compute Clients and an Aggregator. If you want to simulate a cluster
            locally, use a `LocalDummySimpleStatsSession` or
            `LocalDebugSimpleStatsSession`.
        column_name: name of the column for which the histogram shall be generated
        global_min_max: a list that contains the global minimum and maximum values
            of the combined datasets. This needs to be computed separately, using for
            example the function `min_column`/`max_column` combined with
            `min_aggregation`/`max_aggregation`.
        group_by: mapping, label, or list of labels, used to group before aggregation.
        n_bins: number of bins for internal histogram
        handle_outliers:
            Parameter of enum type PrivacyHandlingMethod which specifies
            the handling method in case of bounded privacy violations.
            The implemented options are:

              - `PrivacyHandlingMethod.FILTER`: filters out all groups that are violating
                 privacy bound.
              - `PrivacyHandlingMethod.FILTER_DATASET`: removes out the entire dataset
                 from the federated computation in case of privacy violations.
              - `PrivacyHandlingMethod.RAISE`: raises a PrivacyException if privacy bound
                 was violated.

            Default is `PrivacyHandlingMethod.RAISE`.

    Returns:
        statistical result
    """
    handle_outliers = _get_locally_validated_handle_outliers(handle_outliers)

    results = _run_simple_stats(
        datasets=datasets,
        computation="iqr_column",
        computation_args={
            "column_name": column_name,
            "global_min_max": global_min_max,
            "n_bins": n_bins,
            "group_by": group_by,
        },
        aggregation="iqr_aggregation",
        aggregation_args={"global_min_max": global_min_max},
        handle_outliers=handle_outliers,
        session=session,
    )
    return results

kaplan_meier(datasets, session, duration_column_name, event_column_name, group_by=None, plot=False, stepsize=1, handle_outliers=PrivacyHandlingMethod.RAISE) 🔗

Create a Kaplan Meier survival statistic

Parameters:

Name Type Description Default
datasets Union[Iterable[FederatedDataFrame], FederatedDataFrame]

list of FederatedDataFrames that define the pre-preprocessing of individual datasets.

required
session Union[SimpleStatsSession, LocalDummySimpleStatsSession, LocalDebugSimpleStatsSession]

For remote runs, use a SimpleStatsSession that refers to a cluster of Compute Clients and an Aggregator. If you want to simulate a cluster locally, use a LocalDummySimpleStatsSession or LocalDebugSimpleStatsSession.

required
duration_column_name str

duration column for survival function

required
event_column_name str

event column - indicating death

required
group_by str

grouping column

None
plot

if True results will be displayed using pd.DataFrame.plot()

False
stepsize int

histogram bin size

1
handle_outliers Union[PrivacyHandlingMethod, str]

Parameter of enum type PrivacyHandlingMethod which specifies the handling method in case of bounded privacy violations. The implemented options are:

- PrivacyHandlingMethod.FILTER: filters out all groups that are violating privacy bound. - PrivacyHandlingMethod.FILTER_DATASET: removes out the entire dataset from the federated computation in case of privacy violations. - PrivacyHandlingMethod.RAISE: raises a PrivacyException if privacy bound was violated.

Default is PrivacyHandlingMethod.RAISE.

RAISE

Returns:

Type Description

statistical result

Source code in .env/lib/python3.10/site-packages/apheris_stats/simple_stats/_core/simple_stats.py
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
def kaplan_meier(
    datasets: Union[Iterable[FederatedDataFrame], FederatedDataFrame],
    session: Union[
        SimpleStatsSession, LocalDummySimpleStatsSession, LocalDebugSimpleStatsSession
    ],
    duration_column_name: str,
    event_column_name: str,
    group_by: str = None,
    plot=False,
    stepsize: int = 1,
    handle_outliers: Union[PrivacyHandlingMethod, str] = PrivacyHandlingMethod.RAISE,
):
    """
    Create a Kaplan Meier survival statistic

    Args:
        datasets: list of FederatedDataFrames that define the pre-preprocessing of
            individual datasets.
        session: For remote runs, use a `SimpleStatsSession` that refers to a cluster
            of Compute Clients and an Aggregator. If you want to simulate a cluster
            locally, use a `LocalDummySimpleStatsSession` or
            `LocalDebugSimpleStatsSession`.
        duration_column_name: duration column for survival function
        event_column_name: event column - indicating death
        group_by: grouping column
        plot: if True results will be displayed using pd.DataFrame.plot()
        stepsize: histogram bin size
        handle_outliers:
            Parameter of enum type PrivacyHandlingMethod which specifies
            the handling method in case of bounded privacy violations.
            The implemented options are:

              - `PrivacyHandlingMethod.FILTER`: filters out all groups that are violating
                 privacy bound.
              - `PrivacyHandlingMethod.FILTER_DATASET`: removes out the entire dataset
                 from the federated computation in case of privacy violations.
              - `PrivacyHandlingMethod.RAISE`: raises a PrivacyException if privacy bound
                 was violated.

            Default is `PrivacyHandlingMethod.RAISE`.

    Returns:
        statistical result
    """

    handle_outliers = _get_locally_validated_handle_outliers(handle_outliers)

    computation_args_2 = {
        "duration_column_name": duration_column_name,
        "event_column_name": event_column_name,
        "group_by": group_by,
    }

    results = _run_simple_stats(
        datasets=datasets,
        computation="kaplan_meier_pre_statistics",
        computation_args={
            "duration_column_name": duration_column_name,
            "group_by": group_by,
        },
        aggregation="kaplan_meier_pre_statistics_aggregation",
        aggregation_args={"step_size": stepsize},
        computation_2="kaplan_meier_statistics",
        computation_args_2=computation_args_2,
        aggregation_2="kaplan_meier_statistics_aggregation",
        aggregation_args_2={},
        is_2step=True,
        handle_outliers=handle_outliers,
        session=session,
    )

    if plot:
        _kaplan_meier_plot(results, stepsize)

    return results

max_column(datasets, session, column_name, group_by=None, aggregation=True, handle_outliers=PrivacyHandlingMethod.RAISE) 🔗

Returns the max over a specified column.

Parameters:

Name Type Description Default
datasets Union[Iterable[FederatedDataFrame], FederatedDataFrame]

list of FederatedDataFrames that define the pre-preprocessing of individual datasets.

required
session Union[SimpleStatsSession, LocalDummySimpleStatsSession, LocalDebugSimpleStatsSession]

For remote runs, use a SimpleStatsSession that refers to a cluster of Compute Clients and an Aggregator. If you want to simulate a cluster locally, use a LocalDummySimpleStatsSession or LocalDebugSimpleStatsSession.

required
column_name str

name of the column over which the max shall be calculated

required
group_by Union[Hashable, Iterable[Hashable]]

optional; mapping, label, or list of labels, used to group before aggregation.

None
aggregation bool

defines whether the max should be aggregated over all datasets or whether the max should be returned per dataset.

True
handle_outliers Union[PrivacyHandlingMethod, str]

Parameter of enum type PrivacyHandlingMethod which specifies the handling method in case of bounded privacy violations. The implemented options are:

- PrivacyHandlingMethod.FILTER: filters out all groups that are violating privacy bound. - PrivacyHandlingMethod.FILTER_DATASET: removes out the entire dataset from the federated computation in case of privacy violations. - PrivacyHandlingMethod.RAISE: raises a PrivacyException if privacy bound was violated.

Default is PrivacyHandlingMethod.RAISE.

RAISE

Returns:

Type Description

statistical result

Source code in .env/lib/python3.10/site-packages/apheris_stats/simple_stats/_core/simple_stats.py
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
def max_column(
    datasets: Union[Iterable[FederatedDataFrame], FederatedDataFrame],
    session: Union[
        SimpleStatsSession,
        LocalDummySimpleStatsSession,
        LocalDebugSimpleStatsSession,
    ],
    column_name: str,
    group_by: Union[Hashable, Iterable[Hashable]] = None,
    aggregation: bool = True,
    handle_outliers: Union[PrivacyHandlingMethod, str] = PrivacyHandlingMethod.RAISE,
):
    """
    Returns the max over a specified column.

    Args:
        datasets: list of FederatedDataFrames that define the pre-preprocessing of
            individual datasets.
        session: For remote runs, use a `SimpleStatsSession` that refers to a cluster
            of Compute Clients and an Aggregator. If you want to simulate a cluster
            locally, use a `LocalDummySimpleStatsSession` or
            `LocalDebugSimpleStatsSession`.
        column_name: name of the column over which the max shall be
            calculated
        group_by: optional; mapping, label, or list of labels, used to group before
            aggregation.
        aggregation: defines whether the max should be aggregated over
            all `datasets` or whether the max should be returned per dataset.
        handle_outliers:
            Parameter of enum type PrivacyHandlingMethod which specifies
            the handling method in case of bounded privacy violations.
            The implemented options are:

              - `PrivacyHandlingMethod.FILTER`: filters out all groups that are violating
                 privacy bound.
              - `PrivacyHandlingMethod.FILTER_DATASET`: removes out the entire dataset
                 from the federated computation in case of privacy violations.
              - `PrivacyHandlingMethod.RAISE`: raises a PrivacyException if privacy bound
                 was violated.

            Default is `PrivacyHandlingMethod.RAISE`.

    Returns:
        statistical result
    """
    handle_outliers = _get_locally_validated_handle_outliers(handle_outliers)

    results = _run_simple_stats(
        datasets=datasets,
        computation="max_column",
        computation_args={"column_name": column_name, "group_by": group_by},
        aggregation="max_aggregation" if aggregation else None,
        aggregation_args={},
        handle_outliers=handle_outliers,
        session=session,
    )

    if not aggregation:
        return _unpack_stats_output(results)
    else:
        return results

mean_column(datasets, session, column_name, group_by=None, aggregation=True, handle_outliers=PrivacyHandlingMethod.RAISE) 🔗

Returns the mean over a specified column.

Parameters:

Name Type Description Default
datasets Union[Iterable[FederatedDataFrame], FederatedDataFrame]

list of FederatedDataFrames that define the pre-preprocessing of individual datasets.

required
session Union[SimpleStatsSession, LocalDummySimpleStatsSession, LocalDebugSimpleStatsSession]

For remote runs, use a SimpleStatsSession that refers to a cluster of Compute Clients and an Aggregator. If you want to simulate a cluster locally, use a LocalDummySimpleStatsSession or LocalDebugSimpleStatsSession.

required
column_name str

name of the column over which the mean shall be calculated

required
group_by Union[Hashable, Iterable[Hashable]]

optional; mapping, label, or list of labels, used to group before aggregation.

None
aggregation bool

defines whether the mean should be aggregated over all datasets or whether the mean should be returned per dataset.

True
handle_outliers Union[PrivacyHandlingMethod, str]

Parameter of enum type PrivacyHandlingMethod which specifies the handling method in case of bounded privacy violations. The implemented options are:

- PrivacyHandlingMethod.FILTER: filters out all groups that are violating privacy bound. - PrivacyHandlingMethod.FILTER_DATASET: removes out the entire dataset from the federated computation in case of privacy violations. - PrivacyHandlingMethod.RAISE: raises a PrivacyException if privacy bound was violated.

Default is PrivacyHandlingMethod.RAISE.

RAISE

Returns:

Type Description

statistical result

Source code in .env/lib/python3.10/site-packages/apheris_stats/simple_stats/_core/simple_stats.py
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
def mean_column(
    datasets: Union[Iterable[FederatedDataFrame], FederatedDataFrame],
    session: Union[
        SimpleStatsSession,
        LocalDummySimpleStatsSession,
        LocalDebugSimpleStatsSession,
    ],
    column_name: str,
    group_by: Union[Hashable, Iterable[Hashable]] = None,
    aggregation: bool = True,
    handle_outliers: Union[PrivacyHandlingMethod, str] = PrivacyHandlingMethod.RAISE,
):
    """
    Returns the mean over a specified column.

    Args:
        datasets: list of FederatedDataFrames that define the pre-preprocessing of
            individual datasets.
        session: For remote runs, use a `SimpleStatsSession` that refers to a cluster
            of Compute Clients and an Aggregator. If you want to simulate a cluster
            locally, use a `LocalDummySimpleStatsSession` or
            `LocalDebugSimpleStatsSession`.
        column_name: name of the column over which the mean shall be
            calculated
        group_by: optional; mapping, label, or list of labels, used to group before
            aggregation.
        aggregation: defines whether the mean should be aggregated over
            all `datasets` or whether the mean should be returned per dataset.
        handle_outliers:
            Parameter of enum type PrivacyHandlingMethod which specifies
            the handling method in case of bounded privacy violations.
            The implemented options are:

              - `PrivacyHandlingMethod.FILTER`: filters out all groups that are violating
                 privacy bound.
              - `PrivacyHandlingMethod.FILTER_DATASET`: removes out the entire dataset
                 from the federated computation in case of privacy violations.
              - `PrivacyHandlingMethod.RAISE`: raises a PrivacyException if privacy bound
                 was violated.

            Default is `PrivacyHandlingMethod.RAISE`.

    Returns:
        statistical result
    """
    handle_outliers = _get_locally_validated_handle_outliers(handle_outliers)
    results = _run_simple_stats(
        datasets=datasets,
        computation="mean_column",
        computation_args={"column_name": column_name, "group_by": group_by},
        aggregation="mean_aggregation" if aggregation else None,
        aggregation_args={},
        handle_outliers=handle_outliers,
        session=session,
    )

    if not aggregation:
        return _unpack_stats_output(results)
    else:
        return results

median_with_confidence_intervals_column(datasets, session, column_name, global_min_max, group_by=None, n_bins=100, handle_outliers=PrivacyHandlingMethod.RAISE) 🔗

Function to approximate the median and the 95% confidence interval over multiple datasets. Internally, first a histogram with a user-defined number of bins and user-defined upper and lower bounds is created over all datasets. Based on this histogram the median and the confidence interval are approximated.

Parameters:

Name Type Description Default
datasets Union[Iterable[FederatedDataFrame], FederatedDataFrame]

list of FederatedDataFrames that define the pre-preprocessing of individual datasets.

required
session Union[SimpleStatsSession, LocalDummySimpleStatsSession, LocalDebugSimpleStatsSession]

For remote runs, use a SimpleStatsSession that refers to a cluster of Compute Clients and an Aggregator. If you want to simulate a cluster locally, use a LocalDummySimpleStatsSession or LocalDebugSimpleStatsSession.

required
column_name str

name of the column for which the histogram shall be generated

required
global_min_max Iterable[float]

a list that contains the global minimum and maximum values of the combined datasets. This needs to be computed separately, using for example the function min_column/max_column combined with min_aggregation/max_aggregation.

required
group_by Union[Hashable, Iterable[Hashable]]

mapping, label, or list of labels, used to group before aggregation.

None
n_bins int

number of bins for internal histogram

100
handle_outliers Union[PrivacyHandlingMethod, str]

Parameter of enum type PrivacyHandlingMethod which specifies the handling method in case of bounded privacy violations. The implemented options are:

- PrivacyHandlingMethod.FILTER: filters out all groups that are violating privacy bound. - PrivacyHandlingMethod.FILTER_DATASET: removes out the entire dataset from the federated computation in case of privacy violations. - PrivacyHandlingMethod.RAISE: raises a PrivacyException if privacy bound was violated.

Default is PrivacyHandlingMethod.RAISE.

RAISE

Returns:

Type Description

statistical result - If no group_by argument is used, its result contains a numpy.ndarray with approximate median, lower and upper bound of the 95% confidence interval. - If a group_by argument is used, its result contains a tuple of three dicts (approximate median, lower and upper bound of the 95% confidence interval).

Source code in .env/lib/python3.10/site-packages/apheris_stats/simple_stats/_core/simple_stats.py
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
def median_with_confidence_intervals_column(
    datasets: Union[Iterable[FederatedDataFrame], FederatedDataFrame],
    session: Union[
        SimpleStatsSession, LocalDummySimpleStatsSession, LocalDebugSimpleStatsSession
    ],
    column_name: str,
    global_min_max: Iterable[float],
    group_by: Union[Hashable, Iterable[Hashable]] = None,
    n_bins: int = 100,
    handle_outliers: Union[PrivacyHandlingMethod, str] = PrivacyHandlingMethod.RAISE,
):
    """
    Function to approximate the median and the 95% confidence interval over multiple
    datasets. Internally, first a histogram with a user-defined number of bins and
    user-defined upper and lower bounds is created over all datasets. Based on this
    histogram the median and the confidence interval are approximated.


    Args:
        datasets: list of FederatedDataFrames that define the pre-preprocessing of
            individual datasets.
        session: For remote runs, use a `SimpleStatsSession` that refers to a cluster
            of Compute Clients and an Aggregator. If you want to simulate a cluster
            locally, use a `LocalDummySimpleStatsSession` or
            `LocalDebugSimpleStatsSession`.
        column_name: name of the column for which the histogram shall be generated
        global_min_max: a list that contains the global minimum and maximum values
            of the combined datasets. This needs to be computed separately, using for
            example the function `min_column`/`max_column` combined with
            `min_aggregation`/`max_aggregation`.
        group_by: mapping, label, or list of labels, used to group before aggregation.
        n_bins: number of bins for internal histogram
        handle_outliers:
            Parameter of enum type PrivacyHandlingMethod which specifies
            the handling method in case of bounded privacy violations.
            The implemented options are:

              - `PrivacyHandlingMethod.FILTER`: filters out all groups that are violating
                 privacy bound.
              - `PrivacyHandlingMethod.FILTER_DATASET`: removes out the entire dataset
                 from the federated computation in case of privacy violations.
              - `PrivacyHandlingMethod.RAISE`: raises a PrivacyException if privacy bound
                 was violated.

            Default is `PrivacyHandlingMethod.RAISE`.

    Returns:
        statistical result
            - If no `group_by` argument is used, its result contains a `numpy.ndarray`
            with approximate median, lower and upper bound of the 95% confidence interval.
            - If a `group_by` argument is used, its result contains a tuple of three dicts
            (approximate median, lower and upper bound of the 95% confidence interval).
    """
    handle_outliers = _get_locally_validated_handle_outliers(handle_outliers)

    results = _run_simple_stats(
        datasets=datasets,
        computation="confidence_intervals_column",
        computation_args={
            "column_name": column_name,
            "global_min_max": global_min_max,
            "n_bins": n_bins,
            "group_by": group_by,
        },
        aggregation="confidence_intervals_aggregation",
        aggregation_args={"global_min_max": global_min_max},
        handle_outliers=handle_outliers,
        session=session,
    )
    return results

median_with_quartiles(datasets, session, column_name, global_min_max, group_by=None, n_bins=100, handle_outliers=PrivacyHandlingMethod.RAISE) 🔗

Function to approximate the median and the 1st and 3rd quartile over multiple datasets. Internally, first a histogram with a user-defined number of bins and user-defined upper and lower bounds is created over all datasets. Based on this histogram above-mentioned values are approximated.

Parameters:

Name Type Description Default
datasets Union[Iterable[FederatedDataFrame], FederatedDataFrame]

list of FederatedDataFrames that define the pre-preprocessing of individual datasets.

required
session Union[SimpleStatsSession, LocalDummySimpleStatsSession, LocalDebugSimpleStatsSession]

For remote runs, use a SimpleStatsSession that refers to a cluster of Compute Clients and an Aggregator. If you want to simulate a cluster locally, use a LocalDummySimpleStatsSession or LocalDebugSimpleStatsSession.

required
column_name str

name of the column for which the statistical query shall be computed

required
global_min_max Iterable[float]

a list that contains the global minimum and maximum values of the combined datasets. This needs to be computed separately, using for example the function min_column/max_column combined with min_aggregation/max_aggregation.

required
group_by Union[Hashable, Iterable[Hashable]]

mapping, label, or list of labels, used to group before aggregation.

None
n_bins int

number of bins for the internal histogram

100
handle_outliers Union[PrivacyHandlingMethod, str]

Parameter of enum type PrivacyHandlingMethod which specifies the handling method in case of bounded privacy violations. The implemented options are:

- PrivacyHandlingMethod.FILTER: filters out all groups that are violating privacy bound. - PrivacyHandlingMethod.FILTER_DATASET: removes out the entire dataset from the federated computation in case of privacy violations. - PrivacyHandlingMethod.RAISE: raises a PrivacyException if privacy bound was violated.

Default is PrivacyHandlingMethod.RAISE..

RAISE

Returns:

Type Description

statistical result; Its result contains a tuple with the 1st quartile, the median, and the 3rd quartile.

Source code in .env/lib/python3.10/site-packages/apheris_stats/simple_stats/_core/simple_stats.py
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
def median_with_quartiles(
    datasets: Union[Iterable[FederatedDataFrame], FederatedDataFrame],
    session: Union[
        SimpleStatsSession, LocalDummySimpleStatsSession, LocalDebugSimpleStatsSession
    ],
    column_name: str,
    global_min_max: Iterable[float],
    group_by: Union[Hashable, Iterable[Hashable]] = None,
    n_bins: int = 100,
    handle_outliers: Union[PrivacyHandlingMethod, str] = PrivacyHandlingMethod.RAISE,
):
    """
    Function to approximate the median and the 1st and 3rd quartile over multiple
    datasets. Internally, first a histogram with a user-defined number of bins and
    user-defined upper and lower bounds is created over all datasets. Based on this
    histogram above-mentioned values are approximated.


    Args:
        datasets: list of FederatedDataFrames that define the pre-preprocessing of
            individual datasets.
        session: For remote runs, use a `SimpleStatsSession` that refers to a cluster
            of Compute Clients and an Aggregator. If you want to simulate a cluster
            locally, use a `LocalDummySimpleStatsSession` or
            `LocalDebugSimpleStatsSession`.
        column_name: name of the column for which the statistical query shall be computed
        global_min_max: a list that contains the global minimum and maximum values
            of the combined datasets. This needs to be computed separately, using for
            example the function `min_column`/`max_column` combined with
            `min_aggregation`/`max_aggregation`.
        group_by: mapping, label, or list of labels, used to group before aggregation.
        n_bins: number of bins for the internal histogram
        handle_outliers:
            Parameter of enum type PrivacyHandlingMethod which specifies
            the handling method in case of bounded privacy violations.
            The implemented options are:

              - `PrivacyHandlingMethod.FILTER`: filters out all groups that are violating
                 privacy bound.
              - `PrivacyHandlingMethod.FILTER_DATASET`: removes out the entire dataset
                 from the federated computation in case of privacy violations.
              - `PrivacyHandlingMethod.RAISE`: raises a PrivacyException if privacy bound
                 was violated.

            Default is `PrivacyHandlingMethod.RAISE`..

    Returns:
        statistical result; Its result contains a tuple with the 1st quartile, the
            median, and the 3rd quartile.
    """
    handle_outliers = _get_locally_validated_handle_outliers(handle_outliers)

    results = _run_simple_stats(
        datasets=datasets,
        computation="median_with_quartiles_column",
        computation_args={
            "column_name": column_name,
            "global_min_max": global_min_max,
            "n_bins": n_bins,
            "group_by": group_by,
        },
        aggregation="median_with_quartiles_aggregation",
        aggregation_args={"global_max": global_min_max[1]},
        handle_outliers=handle_outliers,
        session=session,
    )
    return results

min_column(datasets, session, column_name, group_by=None, aggregation=True, handle_outliers=PrivacyHandlingMethod.RAISE) 🔗

Returns the min over a specified column.

Parameters:

Name Type Description Default
datasets Union[Iterable[FederatedDataFrame], FederatedDataFrame]

list of FederatedDataFrames that define the pre-preprocessing of individual datasets.

required
session Union[SimpleStatsSession, LocalDummySimpleStatsSession, LocalDebugSimpleStatsSession]

For remote runs, use a SimpleStatsSession that refers to a cluster of Compute Clients and an Aggregator. If you want to simulate a cluster locally, use a LocalDummySimpleStatsSession or LocalDebugSimpleStatsSession.

required
column_name str

name of the column over which the min shall be calculated

required
group_by Union[Hashable, Iterable[Hashable]]

optional; mapping, label, or list of labels, used to group before aggregation.

None
aggregation bool

defines whether the min should be aggregated over all datasets or whether the min should be returned per dataset.

True
handle_outliers Union[PrivacyHandlingMethod, str]

Parameter of enum type PrivacyHandlingMethod which specifies the handling method in case of bounded privacy violations. The implemented options are:

- PrivacyHandlingMethod.FILTER: filters out all groups that are violating privacy bound. - PrivacyHandlingMethod.FILTER_DATASET: removes out the entire dataset from the federated computation in case of privacy violations. - PrivacyHandlingMethod.RAISE: raises a PrivacyException if privacy bound was violated.

Default is PrivacyHandlingMethod.RAISE.

RAISE

Returns:

Type Description

statistical result

Source code in .env/lib/python3.10/site-packages/apheris_stats/simple_stats/_core/simple_stats.py
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
def min_column(
    datasets: Union[Iterable[FederatedDataFrame], FederatedDataFrame],
    session: Union[
        SimpleStatsSession,
        LocalDummySimpleStatsSession,
        LocalDebugSimpleStatsSession,
    ],
    column_name: str,
    group_by: Union[Hashable, Iterable[Hashable]] = None,
    aggregation: bool = True,
    handle_outliers: Union[PrivacyHandlingMethod, str] = PrivacyHandlingMethod.RAISE,
):
    """
    Returns the min over a specified column.

    Args:
        datasets: list of FederatedDataFrames that define the pre-preprocessing of
            individual datasets.
        session: For remote runs, use a `SimpleStatsSession` that refers to a cluster
            of Compute Clients and an Aggregator. If you want to simulate a cluster
            locally, use a `LocalDummySimpleStatsSession` or
            `LocalDebugSimpleStatsSession`.
        column_name: name of the column over which the min shall be
            calculated
        group_by: optional; mapping, label, or list of labels, used to group before
            aggregation.
        aggregation: defines whether the min should be aggregated over
            all `datasets` or whether the min should be returned per dataset.
        handle_outliers:
            Parameter of enum type PrivacyHandlingMethod which specifies
            the handling method in case of bounded privacy violations.
            The implemented options are:

              - `PrivacyHandlingMethod.FILTER`: filters out all groups that are violating
                 privacy bound.
              - `PrivacyHandlingMethod.FILTER_DATASET`: removes out the entire dataset
                 from the federated computation in case of privacy violations.
              - `PrivacyHandlingMethod.RAISE`: raises a PrivacyException if privacy bound
                 was violated.

            Default is `PrivacyHandlingMethod.RAISE`.

    Returns:
        statistical result
    """
    handle_outliers = _get_locally_validated_handle_outliers(handle_outliers)

    results = _run_simple_stats(
        datasets=datasets,
        computation="min_column",
        computation_args={"column_name": column_name, "group_by": group_by},
        aggregation="min_aggregation" if aggregation else None,
        aggregation_args={},
        handle_outliers=handle_outliers,
        session=session,
    )

    if not aggregation:
        return _unpack_stats_output(results)
    else:
        return results

pca_transformation(datasets, session, column_names, n_components, handle_outliers=PrivacyHandlingMethod.RAISE.value) 🔗

Computes the principal components transformation matrix of given list of datasets. Args: datasets: datasets that the computation shall be run on session: For remote runs, use a SimpleStatsSession that refers to a cluster column_names: set of columns n_components: number of components to keep handle_outliers: Parameter of enum type PrivacyHandlingMethod which specifies the handling method in case of bounded privacy violations. The implemented options are:

      - `PrivacyHandlingMethod.FILTER`: filters out all groups that are violating
         privacy bound.
      - `PrivacyHandlingMethod.FILTER_DATASET`: removes out the entire dataset
         from the federated computation in case of privacy violations.
      - `PrivacyHandlingMethod.RAISE`: raises a PrivacyException if privacy bound
         was violated.

    Default is `PrivacyHandlingMethod.RAISE`.

Returns: transformation matrix as pandas DataFrame.

Source code in .env/lib/python3.10/site-packages/apheris_stats/simple_stats/_core/simple_stats.py
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
def pca_transformation(
    datasets: Union[Iterable[FederatedDataFrame], FederatedDataFrame],
    session: Union[
        SimpleStatsSession, LocalDummySimpleStatsSession, LocalDebugSimpleStatsSession
    ],
    column_names: Iterable[str],
    n_components: int,
    handle_outliers: Union[
        PrivacyHandlingMethod, str
    ] = PrivacyHandlingMethod.RAISE.value,
) -> pd.DataFrame:
    """
    Computes the principal components transformation matrix of given list of datasets.
    Args:
        datasets: datasets that the computation shall be run on
        session: For remote runs, use a `SimpleStatsSession` that refers to a cluster
        column_names: set of columns
        n_components: number of components to keep
        handle_outliers:
            Parameter of enum type PrivacyHandlingMethod which specifies
            the handling method in case of bounded privacy violations.
            The implemented options are:

              - `PrivacyHandlingMethod.FILTER`: filters out all groups that are violating
                 privacy bound.
              - `PrivacyHandlingMethod.FILTER_DATASET`: removes out the entire dataset
                 from the federated computation in case of privacy violations.
              - `PrivacyHandlingMethod.RAISE`: raises a PrivacyException if privacy bound
                 was violated.

            Default is `PrivacyHandlingMethod.RAISE`.
    Returns:
        transformation matrix as pandas DataFrame.
    """

    Cov = cov(
        datasets=datasets,
        session=session,
        column_names=column_names,
        handle_outliers=handle_outliers,
    )
    Cov = Cov.loc["total", ComputationName.JOINED_ERR.value]
    # decompose the covariance matrix into singular values and eigenvectors,
    # we only need the right eigenvectors
    U, D, V = svd(Cov, full_matrices=False)
    transform = V[:n_components, :].T
    df_transformation = pd.DataFrame(
        transform,
        index=Cov.index,
        columns=[f"PC{i}" for i in range(1, transform.shape[1] + 1)],
    )

    return df_transformation

shape(datasets, session, handle_outliers=PrivacyHandlingMethod.RAISE) 🔗

Returns the shape of the datasets

Parameters:

Name Type Description Default
datasets Union[Iterable[FederatedDataFrame], FederatedDataFrame]

list of FederatedDataFrames that define the pre-preprocessing of individual datasets.

required
session Union[SimpleStatsSession, LocalDummySimpleStatsSession, LocalDebugSimpleStatsSession]

For remote runs, use a SimpleStatsSession that refers to a cluster of Compute Clients and an Aggregator. If you want to simulate a cluster locally, use a LocalDummySimpleStatsSession or LocalDebugSimpleStatsSession.

required
handle_outliers Union[PrivacyHandlingMethod, str]

Parameter of enum type PrivacyHandlingMethod which specifies the handling method in case of bounded privacy violations. The implemented options are:

- PrivacyHandlingMethod.FILTER_DATASET: removes out the entire dataset from the federated computation in case of privacy violations. - PrivacyHandlingMethod.ROUND: only valid for counts, rounds to the privacy bound or 0. - PrivacyHandlingMethod.RAISE: raises a PrivacyException if privacy bound was violated.

Default is PrivacyHandlingMethod.RAISE.

RAISE

Returns:

Type Description

statistical result

Source code in .env/lib/python3.10/site-packages/apheris_stats/simple_stats/_core/simple_stats.py
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
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
def shape(
    datasets: Union[Iterable[FederatedDataFrame], FederatedDataFrame],
    session: Union[
        SimpleStatsSession, LocalDummySimpleStatsSession, LocalDebugSimpleStatsSession
    ],
    handle_outliers: Union[PrivacyHandlingMethod, str] = PrivacyHandlingMethod.RAISE,
):
    """
    Returns the shape of the datasets

    Args:
        datasets: list of FederatedDataFrames that define the pre-preprocessing of
            individual datasets.
        session: For remote runs, use a `SimpleStatsSession` that refers to a cluster
            of Compute Clients and an Aggregator. If you want to simulate a cluster
            locally, use a `LocalDummySimpleStatsSession` or
            `LocalDebugSimpleStatsSession`.
        handle_outliers:
            Parameter of enum type PrivacyHandlingMethod which specifies
            the handling method in case of bounded privacy violations.
            The implemented options are:

              - `PrivacyHandlingMethod.FILTER_DATASET`: removes out the entire dataset
                 from the federated computation in case of privacy violations.
              - `PrivacyHandlingMethod.ROUND`: only valid for counts, rounds to the
                 privacy bound or 0.
              - `PrivacyHandlingMethod.RAISE`: raises a PrivacyException if privacy bound
                 was violated.

            Default is `PrivacyHandlingMethod.RAISE`.

    Returns:
        statistical result
    """
    handle_outliers = _get_locally_validated_handle_outliers(
        handle_outliers,
        allowed_methods=[
            PrivacyHandlingMethod.ROUND,
            PrivacyHandlingMethod.RAISE,
            PrivacyHandlingMethod.FILTER_DATASET,
        ],
    )

    results = _run_simple_stats(
        datasets=datasets,
        computation="shape",
        computation_args={},
        aggregation=None,
        aggregation_args={},
        handle_outliers=handle_outliers,
        session=session,
    )
    return [tuple(x["results"].to_frame()["shape"]) for x in results.values()]

squared_errors_by_column(datasets, session, column_name, global_mean, group_by=None, aggregation=True, handle_outliers=PrivacyHandlingMethod.RAISE) 🔗

Returns the sum over the squared difference from global_mean over a specified column.

Parameters:

Name Type Description Default
datasets Union[Iterable[FederatedDataFrame], FederatedDataFrame]

list of FederatedDataFrames that define the pre-preprocessing of individual datasets.

required
session Union[SimpleStatsSession, LocalDummySimpleStatsSession, LocalDebugSimpleStatsSession]

For remote runs, use a SimpleStatsSession that refers to a cluster of Compute Clients and an Aggregator. If you want to simulate a cluster locally, use a LocalDummySimpleStatsSession or LocalDebugSimpleStatsSession.

required
column_name str

name of the column over which the operation shall be calculated

required
group_by Union[Hashable, Iterable[Hashable]]

mapping, label, or list of labels, used to group before aggregation.

None
global_mean float

the deviation of each element to this value is squared and then added up. The mean can be computed via apheris.simple_stats.mean_column.

required
aggregation bool

defines whether the operation should be aggregated over all datasets or whether the operation should be returned per dataset.

True
handle_outliers Union[PrivacyHandlingMethod, str]

Parameter of enum type PrivacyHandlingMethod which specifies the handling method in case of bounded privacy violations. The implemented options are:

- PrivacyHandlingMethod.FILTER: filters out all groups that are violating privacy bound. - PrivacyHandlingMethod.FILTER_DATASET: removes out the entire dataset from the federated computation in case of privacy violations. - PrivacyHandlingMethod.RAISE: raises a PrivacyException if privacy bound was violated.

Default is PrivacyHandlingMethod.RAISE.

RAISE

Returns:

Type Description

statistical result

Source code in .env/lib/python3.10/site-packages/apheris_stats/simple_stats/_core/simple_stats.py
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
def squared_errors_by_column(
    datasets: Union[Iterable[FederatedDataFrame], FederatedDataFrame],
    session: Union[
        SimpleStatsSession, LocalDummySimpleStatsSession, LocalDebugSimpleStatsSession
    ],
    column_name: str,
    global_mean: float,
    group_by: Union[Hashable, Iterable[Hashable]] = None,
    aggregation: bool = True,
    handle_outliers: Union[PrivacyHandlingMethod, str] = PrivacyHandlingMethod.RAISE,
):
    """
    Returns the sum over the squared difference from `global_mean` over a specified
    column.

    Args:
        datasets: list of FederatedDataFrames that define the pre-preprocessing of
            individual datasets.
        session: For remote runs, use a `SimpleStatsSession` that refers to a cluster
            of Compute Clients and an Aggregator. If you want to simulate a cluster
            locally, use a `LocalDummySimpleStatsSession` or
            `LocalDebugSimpleStatsSession`.
        column_name: name of the column over which the operation shall be calculated
        group_by: mapping, label, or list of labels, used to group before aggregation.
        global_mean: the deviation of each element to this value is squared and then
            added up. The mean can be computed via apheris.simple_stats.mean_column.
        aggregation: defines whether the operation should be aggregated over
            all `datasets` or whether the operation should be returned per dataset.
        handle_outliers:
            Parameter of enum type PrivacyHandlingMethod which specifies
            the handling method in case of bounded privacy violations.
            The implemented options are:

              - `PrivacyHandlingMethod.FILTER`: filters out all groups that are violating
                 privacy bound.
              - `PrivacyHandlingMethod.FILTER_DATASET`: removes out the entire dataset
                 from the federated computation in case of privacy violations.
              - `PrivacyHandlingMethod.RAISE`: raises a PrivacyException if privacy bound
                 was violated.

            Default is `PrivacyHandlingMethod.RAISE`.

    Returns:
        statistical result
    """
    handle_outliers = _get_locally_validated_handle_outliers(handle_outliers)

    results = _run_simple_stats(
        datasets=datasets,
        computation="squared_errors_by_column",
        computation_args={
            "column_name": column_name,
            "global_mean": global_mean,
            "group_by": group_by,
        },
        aggregation="sum_aggregation" if aggregation else None,
        aggregation_args={},
        handle_outliers=handle_outliers,
        session=session,
    )
    if not aggregation:
        return _unpack_stats_output(results)
    else:
        return results

sum_column(datasets, session, column_name, group_by=None, aggregation=True, handle_outliers=PrivacyHandlingMethod.RAISE) 🔗

Returns the sum over a specified column.

Parameters:

Name Type Description Default
datasets Union[Iterable[FederatedDataFrame], FederatedDataFrame]

list of FederatedDataFrames that define the pre-preprocessing of individual datasets.

required
session Union[SimpleStatsSession, LocalDummySimpleStatsSession, LocalDebugSimpleStatsSession]

For remote runs, use a SimpleStatsSession that refers to a cluster of Compute Clients and an Aggregator. If you want to simulate a cluster locally, use a LocalDummySimpleStatsSession or LocalDebugSimpleStatsSession.

required
column_name str

name of the column over which the sum shall be calculated

required
group_by Union[Hashable, Iterable[Hashable]]

optional; mapping, label, or list of labels, used to group before aggregation.

None
aggregation bool

defines whether the sum should be aggregated over all datasets or whether the sum should be returned per dataset.

True
handle_outliers Union[PrivacyHandlingMethod, str]

Parameter of enum type PrivacyHandlingMethod which specifies the handling method in case of bounded privacy violations. The implemented options are:

- PrivacyHandlingMethod.FILTER: filters out all groups that are violating privacy bound. - PrivacyHandlingMethod.FILTER_DATASET: removes out the entire dataset from the federated computation in case of privacy violations. - PrivacyHandlingMethod.RAISE: raises a PrivacyException if privacy bound was violated.

Default is PrivacyHandlingMethod.RAISE.

RAISE

Returns:

Type Description

statistical result

Source code in .env/lib/python3.10/site-packages/apheris_stats/simple_stats/_core/simple_stats.py
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
def sum_column(
    datasets: Union[Iterable[FederatedDataFrame], FederatedDataFrame],
    session: Union[
        SimpleStatsSession,
        LocalDummySimpleStatsSession,
        LocalDebugSimpleStatsSession,
    ],
    column_name: str,
    group_by: Union[Hashable, Iterable[Hashable]] = None,
    aggregation: bool = True,
    handle_outliers: Union[PrivacyHandlingMethod, str] = PrivacyHandlingMethod.RAISE,
):
    """
    Returns the sum over a specified column.

    Args:
        datasets: list of FederatedDataFrames that define the pre-preprocessing of
            individual datasets.
        session: For remote runs, use a `SimpleStatsSession` that refers to a cluster
            of Compute Clients and an Aggregator. If you want to simulate a cluster
            locally, use a `LocalDummySimpleStatsSession` or
            `LocalDebugSimpleStatsSession`.
        column_name: name of the column over which the sum shall be
            calculated
        group_by: optional; mapping, label, or list of labels, used to group before
            aggregation.
        aggregation: defines whether the sum should be aggregated over
            all `datasets` or whether the sum should be returned per dataset.
        handle_outliers:
            Parameter of enum type PrivacyHandlingMethod which specifies
            the handling method in case of bounded privacy violations.
            The implemented options are:

              - `PrivacyHandlingMethod.FILTER`: filters out all groups that are violating
                 privacy bound.
              - `PrivacyHandlingMethod.FILTER_DATASET`: removes out the entire dataset
                 from the federated computation in case of privacy violations.
              - `PrivacyHandlingMethod.RAISE`: raises a PrivacyException if privacy bound
                 was violated.

            Default is `PrivacyHandlingMethod.RAISE`.

    Returns:
        statistical result
    """
    handle_outliers = _get_locally_validated_handle_outliers(handle_outliers)

    results = _run_simple_stats(
        datasets=datasets,
        computation="sum_column",
        computation_args={"column_name": column_name, "group_by": group_by},
        aggregation="sum_aggregation" if aggregation else None,
        aggregation_args={},
        handle_outliers=handle_outliers,
        session=session,
    )

    if not aggregation:
        return _unpack_stats_output(results)
    else:
        return results

tableone(datasets, session, numerical_columns=None, numerical_nonnormal_columns=None, categorical_columns=None, group_by=None, n_bins=100, handle_outliers=PrivacyHandlingMethod.RAISE) 🔗

Create an overview statistic

Parameters:

Name Type Description Default
datasets Union[Iterable[FederatedDataFrame], FederatedDataFrame]

list of FederatedDataFrames that define the pre-preprocessing of individual datasets.

required
session Union[SimpleStatsSession, LocalDummySimpleStatsSession, LocalDebugSimpleStatsSession]

For remote runs, use a SimpleStatsSession that refers to a cluster of Compute Clients and an Aggregator. If you want to simulate a cluster locally, use a LocalDummySimpleStatsSession or LocalDebugSimpleStatsSession.

required
numerical_columns Iterable[str]

names of columns for which mean and standard deviation shall be calculated.

None
numerical_nonnormal_columns Iterable[str]

names of columns for which the median, as well as 1st and 3rd quartile shall be calculated. These values are approximated via a histogram.

None
categorical_columns Iterable[str]

names of categorical columns, whose value counts shall be counted.

None
group_by Union[Hashable, Iterable[Hashable]]

mapping, label, or list of labels, used to group before aggregation.

None
n_bins int

number of bins of the histogram that is used to approximate the median and 1st and 3rd quartile of columns in numerical_nonnormal_columns.

100
handle_outliers Union[PrivacyHandlingMethod, str]

Parameter of enum type PrivacyHandlingMethod which specifies the handling method in case of bounded privacy violations. The implemented options are:

- PrivacyHandlingMethod.FILTER: filters out all groups that are violating privacy bound. - PrivacyHandlingMethod.FILTER_DATASET: removes out the entire dataset from the federated computation in case of privacy violations. - PrivacyHandlingMethod.RAISE: raises a PrivacyException if privacy bound was violated.

Default is PrivacyHandlingMethod.RAISE.

RAISE

Returns:

Type Description

statistical result; Its result contains a pandas DataFrame with the

tableone statistics over the datasets.

Source code in .env/lib/python3.10/site-packages/apheris_stats/simple_stats/_core/simple_stats.py
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
def tableone(
    datasets: Union[Iterable[FederatedDataFrame], FederatedDataFrame],
    session: Union[
        SimpleStatsSession, LocalDummySimpleStatsSession, LocalDebugSimpleStatsSession
    ],
    numerical_columns: Iterable[str] = None,
    numerical_nonnormal_columns: Iterable[str] = None,
    categorical_columns: Iterable[str] = None,
    group_by: Union[Hashable, Iterable[Hashable]] = None,
    n_bins: int = 100,
    handle_outliers: Union[PrivacyHandlingMethod, str] = PrivacyHandlingMethod.RAISE,
):
    """
    Create an overview statistic

    Args:
        datasets: list of FederatedDataFrames that define the pre-preprocessing of
            individual datasets.
        session: For remote runs, use a `SimpleStatsSession` that refers to a cluster
            of Compute Clients and an Aggregator. If you want to simulate a cluster
            locally, use a `LocalDummySimpleStatsSession` or
            `LocalDebugSimpleStatsSession`.
        numerical_columns: names of columns for which mean and standard deviation shall
            be calculated.
        numerical_nonnormal_columns: names of columns for which the median, as well as
            1st and 3rd quartile shall be calculated. These values are approximated via a
            histogram.
        categorical_columns: names of categorical columns, whose value counts shall be
            counted.
        group_by: mapping, label, or list of labels, used to group before aggregation.
        n_bins: number of bins of the histogram that is used to approximate the
            median and 1st and 3rd quartile of columns in `numerical_nonnormal_columns`.
        handle_outliers:
            Parameter of enum type PrivacyHandlingMethod which specifies
            the handling method in case of bounded privacy violations.
            The implemented options are:

              - `PrivacyHandlingMethod.FILTER`: filters out all groups that are violating
                 privacy bound.
              - `PrivacyHandlingMethod.FILTER_DATASET`: removes out the entire dataset
                 from the federated computation in case of privacy violations.
              - `PrivacyHandlingMethod.RAISE`: raises a PrivacyException if privacy bound
                 was violated.

            Default is `PrivacyHandlingMethod.RAISE`.

    Returns:
        statistical result; Its result contains a pandas DataFrame with the
        tableone statistics over the datasets.
    """
    handle_outliers = _get_locally_validated_handle_outliers(handle_outliers)

    computation_args = {
        "numerical_columns": numerical_columns,
        "numerical_non_normal_columns": numerical_nonnormal_columns,
        "categorical_columns": categorical_columns,
        "group_by": group_by,
    }

    computation_args_2 = computation_args.copy()
    computation_args_2["n_bins"] = n_bins

    results = _run_simple_stats(
        datasets=datasets,
        computation="tableone_pre_statistics",
        computation_args=computation_args,
        aggregation="tableone_pre_statistics_aggregation",
        aggregation_args={},
        computation_2="tableone_statistics",
        computation_args_2=computation_args,
        aggregation_2="tableone_statistics_aggregation",
        aggregation_args_2={},
        is_2step=True,
        handle_outliers=handle_outliers,
        session=session,
    )
    return results

apheris_stats.simple_stats.exceptions🔗

InsufficientPermissions 🔗

Bases: Exception

Raised when an operation does not have sufficient permissions to be performed.

Source code in .env/lib/python3.10/site-packages/apheris_stats/simple_stats/exceptions.py
4
5
6
7
class InsufficientPermissions(Exception):
    """
    Raised when an operation does not have sufficient permissions to be performed.
    """

ObjectNotFound 🔗

Bases: ApherisException

Raised when trying to access an object that does not exist.

Source code in .env/lib/python3.10/site-packages/apheris_auth/core/exceptions.py
17
18
19
20
class ObjectNotFound(ApherisException):
    """
    Raised when trying to access an object that does not exist.
    """

PrivacyException 🔗

Bases: Exception

Raised when a privacy mechanism required by the data provider(s) fails to be applied, is violated, or is incompatible with the user-chosen settings.

Source code in .env/lib/python3.10/site-packages/apheris_stats/simple_stats/exceptions.py
10
11
12
13
14
15
class PrivacyException(Exception):
    """
    Raised when a privacy mechanism required by the data provider(s)
    fails to be applied, is violated, or is incompatible
    with the user-chosen settings.
    """

RestrictedPreprocessingViolation 🔗

Bases: PrivacyException

Raised when a prohibited command is requested to be executed due to restricted preprocessing.

Source code in .env/lib/python3.10/site-packages/apheris_stats/simple_stats/exceptions.py
18
19
20
21
22
class RestrictedPreprocessingViolation(PrivacyException):
    """
    Raised when a prohibited command is requested to be executed due to
    restricted preprocessing.
    """

apheris_stats.simple_stats.util🔗

FederatedDataFrame 🔗

Object that simplifies preprocessing by providing a pandas-like interface to preprocess with tabular data. The FederatedDataFrame contains preprocessing transformations that are to be applied on a remote dataset. On which dataset it operates is specified in the constructor.

Parameters:

Name Type Description Default
data_source Union[str, RemoteData]

remote id or RemoteData object or path to a data file or graph

required
read_format Union[str, InputFormat, None]

format of data source

None
filename_in_zip Union[str, None]

used for ZIP format to identify which file out of ZIP to take The argument is optional, but must be specified for ZIP format. If read_format is ZIP, the value of this argument is used to read one CSV.

None

Example:

    * via dataset id (recommended): assume your dataset id is 'data-cloudnode':
    ```
        df = FederatedDataFrame('data-cloudnode')

    * via RemoteData object (internal-only):
    assume your remote data id is 'data-cloudnode':
    ```
        rd = apheris_auth.RemoteData('data-cloudnode')
        df = FederatedDataFrame(rd)
    ```

    ```

    * optional: for remote data containing multiple files,
    choose which file to read:
    ```
        df = FederatedDataFrame('data-cloudnode', filename_in_zip='patients.csv')
    ```
Source code in .env/lib/python3.10/site-packages/apheris_stats/simple_stats/_internal/datatools/transformations/dataframe.py
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
class FederatedDataFrame:
    """
    Object that simplifies preprocessing by providing a pandas-like interface
    to preprocess with tabular data.
    The FederatedDataFrame contains preprocessing transformations that are to
    be applied on a remote dataset. On which dataset it operates is specified in
    the constructor.

    Args:
            data_source: remote id or RemoteData object or path to a  data file or graph
            JSON file
            read_format: format of data source
            filename_in_zip: used for ZIP format to identify which file out of ZIP to take
                The argument is optional, but must be specified for ZIP format.
                If read_format is ZIP, the value of this argument is used to read one CSV.

    Example:

            * via dataset id (recommended): assume your dataset id is 'data-cloudnode':
            ```
                df = FederatedDataFrame('data-cloudnode')

            * via RemoteData object (internal-only):
            assume your remote data id is 'data-cloudnode':
            ```
                rd = apheris_auth.RemoteData('data-cloudnode')
                df = FederatedDataFrame(rd)
            ```
            ```

            * optional: for remote data containing multiple files,
            choose which file to read:
            ```
                df = FederatedDataFrame('data-cloudnode', filename_in_zip='patients.csv')
            ```
    """

    def __init__(
        self,
        data_source: Union[str, RemoteData],
        read_format: Union[str, InputFormat, None] = None,
        filename_in_zip: Union[str, None] = None,
    ):
        """
        Create a new data object

        Example:
            * via RemoteData object (recommended):
            assume your remote data id is 'data-cloudnode':
            ```
                rd = apheris_auth.RemoteData('data-cloudnode')
                df = FederatedDataFrame(rd)
            ```

            * via RemoteData id: assume your remote data id is 'data-cloudnode':
            ```
            df = FederatedDataFrame('data-cloudnode')
            ```

            * optional: for remote data containing multiple files,
            choose which file to read:

            ```
                df = FederatedDataFrame(apheris_auth.RemoteData('data-cloudnode'),
                    filename_in_zip='patients.csv')
            ```

        Args:
            data_source: remote id or RemoteData object or path to a  data file or graph
            JSON file
            read_format: format of data source
            filename_in_zip: used for ZIP format to identify which file out of ZIP to take
                The argument is optional, but must be specified for ZIP format.
                If read_format is ZIP, the value of this argument is used to read one CSV.

        """
        self.str = _StringAccessor(self)
        self.special = _SpecialAccessor(self)
        nc = NodeCommands.datetime_like_properties
        remote_function_attrs = nc.get_supported_values_for_remote_function_attr(
            remote_function_attr="datetime_like_property"
        )
        for remote_function_attr in remote_function_attrs:
            _DatetimeLikeAccessor.fill_in_dt_properties(remote_function_attr)
            self.dt = _DatetimeLikeAccessor(self)

        self.remoteData = None
        if isinstance(data_source, RemoteData):
            self.remoteData = data_source
            data_source = data_source.id
        try:
            self._import_graph(graph_json=data_source)
        except TransformationsInvalidJSONFormatException:
            self.__nx_graph = DiGraph()
            self.__uuid_instance = NodeUUID()
            if data_source:
                if not read_format and filename_in_zip:
                    read_format = InputFormat.ZIP
                elif not read_format:
                    read_format = self._parse_file_extension(
                        filepath_or_filename=data_source,
                    )
                self._validate_if_read_format_supported(
                    read_format=read_format,
                )
                self._validate_if_filename_for_zip_provided(
                    read_format=read_format,
                    filename_in_zip=filename_in_zip,
                )
                self._read_data(
                    src_node_uuid=self._uuid,
                    data_source=data_source,
                    read_format=read_format,
                    read_args={"filename": filename_in_zip},
                )
        # cache to save lookup of dummy data paths when user defines remote data ids
        self._remote_data_to_path_cache = {}

    ######################################################################################
    # properties
    ######################################################################################
    @property
    def _uuid(self):
        """Returns a unique id for the object"""
        return self.__uuid_instance.uuid

    @property
    def _graph(self):
        return self.__nx_graph

    @property
    def loc(self) -> "_LocIndexer":
        """Use pandas .loc notation to access the data"""
        return _LocIndexer(obj=self)

    ######################################################################################
    # read file helpers
    ######################################################################################
    @staticmethod
    def _validate_if_filename_for_zip_provided(
        read_format: Union[str, InputFormat, None] = None,
        filename_in_zip: Union[str, None] = None,
    ):
        """
        Raise exception if filename_in_zip is not provided for ZIP data source
        Args:
            read_format: format of data source
            filename_in_zip: used for ZIP format to identify which file out of ZIP to take
        """
        if isinstance(read_format, InputFormat):
            read_format = read_format.value
        if read_format and read_format == InputFormat.ZIP.value and not filename_in_zip:
            raise TransformationsMissingArgumentException(
                argument_name="filename_in_zip",
                function_name="preprocess",
                mark_as_mandatory=False,
            )

    @staticmethod
    def _validate_if_read_format_supported(
        read_format: Union[str, InputFormat, None] = None,
    ):
        """
        Raise exception if read_format is not supported
        Args:
            read_format: format of data source
        """
        if not isinstance(read_format, InputFormat):
            supported_file_extensions = InputFormat.get_supported_formats()
            if read_format and read_format not in supported_file_extensions:
                raise TransformationsFileExtensionNotSupportedException(
                    file_extension=read_format,
                    supported_file_extensions=supported_file_extensions,
                )

    @staticmethod
    def _parse_file_extension(
        filepath_or_filename: str,
        default_extension_handler: InputFormat = InputFormat.CSV,
        raise_warning: bool = False,
    ) -> str:
        """
        Filepath parser which takes file extension, removes dot and down-cases it
        Additional check is performed to validate if the format is supported
        Args:
            filepath_or_filename: filepath,
                if no extension is provided or a string is empty the default
                parser will be called
            default_extension_handler: default handler to be called if
                no extension or empty string was used as input
            raise_warning: bool, if True warning message regarding missing format
                and application of the default format will be displayed

        Returns: file extension as str

        """
        supported_file_extensions = InputFormat.get_supported_formats()
        extension_handler = default_extension_handler.value
        if filepath_or_filename and isinstance(filepath_or_filename, str):
            file_extension = Path(filepath_or_filename).suffix
            file_extension = file_extension.replace(".", "").lower()
        else:
            file_extension = None
        if not file_extension and raise_warning:
            raise TransformationsFileExtensionNotDefinedWarning(
                filepath=filepath_or_filename,
                default_extension=str(extension_handler),
            )
        elif not file_extension:
            pass
        elif file_extension in supported_file_extensions:
            extension_handler = file_extension
        else:
            raise TransformationsFileExtensionNotSupportedException(
                file_extension=file_extension,
                supported_file_extensions=supported_file_extensions,
            )
        return extension_handler

    ######################################################################################
    # graph construction methods
    ######################################################################################
    def _get_src_and_dst_uuids(self):
        """
        Get current node uuid, generate new one, assign it to the node and
            return this new uuid
        Returns: a pair of uuids (old and current which was newly generated)

        """
        src_node_uuid = self._uuid
        dst_node_uuid = self.__uuid_instance.update_uuid()
        return src_node_uuid, dst_node_uuid

    def _add_graph_dst_node_with_edge(
        self,
        node_label: str,
        node_command: str,
        node_command_src_key: Union[str, None] = None,
        node_command_kwargs: Union[dict, None] = None,
        create_a_copy: bool = True,
        include_identifier: bool = False,  # No need to provide more details
    ):
        """
        Add a node with an edge to the graph
        Args:
            node_label: label to be displayed on the graph
            node_command: the command which will be applied during the run call
            node_command_src_key: a key where the source node uuid to be stored
            node_command_kwargs: other arguments to be used for the command
            create_a_copy: bool, if True a copy of the current object will be created and
                returned
            include_identifier: bool, if True command arguments
                will be included in the node label

        Returns: if create_a_copy if True returns new instance of the current object with
            updated graph
        otherwise updates graph inplace and returns itself

        """
        new_self = copy.deepcopy(self) if create_a_copy else self

        src_node_uuid, dst_node_uuid = new_self._get_src_and_dst_uuids()

        node_command_kwargs = node_command_kwargs or dict()
        if node_command_src_key:
            node_command_kwargs[node_command_src_key] = src_node_uuid

        new_self.__nx_graph.add_graph_dst_node_with_edge(
            src_node_uuid=src_node_uuid,
            dst_node_uuid=dst_node_uuid,
            node_label=node_label,
            node_command=node_command,
            node_command_kwargs=node_command_kwargs,
            include_identifier=include_identifier,
        )

        return new_self

    @staticmethod
    def _convert_to_list(obj):
        if isinstance(obj, list):
            return obj
        else:
            return [obj]

    def _add_graph_dst_node_with_multiple_edges(
        self,
        node_label: str,
        other_srcs: Union[List["FederatedDataFrame"], "FederatedDataFrame"],
        node_command: str,
        node_command_src_key: Union[str, None] = None,
        node_command_other_srcs_keys: Union[List[Union[str, None]], str, None] = None,
        node_command_kwargs: Union[dict, None] = None,
        edges_labels: Union[Dict, None] = None,
        create_a_copy: bool = True,
        include_identifier: bool = False,  # No need to provide more details
    ):
        """
        Compose a graph from multiple: the initial graph and other (more than 1) sources,
            add a node with multiple (more than 2) edges
        Args:
            node_label: label to be displayed on the graph
            other_srcs: list of uuids of other source nodes
            node_command: the command which will be applied during the run call
            node_command_src_key: a key where the source node uuid to be stored
            node_command_other_srcs_keys: a list of keys where other source nodes uuids
                to be stored
            node_command_kwargs: other arguments to be used for the command
            edges_labels: dict with labels to be assigned to the edges
            create_a_copy: bool, if True a copy of the current object will be created and
                returned
            include_identifier: bool, if True command arguments
                will be included in the node label

        Returns: if create_a_copy if True returns new instance of the current object
        with updated graph otherwise updates graph inplace and returns itself

        """
        # Perform inputs types conversion and checks
        other_srcs = self._convert_to_list(other_srcs)
        node_command_other_srcs_keys = self._convert_to_list(node_command_other_srcs_keys)
        arguments = [other_srcs, node_command_other_srcs_keys]
        if edges_labels:
            arguments.append(edges_labels)
        numbers_of_arguments = list(map(len, arguments))
        if len(set(numbers_of_arguments)) > 1:
            raise TransformationsNotMatchingNumberOfArgumentsException(
                trigger_argument_name=f"{node_command} sources",
                numbers_of_arguments=numbers_of_arguments,
            )
        for other_src_i, other_src in enumerate(other_srcs):
            if not isinstance(other_src, FederatedDataFrame):
                raise TransformationsOperationArgumentTypeNotAllowedException(
                    function_name=node_command,
                    argument_name=node_command_other_srcs_keys[other_src_i],
                    argument_type=type(other_src),
                    supported_argument_types=[FederatedDataFrame],
                )

        # Create the copy of the self and update the uuid
        new_self = copy.deepcopy(self) if create_a_copy else self
        src_node_uuid, dst_node_uuid = new_self._get_src_and_dst_uuids()

        # Process sources to fill in other uuids in node command kwargs, compose graph
        src_nodes_uuids = [src_node_uuid]
        node_command_kwargs = node_command_kwargs or dict()
        if node_command_src_key:
            node_command_kwargs[node_command_src_key] = src_node_uuid
        for other_src_i, other_src in enumerate(other_srcs):
            new_self.__nx_graph = nx.compose(new_self.__nx_graph, other_src._graph)
            another_src_node_uuid = other_src._uuid
            src_nodes_uuids.append(another_src_node_uuid)
            node_command_another_src_key = node_command_other_srcs_keys[other_src_i]
            if node_command_another_src_key:
                node_command_kwargs[node_command_another_src_key] = another_src_node_uuid

        # Add destination node with multiple edges
        new_self.__nx_graph.add_graph_dst_node_with_multiple_edges(
            src_nodes_uuids=src_nodes_uuids,
            dst_node_uuid=dst_node_uuid,
            node_label=node_label,
            node_command=node_command,
            node_command_kwargs=node_command_kwargs,
            edges_labels=edges_labels,
            include_identifier=include_identifier,
        )
        return new_self

    ######################################################################################
    # methods which are called by user and are mapped to the remote functions
    ######################################################################################
    def _read_data(
        self,
        src_node_uuid: str,
        data_source: str,
        read_format: Union[str, InputFormat],
        read_args: Union[dict, None] = None,
        include_identifier: bool = True,
    ):
        """
        Read inout data source
        Args:
            src_node_uuid: uuid to the source node
            data_source: remote id (for RemoteData) or path to a file
            read_format: input format
            read_args: used for ZIP format to identify which file out of ZIP to take
            include_identifier: bool, if True command arguments
                will be included in the node label
        """
        try:
            if isinstance(read_format, str):
                read_format = InputFormat[read_format.upper()]
        except KeyError:
            raise TransformationsFileExtensionNotSupportedException(
                file_extension=read_format,
                supported_file_extensions=InputFormat.get_supported_formats(),
            )
        if read_format == InputFormat.ZIP and not read_args.get("filename"):
            raise TransformationsMissingArgumentException(
                function_name="read", argument_name="filename_in_zip"
            )
        # additional arguments: no need to fail here, but educate user
        if read_format != InputFormat.ZIP and read_args.get("filename"):
            print(
                f"Argument 'filename_in_zip' is ignored "
                f"as is is not supported for reading {read_format.value}."
            )
            del read_args["filename"]

        self.__nx_graph.add_graph_src_node(
            src_node_uuid=src_node_uuid,
            node_label=f"Read {read_format.value}",
            node_command=NodeCommands.get_read_data_function(read_format).name,
            node_command_kwargs={
                "data_source": data_source,
                "read_args": read_args,
            },
            include_identifier=include_identifier,
        )

    def __setitem__(
        self,
        index: Union[str, int],
        value: Union[ALL_TYPES],
    ):
        """
        Manipulates values of a columns or rows of a FederatedDataFrame. This
        operation does not return a copy of the FederatedDataFrame object,
        instead this operation is implemented inplace.
        That means, the computation graph within the FederatedDataFrame
        object is modified on the object level.
        This function is not available in a privacy fully preserving mode.

        Example:

            Assume the dummy data for 'data_cloudnode' looks like this:

            ```
                patient_id  age  weight
            0           1   77      55
            1           2   88      60
            2           3   93      83

            df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode')
            df["new column"] = df["weight"]
            df.preprocess_on_dummy()
            ```

            results in
            ```
               patient_id  age  weight  new_column
            0           1   77      55          55
            1           2   88      60          60
            2           3   93      83          83
            ```

        Args:
            index: column index or name or a boolean valued FederatedDataFrame as index
            mask.
            value: a constant value or a single column FederatedDataFrame
        """
        if isinstance(value, FederatedDataFrame):
            self._add_graph_dst_node_with_multiple_edges(
                node_label=f"Set column '{index}'",
                other_srcs=value,
                node_command=NodeCommands.setitem.name,
                node_command_src_key="table",
                node_command_other_srcs_keys="column_to_add",
                node_command_kwargs={
                    "index": index,
                },
                create_a_copy=False,  # This is an inplace operation
            )
        elif isinstance(value, (str, int, float)):
            value_for_label = f"'{value}'" if isinstance(value, str) else value
            self._add_graph_dst_node_with_edge(
                node_label=f"Set column '{index}' = {value_for_label}",
                node_command=NodeCommands.setitem.name,
                node_command_src_key="table",
                node_command_kwargs={"index": index, "value_to_add": value},
                create_a_copy=False,  # This is an inplace operation
            )
        else:
            raise TransformationsOperationArgumentTypeNotAllowedException(
                function_name=NodeCommands.setitem.name,
                argument_name="value",
                argument_type=type(value),
                supported_argument_types=[FederatedDataFrame, str, int, float],
            )

    def __getitem__(
        self,
        key: Union[str, int, "FederatedDataFrame"],
    ) -> "FederatedDataFrame":
        """

        Example:
            Assume the dummy data for 'data_cloudnode' looks like this:
            ```
                patient_id  age  weight
            0           1   77      55
            1           2   88      60
            2           3   93      83

            df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode')
            df = df["weight"]
            df.preprocess_on_dummy()
            ```

            results in
            ```
               weight
            0    55
            1    60
            2    83
            ```
        Args:
            key: column index or name or a boolean valued FederatedDataFrame as index
            mask.

        Returns:
            new instance of the current object with updated graph. If the key was a
            column identifier, the computation graph results in a single-column
            FederatedDataFrame. If the key was an index mask the resulting computation
            graph will produce a filtered FederatedDataFrame.
        """
        if isinstance(key, (str, int)):
            # We want to get a column
            return self._add_graph_dst_node_with_edge(
                node_label=f"Get column '{key}'",
                node_command=NodeCommands.getitem.name,
                node_command_kwargs={
                    "column": key,
                },
            )
        elif isinstance(key, FederatedDataFrame):
            # We want to select rows w.r.t. index `key`
            return self._add_graph_dst_node_with_multiple_edges(
                node_label="Filter using index_mask",
                other_srcs=key,
                node_command=NodeCommands.getitem_at_index_table.name,
                node_command_src_key="table",
                node_command_other_srcs_keys="index",
                edges_labels={key._uuid: "index_mask"},
            )
        else:
            raise TransformationsInputTypeException(
                function_name=self.__getitem__.__name__,
                argument_name="key",
                argument_type=type(key),
            )

    def add(self, left, right, result=None) -> FederatedDataFrame:
        """Privacy-preserving addition: to a column (`left`)
        add another column or constant value (`right`)
        and store the result in `result`.
        Adding arbitrary iterables would allow for
        singling out attacks and is therefore disallowed.

        Example:
            Assume the dummy data for 'data_cloudnode' looks like this:
            ```
                patient_id  age  weight
            0           1   77      55
            1           2   88      60
            2           3   93      83

            df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode')
            df.add("weight", 100, "new_weight")
            df.preprocess_on_dummy()
            ```

            returns
            ```
               patient_id  age  weight  new_weight
            0           1   77      55         155
            1           2   88      60         160
            2           3   93      83         183

            df.add("weight", "age", "new_weight")
            ```

            returns
            ```
               patient_id  age  weight  new_weight
            0           1   77      55         132
            1           2   88      60         148
            2           3   93      83         176
            ```

        Args:
            left: a column identifier
            right: a column identifier or constant value
            result: name for the new result column
                can be set to None to overwrite the left column

        Returns:
            new instance of the current object with updated graph.

        """
        if isinstance(right, FederatedDataFrame):
            raise TransformationsOperationArgumentTypeNotAllowedException(
                function_name=self.add.__name__,
                argument_name="right",
                argument_type=type(right),
                supported_argument_types=list(BASIC_TYPES),
            )
        if isinstance(left, FederatedDataFrame):
            raise TransformationsOperationArgumentTypeNotAllowedException(
                function_name=self.add.__name__,
                argument_name="left",
                argument_type=type(left),
                supported_argument_types=["column identifier"],
            )
        if result is None:
            result = left

        return self._add_graph_dst_node_with_edge(
            node_label=f"{result} = {left} + {right}",
            node_command=NodeCommands.addition.name,
            node_command_src_key="table",
            node_command_kwargs={
                "summand_column1": left,
                "summand2": right,
                "result_column": result,
            },
        )

    def neg(self, column_to_negate, result_column=None) -> FederatedDataFrame:
        """Privacy-preserving negation: negate column `column_to_negate` and store
        the result in column `result_column`, or leave `result_column` as None
        and overwrite `column_to_negate`.
        Using this form of negation removes the need for __setitem__ functionality
        which is not privacy-preserving.

        Example:
            Assume the dummy data for 'data_cloudnode' looks like this:
            ```
                patient_id  age  weight
            0           1   77      55
            1           2   88      60
            2           3   93      83

            df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode')
            df = df.neg("age", "neg_age")
            df.preprocess_on_dummy()
            ```

            returns
            ```
               patient_id  age  weight  neg_age
            0           1   77      55      -77
            1           2   88      60      -88
            2           3   93      83      -93
            ```

        Args:
            column_to_negate: column identifier
            result_column: optional name for the new column,
                if not specified, column_to_negate is overwritten

        Returns:
            new instance of the current object with updated graph.

        """
        if result_column is None:
            result_column = column_to_negate

        return self._add_graph_dst_node_with_edge(
            node_label=f"{result_column} = Negate {column_to_negate}",
            node_command=NodeCommands.negation.name,
            node_command_src_key="table",
            node_command_kwargs={
                "column_to_negate": column_to_negate,
                "result_column": result_column,
            },
        )

    def sub(self, left, right, result) -> FederatedDataFrame:
        """Privacy-preserving subtraction:
        computes `left` - `right` and stores
        the result in the column `result`.
        Both left and right can be column names,
        or one of it a column name and one a constant.
        Arbitrary subtraction with iterables would allow for
        singling-out attacks and is therefore disallowed.

        Example:
            Assume the dummy data for 'data_cloudnode' looks like this:
            ```
                patient_id  age  weight
            0           1   77      55
            1           2   88      60
            2           3   93      83

            df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode'))
            df = df.sub("weight", 100, "new_weight")
            df.preprocess_on_dummy()
            ```

            returns
            ```
               patient_id  age  weight  new_weight
            0           1   77      55         -45
            1           2   88      60         -40
            2           3   93      83         -17

            df.sub("weight", "age", "new_weight")
            ```

            returns
            ```
               patient_id  age  weight  new_weight
            0           1   77      55         -22
            1           2   88      60         -28
            2           3   93      83         -10
            ```

        Args:
            left: column identifier or constant
            right: column identifier or constant
            result: column name for the new result colum

        Returns:
            new instance of the current object with updated graph.

        """
        if isinstance(right, FederatedDataFrame):
            raise TransformationsOperationArgumentTypeNotAllowedException(
                function_name=self.sub.__name__,
                argument_name="right",
                argument_type=type(right),
                supported_argument_types=list(BASIC_TYPES),
            )
        if isinstance(left, FederatedDataFrame):
            raise TransformationsOperationArgumentTypeNotAllowedException(
                function_name=self.sub.__name__,
                argument_name="left",
                argument_type=type(left),
                supported_argument_types=list(BASIC_TYPES),
            )

        return self._add_graph_dst_node_with_edge(
            node_label=f"{result} = {left} - {right}",
            node_command=NodeCommands.subtraction.name,
            node_command_src_key="table",
            node_command_kwargs={"left": left, "right": right, "result": result},
        )

    def mult(self, left, right, result=None) -> FederatedDataFrame:
        """Privacy-preserving multiplication: to a column (`left`)
        multiply another column or constant value (`right`)
        and store the result in `result`.
        Multiplying arbitrary iterables would allow for
        singling out attacks and is therefore disallowed.

        Example:
            Assume the dummy data for 'data_cloudnode' looks like this:
            ```
                patient_id  age  weight
            0           1   77      55
            1           2   88      60
            2           3   93      83

            df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode')
            df.mult("weight", 2, "new_weight")
            df.preprocess_on_dummy()
            ```

            returns
            ```
                patient_id  age  weight  new_weight
            0           1   77      55         110
            1           2   88      60         120
            2           3   93      83         166

            df.mult("weight", "patient_id", "new_weight")
            ```

            returns
            ```
               patient_id  age  weight  new_weight
            0           1   77      55          55
            1           2   88      60         120
            2           3   93      83         249
            ```

        Args:
            left: a column identifier
            right: a column identifier or constant value
            result: name for the new result column,
                can be set to None to overwrite the left column

        Returns:
            new instance of the current object with updated graph.

        """
        if isinstance(right, FederatedDataFrame):
            raise TransformationsOperationArgumentTypeNotAllowedException(
                function_name=self.mult.__name__,
                argument_name="right",
                argument_type=type(right),
                supported_argument_types=["column identifier"],
            )
        if isinstance(left, FederatedDataFrame):
            raise TransformationsOperationArgumentTypeNotAllowedException(
                function_name=self.mult.__name__,
                argument_name="left",
                argument_type=type(left),
                supported_argument_types=list(BASIC_TYPES),
            )
        if result is None:
            result = left
        return self._add_graph_dst_node_with_edge(
            node_label=f"{result} = {left} * {right}",
            node_command=NodeCommands.mult.name,
            node_command_src_key="table",
            node_command_kwargs={
                "left": left,
                "right": right,
                "result": result,
            },
        )

    def truediv(self, left, right, result) -> FederatedDataFrame:
        """Privacy-preserving division: divide a column or constant (`left`)
        by another column or constant (`right`)
        and store the result in `result`.
        Dividing by arbitrary iterables would allow for
        singling out attacks and is therefore disallowed.

        Example:
            Assume the dummy data for 'data_cloudnode' looks like this:
            ```
                patient_id  age  weight
            0           1   77      55
            1           2   88      60
            2           3   93      83

            df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode')
            df.truediv("weight", 2, "new_weight")
            df.preprocess_on_dummy()
            ```

            returns
            ```
                patient_id  age  weight  new_weight
            0           1   77      55        27.5
            1           2   88      60        30.0
            2           3   93      83        41.5

            df.truediv("weight", "patient_id", "new_weight")
            ```

            returns
            ```
               patient_id  age  weight  new_weight
            0           1   77      55   55.000000
            1           2   88      60   30.000000
            2           3   93      83   27.666667
            ```

        Args:
            left: a column identifier
            right: a column identifier or constant value
            result: name for the new result column

        Returns:
            new instance of the current object with updated graph.

        """
        if isinstance(right, FederatedDataFrame):
            raise TransformationsOperationArgumentTypeNotAllowedException(
                function_name=self.truediv.__name__,
                argument_name="right",
                argument_type=type(right),
                supported_argument_types=list(BASIC_TYPES),
            )
        if isinstance(left, FederatedDataFrame):
            raise TransformationsOperationArgumentTypeNotAllowedException(
                function_name=self.truediv.__name__,
                argument_name="left",
                argument_type=type(left),
                supported_argument_types=list(BASIC_TYPES),
            )
        return self._add_graph_dst_node_with_edge(
            node_label=f"{result} = {left} / {right}",
            node_command=NodeCommands.div.name,
            node_command_src_key="table",
            node_command_kwargs={
                "left": left,
                "right": right,
                "result": result,
            },
        )

    def invert(self, column_to_invert, result_column=None) -> FederatedDataFrame:
        """Privacy-preserving inversion (~ operator):
        invert column `column_to_invert` and store
        the result in column `result_column`, or leave `result_column` as None
        and overwrite `column_to_invert`.
        Using this form of negation removes the need for __setitem__ functionality
        which is not privacy-preserving.

        Example:
            Assume the dummy data for 'data_cloudnode' looks like this:
            ```
               patient_id  age  weight  death
            0           1   77    55.0   True
            1           2   88    60.0  False
            2           3   23     NaN   True

            df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode'))
            df = df.invert("death", "survival")
            df.preprocess_on_dummy()
            ```

            returns
            ```
               patient_id  age  weight  death  survival
            0           1   77    55.0   True     False
            1           2   88    60.0  False      True
            2           3   23     NaN   True     False
            ```

        Args:
            column_to_invert: column identifier
            result_column: optional name for the new column,
                if not specified, column_to_negate is overwritten

        Returns:
            new instance of the current object with updated graph.

        """
        if isinstance(column_to_invert, FederatedDataFrame):
            raise TransformationsOperationArgumentTypeNotAllowedException(
                function_name=self.invert.__name__,
                argument_name="column_to_invert",
                argument_type=type(column_to_invert),
                supported_argument_types=["column identifier"],
            )

        if result_column is None:
            result_column = column_to_invert

        return self._add_graph_dst_node_with_edge(
            node_label=f"{result_column} = Invert {column_to_invert}",
            node_command=NodeCommands.inv.name,
            node_command_src_key="table",
            node_command_kwargs={
                "column_to_invert": column_to_invert,
                "result_column": result_column,
            },
        )

    def __lt__(self, other) -> FederatedDataFrame:
        """
        Compare a single-column FederatedDataFrame with a constant using the operator '<'
        Example:
            Assume the dummy data for 'data_cloudnode' looks like this:
            ```
               patient_id  age  weight
            0           1   77      55
            1           2   88      60
            2           3   40      50

            df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode')
            df = df["age"] < df["weight"]
            df.preprocess_on_dummy()
            ```

            returns
            ```
            0    False
            1    False
            2     True
            ```

        Args:
            other: FederatedDataFrame or value to compare with

        Returns:
            single column FederatedDataFrame with computation graph resulting in a
            boolean Series.

        """
        return self._comparison(other, ComparisonType.LESS_THAN)

    def __gt__(self, other) -> FederatedDataFrame:
        """
        Compare a single-column FederatedDataFrame with a constant using the operator '>'

        Example:
            Assume the dummy data for 'data_cloudnode' looks like this:
            ```
               patient_id  age  weight
            0           1   77      55
            1           2   88      60
            2           3   40      50

            df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode')
            df = df["age"] > df["weight"]
            df.preprocess_on_dummy()
            ```

            returns
            ```
            0     True
            1     True
            2    False
            ```

        Args:
            other: FederatedDataFrame or value to compare with

        Returns:
            single column FederatedDataFrame with computation graph resulting in a
            boolean Series.


        """
        return self._comparison(other, ComparisonType.GREATER_THAN)

    def __eq__(self, other) -> FederatedDataFrame:
        """
        Compare a single-column FederatedDataFrame with a constant using the operator '=='

        Example:
            Assume the dummy data for 'data_cloudnode' looks like this:
            ```
               patient_id  age  weight
            0           1   77      55
            1           2   88      60
            2           3   40      40

            df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode')
            df = df["age"] == df["weight"]
            df.preprocess_on_dummy()
            ```

            returns
            ```
            0    False
            1    False
            2     True
            ```

        Args:
            other: FederatedDataFrame or value to compare with

        Returns:
            single column FederatedDataFrame with computation graph resulting in a
            boolean Series.

        """
        return self._comparison(other, ComparisonType.EQUAL_TO)

    def __le__(self, other) -> FederatedDataFrame:
        """
        Compare a single-column FederatedDataFrame with a constant using the operator '<='

        Example:
            Assume the dummy data for 'data_cloudnode' looks like this:
            ```
               patient_id  age  weight
            0           1   77      55
            1           2   88      60
            2           3   40      40

            df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode')
            df = df["age"] <= df["weight"]
            df.preprocess_on_dummy()
            ```

            returns
            ```
            0    False
            1    False
            2     True
            ```

        Args:
            other: FederatedDataFrame or value to compare with

        Returns:
            single column FederatedDataFrame with computation graph resulting in a
            boolean Series.

        """
        return self._comparison(other, ComparisonType.LESS_THAN_OR_EQUAL_TO)

    def __ge__(self, other) -> FederatedDataFrame:
        """
        Compare a single-column FederatedDataFrame with a constant using the operator '>='

        Example:
            Assume the dummy data for 'data_cloudnode' looks like this:
            ```
               patient_id  age  weight
            0           1   77      55
            1           2   88      60
            2           3   40      40

            df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode')
            df = df["age"] >= df["weight"]
            df.preprocess_on_dummy()
            ```

            returns
            ```
            0    True
            1    True
            2    True
            ```

        Args:
            other: FederatedDataFrame or value to compare with

        Returns:
            single column FederatedDataFrame with computation graph resulting in a
            boolean Series.

        """
        return self._comparison(other, ComparisonType.GREATER_THAN_OR_EQUAL_TO)

    def __ne__(self, other) -> FederatedDataFrame:
        """
        Compare a single-column FederatedDataFrame with a constant using the operator '!='

        Example:
            Assume the dummy data for 'data_cloudnode' looks like this:
            ```
               patient_id  age  weight
            0           1   77      55
            1           2   88      60
            2           3   40      40

            df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode')
            df = df["age"] != df["weight"]
            df.preprocess_on_dummy()
            ```

            returns
            ```
            0     True
            1     True
            2    False
            ```

        Args:
            other: FederatedDataFrame or value to compare with

        Returns:
            single column FederatedDataFrame with computation graph resulting in a
            boolean Series.

        """
        return self._comparison(other, ComparisonType.NOT_EQUAL_TO)

    def _comparison(
        self,
        other: Union[ALL_TYPES],
        comparison_type: ComparisonType,
    ):
        """Generic comparison of a single-column FederatedDataFrame with a constant or
        another single-column FederatedDataFrame.
        Args:
            other: constant or single-column FederatedDataFrame to compare with
            comparison_type: string denoting comparison type
        """
        if not isinstance(comparison_type, ComparisonType):
            if hasattr(comparison_type, "value"):
                operation_type = comparison_type.value
            else:
                operation_type = type(comparison_type)
            raise TransformationsOperationNotAllowedException(
                operation_type=operation_type,
                supported_operation_types=ComparisonType.get_supported_types(),
            )
        comparison_type_value = comparison_type.value
        if isinstance(other, BASIC_TYPES):
            value_to_display = f"'{other}'" if isinstance(other, str) else other
            return self._add_graph_dst_node_with_edge(
                node_label=f"{comparison_type_value} {value_to_display}",
                node_command=NodeCommands.compare_to_value.name,
                node_command_src_key="left",
                node_command_kwargs={
                    "right": other,
                    "comparison_type": comparison_type_value,
                },
            )
        elif isinstance(other, FederatedDataFrame):
            return self._add_graph_dst_node_with_multiple_edges(
                node_label=f"{comparison_type_value} column",
                other_srcs=other,
                node_command=NodeCommands.compare_to_table.name,
                node_command_src_key="left",
                node_command_other_srcs_keys="right",
                node_command_kwargs={
                    "comparison_type": comparison_type_value,
                },
            )

        else:
            raise TransformationsOperationArgumentTypeNotAllowedException(
                function_name=self._comparison.__name__,
                argument_name="other",
                argument_type=type(other),
                supported_argument_types=list(BASIC_TYPES + tuple([FederatedDataFrame])),
            )

    def to_datetime(
        self,
        on_column=None,
        result_column=None,
        errors: str = "raise",
        dayfirst: bool = False,
        yearfirst: bool = False,
        utc: bool = None,
        format: str = None,
        exact: bool = True,
        unit: str = "ns",
        infer_datetime_format: bool = False,
        origin="unix",
    ) -> FederatedDataFrame:
        """Convert the column `on_column` to datetime format.
        Further arguments can be passed to the respective underlying pandas'
        to_datetime function with kwargs.
        Results in a table where `column` is updated,
        no need for the unsafe __setitem__ operation.


        Example:
            Assume the dummy data for 'data_cloudnode' looks like this:
            ```
               patient_id  start_date    end_date
            0           1  "2015-08-01"  "2015-12-01"
            1           2  "2017-11-11"  "2020-11-11"
            2           3  "2020-01-01"         NaN

            df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode')
            df = df.to_datetime("start_date", "new_start_date")
            df.preprocess_on_dummy()
            ```

            returns
            ```
                   patient_id  start_date    end_date new_start_date
            0           1  "2015-08-01"  "2015-12-01"     2015-08-01
            1           2  "2017-11-11"  "2020-11-11"     2017-11-11
            2           3  "2020-01-01"          NaN      2020-01-01
            ```

        Args:
            on_column: column to convert
            result_column: optional column where the result should be stored,
                defaults to on_column if not specified
            errors: optional argument how to handle errors during parsing,
                "raise": raise an exception upon errors (default),
                "coerce": set value to NaT and continue,
                "ignore": return the input and continue
            dayfirst: optional argument to specify the parse order,
                if True, parses with the day first,
                e.g. 01/02/03 is parsed to 1st February 2003
                defaults to False
            yearfirst: optional argument to specify the parse order,
                if True, parses the year first,
                e.g. 01/02/03 is parsed to 3rd February 2001
                defaults to False
            utc: optional argument to control the time zone,
                if False (default), assume input is in UTC,
                if True, time zones are converted to UTC
            format: optional strftime argument to parse the time,
                e.g. "%d/%m/%Y, defaults to None
            exact: optional argument to control how "format" is used,
                if True (default), an exact format match is required,
                if False, the format is allowed to match anywhere
                    in the target string
            unit: optional argument to denote the unit, defaults to "ns",
                e.g. unit="ms" and origin="unix" calculates the number
                of milliseconds to the unix epoch start
            infer_datetime_format: optional argument to attempt to infer
                the format based on the first (non-NaN) argument when
                set to True and no format is specified, defaults to False
            origin: optional argument to define the reference date,
                numeric values are parsed as number of units defined by
                the "unit" argument since the reference date,
                e.g. "unix" (default) sets the origin to 1970-01-01,
                "julian" (with "unit" set to "D") sets the origin to the
                beginning of the Julian Calendar (January 1st 4713 BC).

        Returns:
            new instance of the current object with updated graph.

        """

        if result_column is None:
            result_column = on_column
        kwargs = {
            "errors": errors,
            "dayfirst": dayfirst,
            "yearfirst": yearfirst,
            "utc": utc,
            "format": format,
            "exact": exact,
            "unit": unit,
            "infer_datetime_format": infer_datetime_format,
            "origin": origin,
        }
        # avoid "ValueError: cannot specify both format and unit" for default values
        if format is None:
            kwargs.pop("format")
        if unit == "ns":
            kwargs.pop("unit")
        return self._add_graph_dst_node_with_edge(
            node_label=f"'{result_column}' = pd.to_datetime('{on_column}')",
            node_command=NodeCommands.to_datetime.name,
            node_command_src_key="table",
            node_command_kwargs={
                "column": on_column,
                "result": result_column,
                "args": kwargs,
            },
            include_identifier=True,
        )

    def _add_operation_to_graph(self, command: str, args: dict = None):
        """
        Helper function for adding a new operation to the computation graph
        Args:
            command: identifier of the function to be called
            args: function arguments as a dict

        """
        return self._add_graph_dst_node_with_edge(
            node_label=f"Apply {command}",
            node_command=command,
            node_command_src_key="table",
            node_command_kwargs={
                "args": args,
            },
            include_identifier=True,
        )

    def fillna(
        self, value: Union[ALL_TYPES], on_column=None, result_column=None
    ) -> FederatedDataFrame:
        """
        Fill NaN values with a constant (int, float, string)
        similar to pandas' fillna.
        The following arguments from pandas implementation are not supported:
        `method`, `axis`, `inplace`, `limit`, `downcast`

        Example:
            Assume the dummy data for 'data_cloudnode' looks like this:
            ```
               patient_id   age  weight
            0           1  77.0    55.0
            1           2   NaN    60.0
            2           3  88.0     NaN
            df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode')
            df2 = df.fillna(7)
            df2.preprocess_on_dummy()
            ```

            returns
            ```
               patient_id   age  weight
            0           1  77.0    55.0
            1           2   7.0    60.0
            2           3  88.0     7.0
            df3 = df.fillna(7, on_column="weight")
            df3.preprocess_on_dummy()
            ```

            returns
            ```
               patient_id   age  weight
            0           1  77.0    55.0
            1           2   NaN    60.0
            2           3  88.0     7.0
            ```

        Args:
            value: value to use for filling up NaNs
            on_column: only operate on the specified column,
                defaults to None, i.e., operate on the entire table
            result_column: if on_column is specified,
                optionally store the result in a new column with this name,
                defaults to None, i.e., overwriting the column

        Returns:
            new instance of the current object with updated graph.

        """
        if isinstance(value, FederatedDataFrame):
            return self._add_graph_dst_node_with_multiple_edges(
                node_label=NodeCommands.fillna_table.name,
                other_srcs=value,
                node_command=NodeCommands.fillna_table.name,
                node_command_src_key="table",
                node_command_other_srcs_keys="value",
            )
        elif not isinstance(value, BASIC_TYPES):
            raise TransformationsOperationArgumentTypeNotAllowedException(
                function_name=self.fillna.__name__,
                argument_name="value",
                argument_type=type(value),
                supported_argument_types=list(BASIC_TYPES),
            )

        label = "fillna"
        if on_column is not None and result_column is None:
            result_column = on_column
        if on_column is not None:
            label = f"{result_column} = fillna {on_column}"

        extra_quotes_if_needed = "'" if isinstance(value, str) else ""
        label += " with " + extra_quotes_if_needed + str(value) + extra_quotes_if_needed
        return self._add_graph_dst_node_with_edge(
            node_label=label,
            node_command=NodeCommands.fillna.name,
            node_command_src_key="table",
            node_command_kwargs={
                "value": value,
                "column": on_column,
                "result": result_column,
            },
        )

    def dropna(self, axis=0, how="any", thresh=None, subset=None) -> FederatedDataFrame:
        """Drop Nan values from the table with arguments like for pandas' dropna.

        Example:
            Assume the dummy data for 'data_cloudnode' looks like this:
            ```
               patient_id   age  weight
            0           1  77.0    55.0
            1           2  88.0     NaN
            2           3   NaN     NaN
            df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode')
            df2 = df.dropna()
            df2.preprocess_on_dummy()
            ```

            returns
            ```
                patient_id   age  weight
            0           1  77.0    55.0
            df3 = df.dropna(axis=0, subset=["age"])
            df3.preprocess_on_dummy()
            ```
            returns
            ```
               patient_id   age  weight
            0           1  77.0    55.0
            1           2  88.0     NaN
            ```

        Args:
            axis: axis to apply this operation to, defaults to zero
            how: determine if row or column is removed from FederatedDataFrame,
                when we have at least one NA or all NA, defaults to "any".
                ‘any’ : If any NA values are present, drop that row or column.
                ‘all’ : If all values are NA, drop that row or column.
            thresh: optional - require that many non-NA values to drop,
                defaults to None
            subset: optional - use only a subset of columns,
                defaults to None, i.e., operate on the entire data frame,
                subset of rows is not permitted for privacy reasons.

        Returns:
            new instance of the current object with updated graph.

        """
        if subset is not None:
            if axis == 1 or axis == "columns":
                raise PrivacyException(
                    "Considering only a subset of rows "
                    "for dropping is not privacy preserving."
                )
        return self._add_operation_to_graph(
            NodeCommands.dropna.name,
            args={
                "axis": axis,
                "how": how,
                "thresh": thresh,
                "subset": subset,
            },
        )

    def isna(self, on_column=None, result_column=None) -> FederatedDataFrame:
        """
        Checks if an entry is null for given columns or FederatedDataFrame and sets
        boolean value accordingly in the result column.

        Example:
            Assume the dummy data for 'data_cloudnode' looks like this:
            ```
                patient_id   age  weight
            0           1  77.0    55.0
            1           2  88.0     NaN
            2           3   NaN     NaN
            df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode')
            df2 = df.isna()
            df2.preprocess_on_dummy()
            ```
            returns
            ```
                patient_id    age  weight
            0       False  False   False
            1       False  False   False
            2       False   True    True
            df3 = df.isna("age", "na_age")
            df3.preprocess_on_dummy()
            ```
            returns
            ```
                patient_id   age  weight na_age
            0           1  77.0    55.0  False
            1           2  88.0     NaN  False
            2           3   NaN     NaN  True
            ```

        Args:
            on_column: column name which is being checked
            result_column: optional result columns. If specified, a new column is added to
            the FederatedDataFrame, otherwise on_column is overwritten.

        Returns:
            new instance of the current object with updated graph.

        """
        label = "isna"
        if on_column is not None and result_column is None:
            result_column = on_column
        if on_column is not None:
            label = f"{result_column} = isna {on_column}"
        return self._add_graph_dst_node_with_edge(
            node_label=label,
            node_command=NodeCommands.isna.name,
            node_command_src_key="table",
            node_command_kwargs={
                "column": on_column,
                "result": result_column,
            },
        )

    def astype(
        self, dtype: Union[type, str], on_column=None, result_column=None
    ) -> FederatedDataFrame:
        """Convert the entire table to the given datatype
        similarly to pandas' astype.
        The following arguments from pandas implementation are not supported:
        `copy`, `errors`
        Optionally arguments not present in pandas implementation:
        `on_column` and `result_column`: give a column to which the astype function
        should be applied.

        Example:
            Assume the dummy data for 'data_cloudnode' looks like this:
            ```
               patient_id  age  weight
            0           1   77    55.4
            1           2   88    60.0
            2           3   99    65.5
            df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode'))
            df2 = df.astype(str)
            df2.preprocess_on_dummy()
            ```
            returns
            ```
               patient_id   age  weight
            0         "1"  "77"  "55.4"
            1         "2"  "88"  "60.0"
            2         "3"  "99"  "65.5"

            df3 = df.astype(float, on_column="age")

               patient_id   age  weight
            0           1  77.0    55.4
            1           2  88.0    60.0
            2           3  99.0    65.5
            ```

        Args:
            dtype: type to convert to
            on_column: optional column to convert, defaults to None,
                i.e., the entire FederatedDataFrame is converted
            result_column: optional result column if on_column is specified,
                defaults to None, i.e., the on_column is overwritten

        Returns:
            new instance of the current object with updated graph.
        """
        if on_column is not None and result_column is None:
            result_column = on_column
        if isinstance(dtype, type):
            dtype = dtype.__name__

        return self._add_graph_dst_node_with_edge(
            node_label=f"astype {dtype}",
            node_command=NodeCommands.astype.name,
            node_command_src_key="table",
            node_command_kwargs={
                "dtype": dtype,
                "column": on_column,
                "result": result_column,
            },
        )

    def merge(
        self,
        right,
        how="inner",
        on=None,
        left_on=None,
        right_on=None,
        left_index=False,
        right_index=False,
        sort=False,
        suffixes=("_x", "_y"),
        copy=True,
        indicator=False,
        validate=None,
    ) -> FederatedDataFrame:
        """
        Merges two FederatedDataFrames. When the preprocessing privacy guard is enabled,
        merges are only possible as the first preprocessing step.

        Example:
            Assume the dummy data for 'data_cloudnode' looks like this:
            ```
            patients.csv
                id  age  death
            0  423   34      1
            1  561   55      0
            2  917   98      1
            insurance.csv
                id insurance
            0  561        TK
            1  917       AOK
            2  123      None
            patients = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode'),
                filename_in_zip="patients.csv")
            insurance = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode'),
                filename_in_zip="insurance.csv")
            merge1 = patients.merge(insurance, left_on="id", right_on="id", how="left")
            merge1.preprocess_on_dummy()
            returns
                id  age  death insurance
            0  423   34      1       NaN
            1  561   55      0        TK
            2  917   98      1       AOK
            merge2 = patients.merge(insurance, left_on="id", right_on="id", how="right")
            merge2.preprocess_on_dummy()
            ```
            returns
            ```
                id   age  death insurance
            0  561  55.0    0.0        TK
            1  917  98.0    1.0       AOK
            2  123   NaN    NaN      None
            ```


            ```
            merge3 = patients.merge(insurance, left_on="id", right_on="id", how="outer")
            merge3.preprocess_on_dummy()
            ```
            returns
            ```
                id   age  death insurance
            0  423  34.0    1.0       NaN
            1  561  55.0    0.0        TK
            2  917  98.0    1.0       AOK
            3  123   NaN    NaN      None
            ```

        Args:
            right: the other FederatedDataFrame to merge with
            how: type of merge ("left", "right", "outer", "inner", "cross"); see also (*)
            on: column or index to join on, that is available on both sides; see also (*)
            left_on: column or index to join the left FederatedDataFrame; see also (*)
            right_on: column or index to join the right FederatedDataFrame; see also (*)
            left_index: use the index of the left FederatedDataFrame; see also (*)
            right_index: use the index of the right FederatedDataFrame; see also (*)
            sort: Sort the join keys in the resulting FederatedDataFrame; see also (*)
            suffixes: A sequence ot two strings. If columns overlap, these suffixes are
                appended to column names; see also (*)
                defaults to ("_x", "_y"), i.e., if you have the column "id" in both
                tables, the left table's id column will be renamed to "id_x"
                and the right to "id_y".
            copy: see (*)
            indicator: If true, a column "_merge" will be added to the resulting
                FederatedDataFrame that indicates the origin of a row; see also (*)
            validate: “one_to_one”/“one_to_many”/“many_to_one”/“many_to_many”. If set, a
                check is performed if the specified type is met. See also (*)
            (*): https://pandas.pydata.org/docs/reference/api/pandas.merge.html

        Returns:
            new instance of the current object with updated graph.

        Raises:
            PrivacyException if merges are unsecure due the operations done before

        """
        node_label_args = list()
        for arg_name, arg_value in {
            "left_on": left_on,
            "right_on": right_on,
            "on": on,
        }.items():
            if arg_value:
                node_label_args.append(f"{arg_name}='{arg_value}'")
        node_label_args = ", ".join(node_label_args) or f"on={on}"
        return self._add_graph_dst_node_with_multiple_edges(
            node_label=f"Merge with {node_label_args}",
            other_srcs=right,
            node_command=NodeCommands.merge.name,
            node_command_src_key="left",
            node_command_other_srcs_keys="right",
            node_command_kwargs={
                "how": how,
                "on": on,
                "left_on": left_on,
                "right_on": right_on,
                "left_index": left_index,
                "right_index": right_index,
                "sort": sort,
                "suffixes": suffixes,
                "copy": copy,
                "indicator": indicator,
                "validate": validate,
            },
        )

    def concat(
        self,
        other: FederatedDataFrame,
        join: str = "outer",
        ignore_index: bool = True,
        verify_integrity: bool = False,
        sort: bool = False,
    ) -> FederatedDataFrame:
        """
        Concatenate two FederatedDataFrames verically.
        The following arguments from pandas implementation are not supported:
        `keys`, `levels`, `names`, `verify_integrity`, `copy`.
        Args:
            other: the other FederatedDataFrame to concatenate with
            join: type of join to perform ('inner' or 'outer'), defaults to 'outer'
            ignore_index: whether to ignore the index, defaults to True
            verify_integrity: whether to verify the integrity of the result, defaults
                to False
            sort: whether to sort the result, defaults to False
        """

        return self._add_graph_dst_node_with_multiple_edges(
            node_label="Concatenate",
            other_srcs=other,
            node_command=NodeCommands.concat.name,
            node_command_src_key="table1",
            node_command_other_srcs_keys="table2",
            node_command_kwargs={
                "ignore_index": ignore_index,
                "join": join,
                "verify_integrity": verify_integrity,
                "sort": sort,
            },
        )

    def rename(
        self,
        columns: dict,
    ) -> FederatedDataFrame:
        """
        Rename column(s) similarly to pandas' rename.
        The following arguments from pandas implementation are not supported:
        `mapper`,`index`, `axis`, `copy`, `inplace`, `level`, `errors`


        Example:
            Assume the dummy data for 'data_cloudnode' looks like this:
            ```
               patient_id  age  weight
            0           1   77    55.4
            1           2   88    60.0
            2           3   99    65.5
            df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode'))
            df = df.rename({"patient_id": "patient_id_new", "age": "age_new"})
            df.preprocess_on_dummy()
            ```
            returns
            ```
               patient_id_new  age_new  weight
            0           1           77    55.4
            1           2           88    60.0
            2           3           99    65.5
            ```

        Args:
            columns: dict containing the remapping of old names to new names

        Returns:
            new instance of the current object with updated graph
        """
        if not isinstance(columns, dict):
            raise TransformationsOperationArgumentTypeNotAllowedException(
                function_name=self.rename.__name__,
                argument_name="columns",
                argument_type=type(columns),
                supported_argument_types=[dict],
            )
        else:
            return self._add_graph_dst_node_with_edge(
                node_label=f"Rename using {columns}",
                node_command=NodeCommands.rename.name,
                node_command_kwargs={
                    "mapping": columns,
                },
            )

    def drop_column(self, column) -> FederatedDataFrame:
        """Remove the given column from the table.

        Example:
            Assume the dummy data for 'data_cloudnode' looks like this:
            ```
            patient_id  age  weight
            0           1   77      55
            1           2   88      60
            2           3   93      83
            df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode'))
            df = df.drop_column("weight")
            df.preprocess_on_dummy()
            ```
            returns
            ```
            patient_id  age
            0           1   77
            1           2   88
            2           3   93
            ```

        Args:
            column: column name to drop

        Returns:
            new instance of the current object with updated graph.
        """

        return self._add_graph_dst_node_with_edge(
            node_label=f"drop {column}",
            node_command=NodeCommands.drop_column.name,
            node_command_src_key="table",
            node_command_kwargs={
                "column": column,
            },
        )

    def sample(
        self,
        n: Optional[int] = None,
        frac: Optional[float] = None,
        replace: bool = False,
        random_state: Optional[int] = None,
        ignore_index: bool = False,
    ):
        """Sample the data frame based on a given mask and percentage.
        Only one of `n` (number of samples) or `frac` (fraction of the data)
        can be specified. The following arguments from pandas implementation are not
        supported: `weights` and `axis`.

        Args:
            n: number of samples to take
            frac: fraction of the data to sampl between 0 and 1
            replace: whether to sample with replacement
            random_state: seed for the random number generator
            ignore_index: whether to ignore the index when sampling
        """
        if (n is not None and frac is not None) or (n is None and frac is None):
            raise ValueError("Please enter a value for `frac` OR `n`, not both")

        if frac and (frac <= 0 or frac > 1):
            raise ValueError("Please enter a value between 0 and 1 for `frac`")

        return self._add_operation_to_graph(
            command=NodeCommands.sample.name,
            args={
                "n": n,
                "frac": frac,
                "replace": replace,
                "random_state": random_state,
                "ignore_index": ignore_index,
            },
        )

    def __add__(
        self,
        other: Union[ALL_TYPES],
    ) -> FederatedDataFrame:
        """
        Arithmetic operator, which adds a constant value or a single column
        FederatedDataFrame to a single column FederatedDataFrame. This operator is
        useful only in combination with setitem. In a privacy preserving mode use
        the `add` function instead.

        Example:
            Assume the dummy data for 'data_cloudnode' looks like this:
            ```
                patient_id  age  weight
            0           1   77      55
            1           2   88      60
            2           3   93      83
            df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode')
            df["new_weight"] = df["weight"] + 100
            df.preprocess_on_dummy()
            ```
            returns
            ```
               patient_id  age  weight  new_weight
            0           1   77      55         155
            1           2   88      60         160
            2           3   93      83         183
            ```

            ```
            df["new_weight"] = df["weight"] + df["age"]
            ```
            returns
            ```
               patient_id  age  weight  new_weight
            0           1   77      55         132
            1           2   88      60         148
            2           3   93      83         176
            ```


        Args:
            other: constant value or a single column FederatedDataFrame to add.

        Returns:
            new instance of the current object with updated graph.

        """
        if isinstance(other, FederatedDataFrame):
            # We want to add two columns
            return self._add_graph_dst_node_with_multiple_edges(
                node_label="Sum",
                other_srcs=other,
                node_command=NodeCommands.add_table.name,
                node_command_src_key="summand1",
                node_command_other_srcs_keys="summand2",
            )
        elif isinstance(other, BASIC_TYPES):
            return self._add_graph_dst_node_with_edge(
                node_label=f"Add a value '{other}'",
                node_command=NodeCommands.add_number.name,
                node_command_src_key="summand1",
                node_command_kwargs={
                    "summand2": other,
                },
            )
        else:
            raise TransformationsOperationArgumentTypeNotAllowedException(
                function_name=self.__add__.__name__,
                argument_name="other",
                argument_type=type(other),
                supported_argument_types=list(BASIC_TYPES + tuple([FederatedDataFrame])),
            )

    def __radd__(self, other) -> FederatedDataFrame:
        """
        Arithmetic operator, which adds a constant value or a single column
        FederatedDataFrame to a single column FederatedDataFrame from right. This operator
        is useful only in combination with setitem. In a privacy preserving mode use
        the `add` function instead.

        Example:
            Assume the dummy data for 'data_cloudnode' looks like this:
            ```
                patient_id  age  weight
            0           1   77      55
            1           2   88      60
            2           3   93      83
            df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode')
            df["new_weight"] = 100 + df["weight"]
            df.preprocess_on_dummy()
            ```
            returns
            ```
               patient_id  age  weight  new_weight
            0           1   77      55         155
            1           2   88      60         160
            2           3   93      83         183
            ```


        Args:
            other: constant value or a single column FederatedDataFrame to add.

        Returns:
            new instance of the current object with updated graph.
        """
        return self.__add__(other)

    def __neg__(self) -> FederatedDataFrame:
        """
        Logical operator, which negates values of a single column
        FederatedDataFrame. This operator is
        useful only in combination with setitem. In a privacy preserving mode use
        the `neg` function instead.

        Example:
            Assume the dummy data for 'data_cloudnode' looks like this:
            ```
                patient_id  age  weight
            0           1   77      55
            1           2   88      60
            2           3   93      83
            df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode')
            df["neg_age"] = - df["age"]
            df.preprocess_on_dummy()
            ```
            returns
            ```
                patient_id  age  weight  neg_age
            0           1   77      55      -77
            1           2   88      60      -88
            2           3   93      83      -93
            ```

        Returns:
            new instance of the current object with updated graph.

        """
        return self._add_graph_dst_node_with_edge(
            node_label="Negate",
            node_command=NodeCommands.neg.name,
            node_command_src_key="table",
        )

    def __invert__(self) -> FederatedDataFrame:
        """
        Logical operator, which inverts bool values (known as tilde in pandas, ~).

        Example:
            Assume the dummy data for 'data_cloudnode' looks like this:
            ```
               patient_id  age  weight  death
            0           1   77    55.0   True
            1           2   88    60.0  False
            2           3   23     NaN   True
            df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode'))
            df["survival"] = ~df["death"]
            df.preprocess_on_dummy()
            ```
            returns
            ```
               patient_id  age  weight  death  survival
            0           1   77    55.0   True     False
            1           2   88    60.0  False      True
            2           3   23     NaN   True     False
            ```

        Returns:
            new instance of the current object with updated graph.
        """
        return self._add_graph_dst_node_with_edge(
            node_label="~",
            node_command=NodeCommands.invert.name,
            node_command_src_key="table",
        )

    def __sub__(self, other) -> FederatedDataFrame:
        """
        Arithmetic operator, which subtracts a constant value or a single column
        FederatedDataFrame to a single column FederatedDataFrame. This operator is
        useful only in combination with setitem. In a privacy preserving mode use
        the `sub` function instead.

        Example:
            Assume the dummy data for 'data_cloudnode' looks like this:
            ```
                patient_id  age  weight
            0           1   77      55
            1           2   88      60
            2           3   93      83
            df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode'))
            df["new_weight"] = df["weight"] - 100
            df.preprocess_on_dummy()
            ```
            returns
            ```
               patient_id  age  weight  new_weight
            0           1   77      55         -45
            1           2   88      60         -40
            2           3   93      83         -17
            ```

            ```
            df["new_weight"] = df["weight"] - df["age"]
            ```
            returns
            ```
               patient_id  age  weight  new_weight
            0           1   77      55         -22
            1           2   88      60         -28
            2           3   93      83         -10
            ```


        Args:
            other: constant value or a single column FederatedDataFrame to subtract.

        Returns:
            new instance of the current object with updated graph.
        """
        return self.__add__(other.__neg__())

    def __rsub__(self, other) -> FederatedDataFrame:
        """
        Arithmetic operator, which subtracts a single column FederatedDataFrame from a
        constant value or a single column FederatedDataFrame. This operator is
        useful only in combination with setitem. In a privacy preserving mode use
        the `sub` function instead.

        Args:
            other: constant value or a single column FederatedDataFrame from which to
            subtract.

        Returns:
            new instance of the current object with updated graph.

        Example:
            Assume the dummy data for 'data_cloudnode' looks like this:
            ```
                patient_id  age  weight
            0           1   77      55
            1           2   88      60
            2           3   93      83

            df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode'))
            df["new_weight"] = 100 - df["weight"]
            df.preprocess_on_dummy()
            ```

            returns
            ```
               patient_id  age  weight  new_weight
            0           1   77      55         45
            1           2   88      60         40
            2           3   93      83         17
            ```
        """

        return self.__neg__().__add__(other)

    def __truediv__(
        self,
        other: Union[(FederatedDataFrame, int, float, bool)],
    ) -> FederatedDataFrame:
        """
        Arithmetic operator, which divides FederatedDataFrame by a constant or
        another FederatedDataFrame.

        Example:
            Assume the dummy data for 'data_cloudnode' looks like this:
            ```
                patient_id  age  weight
            0           1   77      55
            1           2   88      60
            2           3   93      83
            df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode')
            df["new_weight"] = df["weight"] / 2
            df.preprocess_on_dummy()
            ```
            returns
            ```
                patient_id  age  weight  new_weight
            0           1   77      55        27.5
            1           2   88      60        30.0
            2           3   93      83        41.5
            ```

            ```
            df["new_weight"] = df["weight"] / df["patient_id"]
            ```
            returns
            ```
               patient_id  age  weight  new_weight
            0           1   77      55   55.000000
            1           2   88      60   30.000000
            2           3   93      83   27.666667
            ```


        Args:
            other: constant value or another FederatedDataFrame to divide by.

        Returns:
            new instance of the current object with updated graph.
        """
        if isinstance(other, FederatedDataFrame):
            # We want to add two columns
            return self._add_graph_dst_node_with_multiple_edges(
                node_label="dividend / divisor",
                other_srcs=other,
                node_command=NodeCommands.divide.name,
                node_command_src_key="dividend",
                node_command_other_srcs_keys="divisor",
                edges_labels={other._uuid: "divisor"},
            )
        elif isinstance(other, (int, float, bool)):
            return self._add_graph_dst_node_with_edge(
                node_label=f"dividend / {other}",
                node_command=NodeCommands.divide_by_constant.name,
                node_command_src_key="dividend",
                node_command_kwargs={
                    "divisor": other,
                },
            )
        else:
            raise TransformationsOperationArgumentTypeNotAllowedException(
                function_name=self.__truediv__.__name__,
                argument_name="other",
                argument_type=type(other),
                supported_argument_types=[FederatedDataFrame, int, float, bool],
            )

    def __mul__(
        self,
        other: Union[(FederatedDataFrame, int, float, bool)],
    ) -> FederatedDataFrame:
        """
        Arithmetic operator, which multiplies FederatedDataFrame by a constant or
        another FederatedDataFrame.

        Example:
            Assume the dummy data for 'data_cloudnode' looks like this:
            ```
                patient_id  age  weight
            0           1   77      55
            1           2   88      60
            2           3   93      83
            df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode')
            df["new_weight"] = df["weight"] * 2
            df.preprocess_on_dummy()
            ```
            returns
            ```
                patient_id  age  weight  new_weight
            0           1   77      55         110
            1           2   88      60         120
            2           3   93      83         166
            ```

            ```
            df["new_weight"] = df["weight"] * df["patient_id"]
            ```
            returns
            ```
               patient_id  age  weight  new_weight
            0           1   77      55          55
            1           2   88      60         120
            2           3   93      83         249
            ```

        Args:
            other: constant value or another FederatedDataFrame to multiply by.

        Returns:
            new instance of the current object with updated graph.


        """
        if isinstance(other, FederatedDataFrame):
            # We want to add two columns
            return self._add_graph_dst_node_with_multiple_edges(
                node_label="multiplicand * multiplier",
                other_srcs=other,
                node_command=NodeCommands.multiply.name,
                node_command_src_key="multiplicand",
                node_command_other_srcs_keys="multiplier",
                edges_labels={other._uuid: "multiplier"},
            )
        elif isinstance(other, (int, float, bool)):
            return self._add_graph_dst_node_with_edge(
                node_label=f"multiplicand / {other}",
                node_command=NodeCommands.multiply_by_constant.name,
                node_command_src_key="multiplicand",
                node_command_kwargs={
                    "multiplier": other,
                },
            )
        else:
            raise TransformationsOperationArgumentTypeNotAllowedException(
                function_name=self.__mul__.__name__,
                argument_name="other",
                argument_type=type(other),
                supported_argument_types=[FederatedDataFrame, int, float, bool],
            )

    def __rmul__(
        self,
        other: Union[(FederatedDataFrame, int, float, bool)],
    ) -> FederatedDataFrame:
        """
        Arithmetic operator, which multiplies FederatedDataFrame by a constant or
        another FederatedDataFrame.

        Example:
            Assume the dummy data for 'data_cloudnode' looks like this:
            ```
                patient_id  age  weight
            0           1   77      55
            1           2   88      60
            2           3   93      83
            df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode')
            df["new_weight"] = 2 * df["weight"] * 2
            df.preprocess_on_dummy()
            ```
            returns
            ```
                patient_id  age  weight  new_weight
            0           1   77      55         110
            1           2   88      60         120
            2           3   93      83         166
            ```

        Args:
            other: constant value or another FederatedDataFrame to multiply by.
        Returns:
            new instance of the current object with updated graph.
        """
        return self.__mul__(other=other)

    def __and__(self, other: Union[FederatedDataFrame, bool, int]) -> FederatedDataFrame:
        """
        Logical operator, which conjuncts values of a single column
        FederatedDataFrame with a constant or another single column
        FederatedDataFrame.

        Example:
            Assume the dummy data for 'data_cloudnode' looks like this:
            ```
               patient_id  age  death  infected
            0           1   77      1         1
            1           2   88      0         1
            2           3   40      1         0
            df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode')
            df = df["death"] & df["infected"]
            df.preprocess_on_dummy()
            ```
            returns
            ```
            0    1
            1    0
            2    0
            ```
        Args:
            other: constant value or another FederatedDataFrame to logically conjunct

        Returns:
            new instance of the current object with updated graph.

        """
        if isinstance(other, FederatedDataFrame):
            # We want to and-conjunct two columns
            return self._add_graph_dst_node_with_multiple_edges(
                node_label="And",
                other_srcs=other,
                node_command=NodeCommands.logical_conjunction_table.name,
                node_command_src_key="left",
                node_command_other_srcs_keys="right",
                node_command_kwargs={"conjunction_type": "and"},
            )
        elif isinstance(other, (bool, int)):
            return self._add_graph_dst_node_with_edge(
                node_label=f"And '{other}'",
                node_command=NodeCommands.logical_conjunction_number.name,
                node_command_src_key="left",
                node_command_kwargs={"right": other, "conjunction_type": "and"},
            )
        else:
            raise TransformationsOperationArgumentTypeNotAllowedException(
                function_name=self.__and__.__name__,
                argument_name="other",
                argument_type=type(other),
                supported_argument_types=[FederatedDataFrame, bool],
            )

    def __or__(self, other: Union[FederatedDataFrame, bool, int]) -> FederatedDataFrame:
        """
        Logical operator, which conjuncts values of a single column
        FederatedDataFrame with a constant or another single column
        FederatedDataFrame.

        Example:
            Assume the dummy data for 'data_cloudnode' looks like this:
            ```
               patient_id  age  death  infected
            0           1   77      1         1
            1           2   88      0         1
            2           3   40      1         0
            df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode')
            df = df["death"] | df["infected"]
            df.preprocess_on_dummy()
            ```
            returns
            ```
            0    1
            1    1
            2    1
            ```

        Args:
            other: constant value or another FederatedDataFrame to logically conjunct

        Returns:
            new instance of the current object with updated graph.
        """
        if isinstance(other, FederatedDataFrame):
            # We want to or-conjunct two columns
            return self._add_graph_dst_node_with_multiple_edges(
                node_label="Or",
                other_srcs=other,
                node_command=NodeCommands.logical_conjunction_table.name,
                node_command_src_key="left",
                node_command_other_srcs_keys="right",
                node_command_kwargs={"conjunction_type": "or"},
            )
        elif isinstance(other, (bool, int)):
            return self._add_graph_dst_node_with_edge(
                node_label=f"Or '{other}'",
                node_command=NodeCommands.logical_conjunction_number.name,
                node_command_src_key="left",
                node_command_kwargs={"right": other, "conjunction_type": "or"},
            )
        else:
            raise TransformationsOperationArgumentTypeNotAllowedException(
                function_name=self.__or__.__name__,
                argument_name="other",
                argument_type=type(other),
                supported_argument_types=[FederatedDataFrame, bool],
            )

    def str_contains(self, pattern) -> FederatedDataFrame:
        """
        Checks if string values of single column FederatedDataFrame contain
        pattern. Typical usage
        `federated_dataframe[column].str.contains(pattern)`

        Example:
            Assume the dummy data for 'data_cloudnode' looks like this:
            ```
               patient_id  age  weight   race
            0           1   77      55  white
            1           2   88      60  black
            2           3   93      83  asian
            df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode'))
            df = df["race"].str.contains("a")
            df.preprocess_on_dummy()
            ```
            returns
            ```
            0    False
            1     True
            2     True
            ```

        Args:
            pattern: pattern string to check for
        Returns:
            new instance of the current object with updated graph.
        """
        return self._add_graph_dst_node_with_edge(
            node_label=f"contains {pattern}",
            node_command=NodeCommands.str_contains.name,
            node_command_src_key="table",
            node_command_kwargs={
                "pattern": pattern,
            },
        )

    def str_len(self) -> FederatedDataFrame:
        """
        Computes string lenght for each entry. Typical usage
        `federated_dataframe[column].str.len()`

        Example:
            Assume the dummy data for 'data_cloudnode' looks like this:
            ```
               patient_id  age  weight   race
            0           1   77      55      w
            1           2   88      60     bl
            2           3   93      83  asian
            df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode'))
            df = df["race"].str.len()
            df.preprocess_on_dummy()
            ```
            returns
            ```
            0    1
            1    2
            2    5
            ```

        Returns:
            new instance of the current object with updated graph.
        """
        return self._add_graph_dst_node_with_edge(
            node_label="lenght",
            node_command=NodeCommands.str_len.name,
            node_command_src_key="table",
        )

    def dt_datetime_like_properties(self, datetime_like_property):
        """
        Checks if a property of datetime-like object can be applied to a column
        of FederatedDataFrame. Typical usage
        `federated_dataframe[column].dt.days`

        Example:
            Assume the dummy data for 'data_cloudnode' looks like this:
            ```
               patient_id  start_date    end_date
            0           1  2015-08-01  2015-12-01
            1           2  2017-11-11  2020-11-11
            2           3  2020-01-01  2022-06-16
            df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode'))
            df = df.to_datetime("start_date")
            df = df.to_datetime("start_date")
            df = df.sub("end_date", "start_date", "duration")
            df = df["duration"] = df["duration"].dt.days - 5
            df.preprocess_on_dummy()
            ```
            returns
            ```
               patient_id start_date   end_date  duration
            0           1 2015-08-01 2015-12-01       117
            1           2 2017-11-11 2020-11-11      1091
            2           3 2020-01-01 2022-06-16       892
            ```

        Args:
            datetime_like_property: datetime-like (.dt) property to be accessed
        Returns:
            new instance of the current object with updated graph.
        """
        return self._add_graph_dst_node_with_edge(
            node_label=f"Get dt.{datetime_like_property}",
            node_command=NodeCommands.datetime_like_properties.name,
            node_command_src_key="table",
            node_command_kwargs={"datetime_like_property": datetime_like_property},
        )

    def sort_values(
        self,
        by,
        axis=0,
        ascending=True,
        kind="quicksort",
        na_position="last",
        ignore_index=False,
    ) -> FederatedDataFrame:
        """Sort values, similar to pandas' sort_values.
        The following arguments from pandas implementation are not supported:
        `key` - we do not support the `key` argument, as that could be an arbitrary
        function.

        Example:
            Assume the dummy data for 'data_cloudnode' looks like this:
            ```
               patient_id  age  weight
            0           1   77    55.0
            1           2   88    60.0
            2           3   93    83.0
            3           4   18     NaN
            df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode'))
            df = df.sort_values(by="weight", axis="index", ascending=False)
            df.preprocess_on_dummy()
            ```
            returns
            ```
               patient_id  age  weight
            2           3   93    83.0
            1           2   88    60.0
            0           1   77    55.0
            3           4   18     NaN
            ```

        Args:
            by: name or list of names to sort by
            axis: axis to be sorted:
                0 or "index" means sort by index, thus, by contains column labels
                1 or "column" means sort by column, thus, by contains index labels
            ascending: defaults to ascending sorting,
                but can be set to False for descending sorting
            kind: defaults to the quicksort sorting algorithm;
                mergesort, heapsort and stable are available as well
            na_position: defaults to sorting NaNs to the end,
                set to "first" to put them in the beginning
            ignore_index: defaults to false,
                otherwise, the resulting axis will be labelled 0, 1, ... length-1

        Returns:
            new instance of the current object with updated graph.

        """
        return self._add_operation_to_graph(
            command=NodeCommands.sort_values.name,
            args={
                "by": by,
                "axis": axis,
                "ascending": ascending,
                "kind": kind,
                "na_position": na_position,
                "ignore_index": ignore_index,
            },
        )

    def isin(self, values) -> FederatedDataFrame:
        """
        Whether each element in the data is contained in values,
        similar to pandas' isin.

        Example:
            Assume the dummy data for 'data_cloudnode' looks like this:
            ```
            patients.csv:
               patient_id  age  weight
            0           1   77    55.0
            1           2   88    60.0
            2           3   93    83.0
            3           4   18     NaN
            other.csv:
               patient_id  age  weight
            0           1   77    55.0
            1           2   88    60.0
            2           7   33    93.0
            3           8   66     NaN
            df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode'),
                filename_in_zip='patients.csv')
            df = df.isin(values = {"age": [77], "weight": [55]})
            df.preprocess_on_dummy()
            ```
            returns
            ```
               patient_id    age  weight
            0       False   True    True
            1       False  False   False
            2       False  False   False
            3       False  False   False
            ```

            ```
            df_other = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode'),
                filename_in_zip='other.csv')
            df = df.isin(df_other)
            df.preprocess_on_dummy()
            ```
            returns
            ```
               patient_id    age  weight
            0        True   True    True
            1        True   True    True
            2       False  False   False
            3       False  False   False
            ```

        Args:
            values: iterable, dict or FederatedDataFrame to check against.
            Returns true at each location if all the labels match,
            if values is a Series, that's the index,
            if values is a dict, the keys are expected to be column names,
            if values is a FederatedDataFrame, both index and column labels must match.

        Returns:
            new instance of the current object with updated graph.

        """
        if isinstance(values, FederatedDataFrame):
            return self._add_graph_dst_node_with_multiple_edges(
                node_label="isin",
                other_srcs=values,
                node_command=NodeCommands.isin.name,
                node_command_src_key="table",
                node_command_other_srcs_keys="values",
            )
        else:
            return self._add_graph_dst_node_with_edge(
                node_label="isin",
                node_command=NodeCommands.isin.name,
                node_command_src_key="table",
                node_command_kwargs={
                    "iterable_values": values,
                },
            )

    def groupby(
        self, by=None, axis=0, sort=True, group_keys=True, observed=False, dropna=True
    ) -> _FederatedDataFrameGroupBy:
        """Group the data using a mapper. Notice that this operation must be followed by
        an aggregation (such as .last or .first) before further operations can be made.
        The arguments are similar to pandas' original groupby.
        The following arguments from pandas implementation are not supported:
        `axis`, `level`, `as_index`


        Example:
            Assume the dummy data for 'data_cloudnode' looks like this:
            ```
               patient_id  age  weight procedures  start_date
            0           1   77      55          a  2015-08-01
            1           1   77      55          b  2015-10-01
            2           2   88      60          a  2017-11-11
            3           3   93      83          c  2020-01-01
            4           3   93      83          b  2020-05-01
            5           3   93      83          a  2021-01-04
            df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode'))
            grouped_first = df.groupby(by='patient_id').first()
            grouped_first.preprocess_on_dummy()
            ```
            returns
            ```
                        age  weight procedures start_date
            patient_id
            1            77      55          a 2015-08-01
            2            88      60          a 2017-11-11
            3            93      83          c 2020-01-01
            ```

            ```
            grouped_last = df.groupby(by='patient_id').last()
            grouped_last.preprocess_on_dummy()
            ```
            returns
            ```
                        age  weight procedures start_date
            patient_id
            1            77      55          b 2015-10-01
            2            88      60          a 2017-11-11
            3            93      83          a 2021-01-04
            ```

        Args:
            by: dictionary, series, label, or list of labels to determine the groups.
                Grouping with a custom function is not allowed.
                If a dict or Series is passed, the Series or dict VALUES will be used
                to determine the groups.
                If a list or ndarray of length equal to the selected axis is passed,
                the values are used as-is to determine the groups.
                A label or list of labels may be passed to group by the columns in self.
                Notice that a tuple is interpreted as a (single) key.
            axis: Split along rows (0 or "index") or columns (1 or "columns")
            sort: Sort group keys.
            group_keys: During aggregation, add group keys to index to identify groups.
            observed: Only applies to categorical grouping, if true, only show
                observed values, otherwise, show all values.
            dropna: if true and groups contain NaN values, they will be dropped
                together with the row/column, otherwise, treat NaN as key in groups.

        Returns:
            _FederatedGroupBy object to be used in combination with further aggregations.
        Raises:
            PrivacyException if by is a function
        """
        if isinstance(by, Callable):
            raise PrivacyException(
                "Only predefined functions are allowed within a graph, "
                "so grouping by a function is not possible."
            )
        result = self._add_operation_to_graph(
            NodeCommands.groupby.name,
            args={
                "by": by,
                "axis": axis,
                "sort": sort,
                "group_keys": group_keys,
                "observed": observed,
                "dropna": dropna,
            },
        )
        return _FederatedDataFrameGroupBy(result)

    def rolling(
        self,
        window: Union[int, timedelta],
        min_periods: Optional[int] = None,
        center: bool = False,
        on: Optional[str] = None,
        axis: Optional[Union[int, str]] = 0,
        closed: Optional[str] = None,
    ) -> _FederatedDataFrameRolling:
        """
        Rolling window operation, similar to `pandas.DataFrame.rolling`
        Following pandas arguments are not supported: `win_type`, `method`, `step`
        """

        result = self._add_operation_to_graph(
            NodeCommands.rolling.name,
            args={
                "window": window,
                "min_periods": min_periods,
                "center": center,
                "on": on,
                "axis": axis,
                "closed": closed,
            },
        )
        return _FederatedDataFrameRolling(result)

    def drop_duplicates(
        self,
        subset=None,
        keep: Union[Literal["first"], Literal["last"], Literal[False]] = "first",
        ignore_index=False,
    ):
        """Drop duplicates in a table or column, similar to pandas' drop_duplicates

        Example:
            Assume the dummy data for 'data_cloudnode' looks like this:
            ```
               patient_id  age  weight
            0           1   77      55
            1           2   88      83
            2           3   93      83
            3           3   93      83
            df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode')
            df1 = df.drop_duplicates()
            df1.preprocess_on_dummy()
            ```
            returns
            ```
               patient_id  age  weight
            0           1   77      55
            1           2   88      83
            2           3   93      83
            df2 = df.drop_duplicates(subset=['weight'])
            df2.preprocess_on_dummy()
            ```
            returns
            ```
               patient_id  age  weight
            0           1   77      55
            1           2   88      83
            ```

        Args:
            subset: optional column label or sequence of column labels to
                consider when identifying duplicates, uses all columns by default
            keep: string determining which duplicates to keep,
                can be "first" or "last" or set to False to keep no duplicates
            ignore_index: if set to True, the resulting axis will be re-labeled,
                defaults to False

        Returns:
            new instance of the current object with updated graph.

        """
        return self._add_operation_to_graph(
            command=NodeCommands.drop_duplicates.name,
            args={
                "subset": subset,
                "keep": keep,
                "ignore_index": ignore_index,
            },
        )

    def charlson_comorbidities(
        self, index_column: str, icd_columns: List[str], mapping: Dict[str, List] = None
    ):
        """Converts icd codes into comorbidities. If no comorbidity mapping is specified,
        the default mapping of the NCI is used. See function
        'apheris.datatools.transformations.utils.formats.get_default_comorbidity_mapping'
        for the mapping or the original SAS file maintained by the NCI:
        https://healthcaredelivery.cancer.gov/seermedicare/considerations/NCI.comorbidity.macro.sas

        Args:
            index_column: column name of the index column (e.g. patient_id)
            icd_columns: names of columns containing icd codes, contributing
                to comorbidity derivation
            mapping: dictionary that maps comorbidity strings to list of icd codes

        Returns:
            pd.DataFrame with comorbidity columns according to the used mapping and
                index from given index column,
            containing comorbidity entries as boolean values.

        """
        if isinstance(icd_columns, str):
            icd_columns = [icd_columns]

        if mapping is None:
            mapping = get_default_comorbidity_mapping()

        return self._add_operation_to_graph(
            command=NodeCommands.charlson_comorbidities.name,
            args={
                "index_column": index_column,
                "icd_columns": icd_columns,
                "mapping": mapping,
            },
        )

    def charlson_comorbidity_index(
        self,
        index_column: str,
        icd_columns: Union[List[str], str],
        mapping: Dict[str, List] = None,
    ):
        """Converts icd codes into Charlson Comorbidity Index score.
        If no comorbidity mapping is specified,
        the default mapping of the NCI is used. See function
        'apheris.datatools.transformations.utils.formats.get_default_comorbidity_mapping'
        for the mapping or the original SAS file maintained by the NCI:
        https://healthcaredelivery.cancer.gov/seermedicare/considerations/NCI.comorbidity.macro.sas


        Args:
            index_column: column name of the index column (e.g. patient_id)
            icd_columns: names of columns containing icd codes, contributing
                to comorbidity derivation
            mapping: dictionary that maps comorbidity strings to list of icd codes

        Returns:
            pd.DataFrame with containing comorbidity score per patient.

        """
        if isinstance(icd_columns, str):
            icd_columns = [icd_columns]

        if mapping is None:
            mapping = get_default_comorbidity_mapping()

        return self._add_operation_to_graph(
            command=NodeCommands.charlson_comorbidity_score.name,
            args={
                "index_column": index_column,
                "icd_columns": icd_columns,
                "mapping": mapping,
            },
        )

    def reset_index(self, drop=False) -> FederatedDataFrame:
        """Resets the index, e.g., after a groupby operation, similar to pandas
        `reset_index`.
        The following arguments from pandas implementation are not supported:
        `level`, `inplace`, `col_level`, `col_fill`, `allow_duplicates`, `names`

        Example:
            Assume the dummy data for 'data_cloudnode' looks like this:
            ```
               patient_id  age  weight
            0           1   77      55
            1           2   88      83
            2           3   93      60
            3           4   18      72
            df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode')
            df1 = df.reset_index()
            df1.preprocess_on_dummy()
            ```
            returns
            ```
               index  Unnamed: 0  patient_id  age  weight
            0      0           0           1   77      55
            1      1           1           2   88      83
            2      2           2           3   93      60
            3      3           3           4   18      72
            ```

            ```
            df2 = df.reset_index(drop=True)
            df2.preprocess_on_dummy()
            ```
            returns
            ```
               Unnamed: 0  patient_id  age  weight
            0           0           1   77      55
            1           1           2   88      83
            2           2           3   93      60
            3           3           4   18      72
            ```

        Args:
            drop: If true, do not try to insert index into the data columns.
                This resets the index to the default integer index.
                Defaults to False.

        Returns:
            new instance of the current object with updated graph.

        """
        return self._add_operation_to_graph(
            command=NodeCommands.reset_index.name, args={"drop": drop}
        )

    def transform_columns(self, transformation: pandas.DataFrame) -> FederatedDataFrame:
        """
        Transform columns of a FederatedDataFrame using a pandas DataFrame as
        Transformation Matrix.
        The DataFrame index must correspond to the columns of the original
        FederatedDataFrame. The transformation is applied row-wise, i.e. each row is
        transformed to a subspace of the original feature space defined by the columns
        of the original FederatedDataFrame.

        Args:
            column_transformations: DataFrame with the same index as the columns of the
                original FederatedDataFrame. The DataFrame must have the same number of
                rows as the original FederatedDataFrame has columns.

        Returns:
            new instance of the current object with updated graph.

        """
        return self._add_operation_to_graph(
            command=NodeCommands.transform_columns.name,
            args={"transformation": transformation.to_dict()},
        )

    ######################################################################################
    # graph visualization, import and export
    ######################################################################################
    def display_graph(self):
        """
        Convert DiGraph from networkx into pydot and output SVG

        Returns: SVG content

        """
        graph_visualizer = DiGraphVisualizer()
        return graph_visualizer.create_svg(
            graph=self._graph,
        )

    def save_graph_as_image(
        self,
        filepath: str,
        image_format: str = "svg",
    ):
        """
        Convert DiGraph from networkx into pydot and save SVG
        Args:
            filepath: path where to save an image on the disk
            image_format: image format to be specified,
                supported formats are taken from pydot library

        """
        DiGraphManager.save_graph_as_image(
            graph=self._graph,
            filepath=filepath,
            img_format=image_format,
        )

    def export(self) -> str:
        """
        Export FederatedDataFrame object as JSON which can be then imported when needed

        Example:
            ```
            df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode')
            df_json = df.export()
            # store df_json and later:
            df_imported = FederatedDataFrame(data_source=df_json)
            # go on using df_imported as you would use df
            ```

        Returns:
            JSON-like string containing graph and node uuid
        """
        return DiGraphManager.export_graph(
            graph=self._graph,
            node_uuid=self._uuid,
        )

    def _import_graph(
        self,
        graph_json: str,
    ):
        """
        Imports JSON content applying properties to the current instance
        Args:
            graph_json: JSON-like string containing graph and node uuid

        """
        if isinstance(graph_json, str):
            self.__nx_graph, node_uuid = DiGraphManager.import_graph(
                graph_json=graph_json,
            )
            self.__uuid_instance = NodeUUID(initial_uuid=node_uuid)
        else:
            raise TransformationsInputTypeException(
                function_name=self._import_graph.__name__,
                argument_name="graph_json",
                argument_type=type(graph_json),
            )

    ######################################################################################
    # graph analytics
    ######################################################################################
    @staticmethod
    def _get_head_nodes_ids(graph):
        return [n for n, d in graph.in_degree() if d == 0]

    def _get_datasets_names(self):
        """Helper for flows.py's _federated_dataframe_into_preprocessing_step function:
        return RemoteData objects and their ids to prepare the preprocessing step.
        Whenever the FederatedDataFrame was initialized with a RemoteData object, we
        return the same object, which may include user's privacy settings for testing."""
        head_nodes_ids = self._get_head_nodes_ids(self.__nx_graph)
        datasets = list()
        data_names = list()
        for head_node_id in head_nodes_ids:
            head_node = self.__nx_graph.nodes.get(head_node_id)
            node_command = head_node.get("node_command")
            node_command_kwargs = head_node.get("node_command_kwargs")
            if node_command and "read" in node_command and node_command_kwargs:
                dataset_id = node_command_kwargs.get("data_source")
                if dataset_id:
                    if self.remoteData is not None and self.remoteData.id == dataset_id:
                        datasets.append(self.remoteData)
                    else:
                        datasets.append(RemoteData(dataset_id))
                    data_names.append(dataset_id)
        return datasets, data_names

    def _get_unique_remote_functions_or_raise_exception(self):
        """
        Get all remote functions which are used in the computational graph
        Returns: set of remote functions

        """
        nodes_commands = DiGraphManager.get_nodes_commands(
            graph=self._graph,
        )
        nodes_remote_functions = set()
        for nodes_command in nodes_commands:
            try:
                nodes_remote_function = NodeCommands[nodes_command].remote_function
            except KeyError:
                raise TransformationsModuleCommandNotFoundException(
                    command=nodes_command,
                )
            nodes_remote_functions.add(nodes_remote_function)
        return nodes_remote_functions

    ######################################################################################
    # extract remote functions from the nodes and run them
    ######################################################################################
    def _get_filepath_for_reading(
        self,
        data_source_from_command: str,
        filepaths: Optional[Dict],
        expected_input_format: InputFormat,
        reading_from_data_source_allowed: bool,
    ) -> str:
        """Helper function for overwriting the data source given during the object's
        init with a local file (that was passed to the .run method)
        or a dummy data path if the data source is a remote data id.
        Args:
            data_source_from_command: what the FederatedDataFrame was initialized with
            filepaths: optional dictionary overwriting data sources at runtime,
                used both for testing and from within flows
            expected_input_format: to check whether the given data source is a
                file already, or whether to attempt using the dummy data from
                a respective remote data object
            reading_from_data_source_allowed: If True, DummyData can be loaded from an
                external service. This is possible when a user runs a
                FederatedDataFrame locally. If False, no DummyData will be loaded from an
                external service. We need this setting when FederatedDataFrame is
                re-played in the encapsulated environment of a Data Custodian.
        Raises:
            TransformationDataUnavailableException if the data source is not a path
                and getting a corresponding RemoteData object failed
        """
        if filepaths is not None and data_source_from_command in filepaths:
            data_source = filepaths[data_source_from_command]
        else:
            if not reading_from_data_source_allowed:
                raise TransformationsInvalidSourceDataException(data_source_from_command)
            else:
                data_source = data_source_from_command
        # check if it is a path already
        is_path = False
        try:
            file_extension = self._parse_file_extension(
                filepath_or_filename=data_source, raise_warning=True
            )
            is_path = file_extension == expected_input_format.value
        except TransformationsFileExtensionNotDefinedWarning:
            pass
        except TransformationsFileExtensionNotSupportedException:
            pass

        # try to parse into RemoteData, if possible
        if not is_path and reading_from_data_source_allowed:
            # try to save time to connect to apheris client by caching
            if (
                data_source in self._remote_data_to_path_cache
                and isinstance(self._remote_data_to_path_cache[data_source], str)
                and Path(self._remote_data_to_path_cache[data_source]).exists()
            ):
                filepath = self._remote_data_to_path_cache[data_source]
            else:
                try:
                    ds = RemoteData(data_source)
                    filepath = ds.dummy_data_path
                    self._remote_data_to_path_cache[ds.id] = filepath
                except ObjectNotFound:
                    # not a string referring to a RemoteData object
                    self._remote_data_to_path_cache.pop(data_source, None)
                    raise TransformationDataUnavailableException(data_source)
        else:
            filepath = data_source
        return filepath

    def preprocess_on_dummy(self) -> pandas.DataFrame:
        """
        Execute computations "recorded" inside the FederatedDataFrame object
        on the dummy data attached to the RemoteData object used during initialization.

        If no dummy data is available, this method will fail. If you have data for
        testing stored on your local machine, please use `preprocess_on_files`
        instead.

        Example:
            ```
            df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode'))
            df["new_weight"] = df["weight"] + 100

            # executes the addition on the dummy data of 'data_cloudnode'
            df.preprocess_on_dummy()

            # the resulting dataframe is equivalent to:
            df_raw = pd.read_csv(
                apheris_auth.RemoteData('data_cloudnode').dummy_data_path
            )
            df_raw["new_weight"] = df_raw["weight"] + 100
            ```

        Returns:
            resulting pandas.DataFrame after preprocessing has been applied to dummy
            data.
        """

        return self._run(filepaths=None, reading_from_data_source_allowed=True)

    def preprocess_on_files(self, filepaths: Dict[str, str]) -> pandas.DataFrame:
        """
        Execute computations "recorded" inside the FederatedDataFrame object
        on local data.

        Args:
            filepaths: dictionary to overwrite RemoteData used during
                FederatedDataFrame intitialization with other data sources from your
                local machine. Keys are expected to be RemoteData ids,
                values are expected to be file paths.

        Example:
            ```
            df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode'))
            df["new_weight"] = df["weight"] + 100
            df.preprocess_on_files({'data_cloudnode':
                                    'myDirectory/local/replacement_data.csv'})

            # the resulting dataframe is equivalent to:
            df_raw = pd.read_csv('myDirectory/local/replacement_data.csv')
            df_raw["new_weight"] = df_raw["weight"] + 100
            ```

            Note that in case the FederatedDataFrame merges multiple RemoteData objects
            and you don't specify all their ids in the filepaths, we use dummy data for
            all "missing" ids (if available, otherwise, an exception is raised).

        Returns:
            resulting pandas.DataFrame after preprocessing has been applied to given file

        """
        return self._run(filepaths=filepaths, reading_from_data_source_allowed=True)

    def _run(
        self, filepaths: Dict[str, str] = None, reading_from_data_source_allowed=False
    ):
        """
        Execute computations "recorded" inside the FederatedDataFrame object
        on actual data.
        Args:
            filepaths: optionally overwrite data used during FederatedDataFrame
                intitialization with other data sources.
            reading_from_data_source_allowed: If True, DummyData can be loaded from an
                external service. This is possible when a user runs a
                FederatedDataFrame locally. If False, no DummyData will be loaded from an
                external service. We need this setting when FederatedDataFrame is
                re-played in the encapsulated environment of a Data Custodian.

        When using the FederatedDataFrame object in a remote computation,
        the computation internally will ensure to run on real data
        using this function using the filepaths
        """

        graph = copy.deepcopy(self.__nx_graph)
        fulfilled_dependencies = set()
        known_commands = [c.name for c in NodeCommands]

        for _ in range(graph.number_of_nodes()):  # This is to avoid an infinite loop
            for key, content in graph.nodes.items():
                dependencies = [x for x in graph.predecessors(key)]
                if key in fulfilled_dependencies:
                    # We have already computed this node
                    continue

                elif not set(dependencies).issubset(fulfilled_dependencies):
                    # We cannot compute this node because the dependencies are not
                    # fulfilled
                    continue
                else:
                    command = content.get("node_command")
                    if command not in known_commands:
                        raise TransformationsUnknownCommandException(
                            function_name=command,
                        )
                    command_kwargs = content.get("node_command_kwargs", dict())

                    # All dependencies are fulfilled.
                    command_enum = NodeCommands[command]
                    args, kwargs = list(), dict()
                    if command_enum == NodeCommands.read_csv:
                        data_source = command_kwargs["data_source"]
                        filepath = self._get_filepath_for_reading(
                            data_source,
                            filepaths,
                            InputFormat.CSV,
                            reading_from_data_source_allowed,
                        )
                        args = [filepath]
                    elif command_enum == NodeCommands.read_zip:
                        data_source = command_kwargs["data_source"]
                        zip_filepath = self._get_filepath_for_reading(
                            data_source,
                            filepaths,
                            InputFormat.ZIP,
                            reading_from_data_source_allowed,
                        )
                        single_file_name = command_kwargs.get("read_args").get("filename")
                        args = [zip_filepath, single_file_name]
                    elif command_enum == NodeCommands.read_parquet:
                        data_source = command_kwargs["data_source"]
                        filepath = self._get_filepath_for_reading(
                            data_source,
                            filepaths,
                            InputFormat.PARQUET,
                            reading_from_data_source_allowed,
                        )
                        args = [filepath]
                    elif command_enum == NodeCommands.setitem:
                        if "column_to_add" in command_kwargs:
                            item = graph.nodes[command_kwargs["column_to_add"]]["result"]
                        elif "value_to_add" in command_kwargs:
                            item = command_kwargs["value_to_add"]
                        else:
                            raise TransformationsMissingArgumentWarning(
                                "None of the arguments column_to_add or value_to_add "
                                "were found, item is set to None."
                            )
                        kwargs = {
                            "table": graph.nodes[command_kwargs["table"]]["result"],
                            "item_to_add": item,
                            "index": command_kwargs["index"],
                        }
                    elif command_enum == NodeCommands.getitem:
                        kwargs = {
                            "column": command_kwargs["column"],
                            "df": graph.nodes[dependencies[0]]["result"],
                        }
                    elif command_enum == NodeCommands.getitem_at_index_table:
                        kwargs = {
                            "table": graph.nodes[command_kwargs["table"]]["result"],
                            "mask": graph.nodes[command_kwargs["index"]]["result"],
                        }
                    elif command_enum == NodeCommands.addition:
                        kwargs = {
                            "this": graph.nodes[command_kwargs["table"]]["result"],
                            "summand_column1": command_kwargs["summand_column1"],
                            "summand2": command_kwargs["summand2"],
                            "result_column": command_kwargs["result_column"],
                        }
                    elif command_enum == NodeCommands.negation:
                        kwargs = {
                            "table": graph.nodes[command_kwargs["table"]]["result"],
                            "column_to_negate": command_kwargs["column_to_negate"],
                            "result_column": command_kwargs["result_column"],
                        }
                    elif command_enum == NodeCommands.inv:
                        kwargs = {
                            "table": graph.nodes[command_kwargs["table"]]["result"],
                            "column_to_invert": command_kwargs["column_to_invert"],
                            "result_column": command_kwargs["result_column"],
                        }
                    elif command_enum == NodeCommands.subtraction:
                        kwargs = {
                            "this": graph.nodes[command_kwargs["table"]]["result"],
                            "left": command_kwargs["left"],
                            "right": command_kwargs["right"],
                            "result": command_kwargs["result"],
                        }
                    elif command_enum == NodeCommands.mult:
                        kwargs = {
                            "this": graph.nodes[command_kwargs["table"]]["result"],
                            "left": command_kwargs["left"],
                            "right": command_kwargs["right"],
                            "result": command_kwargs["result"],
                        }
                    elif command_enum == NodeCommands.div:
                        kwargs = {
                            "this": graph.nodes[command_kwargs["table"]]["result"],
                            "left": command_kwargs["left"],
                            "right": command_kwargs["right"],
                            "result": command_kwargs["result"],
                        }
                    elif command_enum == NodeCommands.compare_to_table:
                        kwargs = {
                            "left": graph.nodes[command_kwargs["left"]]["result"],
                            "right": graph.nodes[command_kwargs["right"]]["result"],
                            "comparison_type": command_kwargs["comparison_type"],
                        }
                    elif command_enum == NodeCommands.compare_to_value:
                        kwargs = {
                            "left": graph.nodes[command_kwargs["left"]]["result"],
                            "right": command_kwargs["right"],
                            "comparison_type": command_kwargs["comparison_type"],
                        }
                    elif command_enum == NodeCommands.to_datetime:
                        kwargs = command_kwargs["args"]
                        kwargs["table"] = graph.nodes[command_kwargs["table"]]["result"]
                        kwargs["column"] = command_kwargs["column"]
                        kwargs["result"] = command_kwargs["result"]
                    elif command_enum == NodeCommands.fillna_table:
                        kwargs = {
                            "table": graph.nodes[command_kwargs["table"]]["result"],
                            "value": graph.nodes[command_kwargs["value"]]["result"],
                        }
                    elif command_enum == NodeCommands.fillna:
                        kwargs = {
                            "table": graph.nodes[command_kwargs["table"]]["result"],
                            "value": command_kwargs["value"],
                            "column": command_kwargs["column"],
                            "result": command_kwargs["result"],
                        }
                    elif command_enum == NodeCommands.dropna:
                        kwargs = command_kwargs["args"]
                        kwargs["table"] = graph.nodes[command_kwargs["table"]]["result"]
                    elif command_enum == NodeCommands.isna:
                        kwargs = {
                            "table": graph.nodes[command_kwargs["table"]]["result"],
                            "column": command_kwargs["column"],
                            "result": command_kwargs["result"],
                        }
                    elif command_enum == NodeCommands.astype:
                        kwargs = {
                            "table": graph.nodes[command_kwargs["table"]]["result"],
                            "dtype": command_kwargs["dtype"],
                            "column": command_kwargs["column"],
                            "result": command_kwargs["result"],
                        }
                    elif command_enum == NodeCommands.str_contains:
                        kwargs = {
                            "table": graph.nodes[command_kwargs["table"]]["result"],
                            "pattern": command_kwargs["pattern"],
                        }
                    elif command_enum == NodeCommands.str_len:
                        kwargs = {
                            "table": graph.nodes[command_kwargs["table"]]["result"],
                        }
                    elif command_enum == NodeCommands.merge:
                        kwargs = {
                            "left": graph.nodes[command_kwargs["left"]]["result"],
                            "right": graph.nodes[command_kwargs["right"]]["result"],
                            "how": command_kwargs["how"],
                            "on": command_kwargs["on"],
                            "left_on": command_kwargs["left_on"],
                            "right_on": command_kwargs["right_on"],
                            "left_index": command_kwargs["left_index"],
                            "right_index": command_kwargs["right_index"],
                            "sort": command_kwargs["sort"],
                            "suffixes": command_kwargs["suffixes"],
                            "copy": command_kwargs["copy"],
                            "indicator": command_kwargs["indicator"],
                            "validate": command_kwargs["validate"],
                        }
                    elif command_enum == NodeCommands.concat:
                        kwargs = {
                            "table1": graph.nodes[command_kwargs.pop("table1")]["result"],
                            "table2": graph.nodes[command_kwargs.pop("table2")]["result"],
                        }
                        kwargs.update(command_kwargs)
                    elif command_enum == NodeCommands.rename:
                        kwargs = {
                            "table": graph.nodes[dependencies[0]]["result"],
                            "mapping": command_kwargs["mapping"],
                        }
                    elif command_enum == NodeCommands.drop_column:
                        kwargs = {
                            "table": graph.nodes[dependencies[0]]["result"],
                            "column": command_kwargs["column"],
                        }
                    elif command_enum == NodeCommands.add_table:
                        kwargs = {
                            "summand1": graph.nodes[command_kwargs["summand1"]]["result"],
                            "summand2": graph.nodes[command_kwargs["summand2"]]["result"],
                        }
                    elif command_enum == NodeCommands.add_number:
                        kwargs = {
                            "summand1": graph.nodes[command_kwargs["summand1"]]["result"],
                            "summand2": command_kwargs["summand2"],
                        }
                    elif command_enum in [
                        NodeCommands.divide,
                        NodeCommands.divide_by_constant,
                    ]:
                        kwargs = {
                            "dividend": graph.nodes[command_kwargs["dividend"]]["result"],
                        }
                        if command_enum == NodeCommands.divide:
                            kwargs["divisor"] = graph.nodes[command_kwargs["divisor"]][
                                "result"
                            ]
                        else:
                            kwargs["divisor"] = command_kwargs["divisor"]
                    elif command_enum in [
                        NodeCommands.multiply,
                        NodeCommands.multiply_by_constant,
                    ]:
                        kwargs = {
                            "multiplicand": graph.nodes[command_kwargs["multiplicand"]][
                                "result"
                            ],
                        }
                        if command_enum == NodeCommands.multiply:
                            kwargs["multiplier"] = graph.nodes[
                                command_kwargs["multiplier"]
                            ]["result"]
                        else:
                            kwargs["multiplier"] = command_kwargs["multiplier"]
                    elif command_enum in [
                        NodeCommands.logical_conjunction_table,
                        NodeCommands.logical_conjunction_number,
                    ]:
                        kwargs = {
                            "left": graph.nodes[command_kwargs["left"]]["result"],
                            "right": graph.nodes[command_kwargs["right"]]["result"],
                            "conjunction_type": command_kwargs["conjunction_type"],
                        }
                    elif command_enum == NodeCommands.sort_values:
                        kwargs = command_kwargs["args"]
                        kwargs["table"] = graph.nodes[command_kwargs["table"]]["result"]
                    elif command_enum == NodeCommands.groupby:
                        kwargs = command_kwargs["args"]
                        kwargs["table"] = graph.nodes[command_kwargs["table"]]["result"]
                    elif command_enum == NodeCommands.first:
                        kwargs = {
                            "table": graph.nodes[command_kwargs["table"]]["result"],
                        }
                    elif command_enum == NodeCommands.size:
                        kwargs = {
                            "table": graph.nodes[command_kwargs["table"]]["result"],
                        }
                    elif command_enum == NodeCommands.last:
                        kwargs = {
                            "table": graph.nodes[command_kwargs["table"]]["result"],
                        }
                    elif command_enum == NodeCommands.mean:
                        kwargs = {
                            "table": graph.nodes[command_kwargs["table"]]["result"],
                        }
                    elif command_enum == NodeCommands.sum:
                        kwargs = {
                            "table": graph.nodes[command_kwargs["table"]]["result"],
                        }
                    elif command_enum == NodeCommands.cumsum:
                        kwargs = {
                            "table": graph.nodes[command_kwargs["table"]]["result"],
                        }
                    elif command_enum == NodeCommands.count:
                        kwargs = {
                            "table": graph.nodes[command_kwargs["table"]]["result"],
                        }
                    elif command_enum == NodeCommands.diff:
                        kwargs = {
                            "table": graph.nodes[command_kwargs["table"]]["result"],
                            "periods": command_kwargs["args"]["periods"],
                            "axis": command_kwargs["args"]["axis"],
                        }
                    elif command_enum == NodeCommands.shift:
                        kwargs = {
                            "table": graph.nodes[command_kwargs["table"]]["result"],
                            "periods": command_kwargs["args"]["periods"],
                            "freq": command_kwargs["args"]["freq"],
                            "axis": command_kwargs["args"]["axis"],
                            "fill_value": command_kwargs["args"]["fill_value"],
                        }
                    elif command_enum == NodeCommands.rank:
                        kwargs = {
                            "table": graph.nodes[command_kwargs["table"]]["result"],
                            "method": command_kwargs["args"]["method"],
                            "ascending": command_kwargs["args"]["ascending"],
                            "na_option": command_kwargs["args"]["na_option"],
                            "pct": command_kwargs["args"]["pct"],
                            "axis": command_kwargs["args"]["axis"],
                        }
                    elif command_enum == NodeCommands.isin:
                        if "iterable_values" in command_kwargs:
                            # iterable mode:
                            kwargs = {
                                "table": graph.nodes[command_kwargs["table"]]["result"],
                                "values": command_kwargs["iterable_values"],
                            }
                        else:
                            # table mode
                            kwargs = {
                                "table": graph.nodes[command_kwargs["table"]]["result"],
                                "values": graph.nodes[command_kwargs["values"]]["result"],
                            }
                    elif command_enum == NodeCommands.drop_duplicates:
                        kwargs = command_kwargs["args"]
                        kwargs["table"] = graph.nodes[command_kwargs["table"]]["result"]
                    elif command_enum == NodeCommands.reset_index:
                        kwargs = command_kwargs["args"]
                        kwargs["table"] = graph.nodes[command_kwargs["table"]]["result"]
                    elif command_enum in [
                        NodeCommands.loc_setter,
                        NodeCommands.loc_getter,
                    ]:
                        other_srcs_keys = command_kwargs.get("other_srcs_keys", list())
                        index_mask = command_kwargs["index_mask"]
                        if "index_mask" in other_srcs_keys:
                            index_mask = graph.nodes[index_mask]["result"]
                        kwargs = {
                            "table": graph.nodes[command_kwargs["table"]]["result"],
                            "index_mask": index_mask,
                            "columns": command_kwargs["columns"],
                        }
                        if command_enum == NodeCommands.loc_setter:
                            values = command_kwargs["values"]
                            if "values" in other_srcs_keys:
                                values = graph.nodes[values]["result"]
                            kwargs["values"] = values
                    elif command == NodeCommands.prepare_sankey_plot:
                        kwargs = {
                            "table": graph.nodes[command_kwargs["table"]]["result"],
                            "time_col": command_kwargs["time_col"],
                            "group_col": command_kwargs["group_col"],
                            "observable_col": command_kwargs["observable_col"],
                        }
                    elif command_enum == NodeCommands.rolling:
                        kwargs = command_kwargs["args"]
                        kwargs["table"] = graph.nodes[command_kwargs["table"]]["result"]
                    elif command_enum == NodeCommands.rolling_sum:
                        kwargs = {}
                        kwargs["table"] = graph.nodes[command_kwargs["table"]]["result"]
                    elif command_enum == NodeCommands.rolling_mean:
                        kwargs = {}
                        kwargs["table"] = graph.nodes[command_kwargs["table"]]["result"]
                    elif command_enum == NodeCommands.charlson_comorbidities:
                        kwargs = command_kwargs["args"]
                        kwargs["table"] = graph.nodes[command_kwargs["table"]]["result"]
                    elif command_enum == NodeCommands.charlson_comorbidity_score:
                        kwargs = command_kwargs["args"]
                        kwargs["table"] = graph.nodes[command_kwargs["table"]]["result"]
                    elif command_enum == NodeCommands.transform_columns:
                        kwargs = command_kwargs["args"]
                        kwargs["table"] = graph.nodes[command_kwargs["table"]]["result"]
                    elif command_enum == NodeCommands.sample:
                        kwargs = command_kwargs["args"]
                        kwargs["table"] = graph.nodes[command_kwargs["table"]]["result"]
                    else:
                        # ex.: NodeCommands.neg, NodeCommands.datetime_like_properties
                        kwargs = command_kwargs
                        table_ref = command_kwargs.get("table")
                        if table_ref:
                            kwargs["table"] = graph.nodes[table_ref]["result"]
                    if args or kwargs:
                        graph.nodes[key]["result"] = command_enum.remote_function(
                            *args, **kwargs
                        )
                    fulfilled_dependencies.add(key)
        df_final = graph.nodes[self._uuid]["result"]
        if df_final is None:
            raise TransformationsFailedExecutionException()
        if isinstance(df_final, DataFrameGroupBy):
            raise TransformationsInvalidGraphException(
                reason="groupby was found as the last operation",
                do_that="define an aggregation after groupby",
            )
        return df_final

__add__(other) 🔗

Arithmetic operator, which adds a constant value or a single column FederatedDataFrame to a single column FederatedDataFrame. This operator is useful only in combination with setitem. In a privacy preserving mode use the add function instead.

Example

Assume the dummy data for 'data_cloudnode' looks like this:

    patient_id  age  weight
0           1   77      55
1           2   88      60
2           3   93      83
df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode')
df["new_weight"] = df["weight"] + 100
df.preprocess_on_dummy()
returns
   patient_id  age  weight  new_weight
0           1   77      55         155
1           2   88      60         160
2           3   93      83         183

df["new_weight"] = df["weight"] + df["age"]
returns
   patient_id  age  weight  new_weight
0           1   77      55         132
1           2   88      60         148
2           3   93      83         176

Parameters:

Name Type Description Default
other Union[ALL_TYPES]

constant value or a single column FederatedDataFrame to add.

required

Returns:

Type Description
FederatedDataFrame

new instance of the current object with updated graph.

Source code in .env/lib/python3.10/site-packages/apheris_stats/simple_stats/_internal/datatools/transformations/dataframe.py
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
def __add__(
    self,
    other: Union[ALL_TYPES],
) -> FederatedDataFrame:
    """
    Arithmetic operator, which adds a constant value or a single column
    FederatedDataFrame to a single column FederatedDataFrame. This operator is
    useful only in combination with setitem. In a privacy preserving mode use
    the `add` function instead.

    Example:
        Assume the dummy data for 'data_cloudnode' looks like this:
        ```
            patient_id  age  weight
        0           1   77      55
        1           2   88      60
        2           3   93      83
        df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode')
        df["new_weight"] = df["weight"] + 100
        df.preprocess_on_dummy()
        ```
        returns
        ```
           patient_id  age  weight  new_weight
        0           1   77      55         155
        1           2   88      60         160
        2           3   93      83         183
        ```

        ```
        df["new_weight"] = df["weight"] + df["age"]
        ```
        returns
        ```
           patient_id  age  weight  new_weight
        0           1   77      55         132
        1           2   88      60         148
        2           3   93      83         176
        ```


    Args:
        other: constant value or a single column FederatedDataFrame to add.

    Returns:
        new instance of the current object with updated graph.

    """
    if isinstance(other, FederatedDataFrame):
        # We want to add two columns
        return self._add_graph_dst_node_with_multiple_edges(
            node_label="Sum",
            other_srcs=other,
            node_command=NodeCommands.add_table.name,
            node_command_src_key="summand1",
            node_command_other_srcs_keys="summand2",
        )
    elif isinstance(other, BASIC_TYPES):
        return self._add_graph_dst_node_with_edge(
            node_label=f"Add a value '{other}'",
            node_command=NodeCommands.add_number.name,
            node_command_src_key="summand1",
            node_command_kwargs={
                "summand2": other,
            },
        )
    else:
        raise TransformationsOperationArgumentTypeNotAllowedException(
            function_name=self.__add__.__name__,
            argument_name="other",
            argument_type=type(other),
            supported_argument_types=list(BASIC_TYPES + tuple([FederatedDataFrame])),
        )

__and__(other) 🔗

Logical operator, which conjuncts values of a single column FederatedDataFrame with a constant or another single column FederatedDataFrame.

Example

Assume the dummy data for 'data_cloudnode' looks like this:

   patient_id  age  death  infected
0           1   77      1         1
1           2   88      0         1
2           3   40      1         0
df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode')
df = df["death"] & df["infected"]
df.preprocess_on_dummy()
returns
0    1
1    0
2    0

Args: other: constant value or another FederatedDataFrame to logically conjunct

Returns:

Type Description
FederatedDataFrame

new instance of the current object with updated graph.

Source code in .env/lib/python3.10/site-packages/apheris_stats/simple_stats/_internal/datatools/transformations/dataframe.py
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
def __and__(self, other: Union[FederatedDataFrame, bool, int]) -> FederatedDataFrame:
    """
    Logical operator, which conjuncts values of a single column
    FederatedDataFrame with a constant or another single column
    FederatedDataFrame.

    Example:
        Assume the dummy data for 'data_cloudnode' looks like this:
        ```
           patient_id  age  death  infected
        0           1   77      1         1
        1           2   88      0         1
        2           3   40      1         0
        df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode')
        df = df["death"] & df["infected"]
        df.preprocess_on_dummy()
        ```
        returns
        ```
        0    1
        1    0
        2    0
        ```
    Args:
        other: constant value or another FederatedDataFrame to logically conjunct

    Returns:
        new instance of the current object with updated graph.

    """
    if isinstance(other, FederatedDataFrame):
        # We want to and-conjunct two columns
        return self._add_graph_dst_node_with_multiple_edges(
            node_label="And",
            other_srcs=other,
            node_command=NodeCommands.logical_conjunction_table.name,
            node_command_src_key="left",
            node_command_other_srcs_keys="right",
            node_command_kwargs={"conjunction_type": "and"},
        )
    elif isinstance(other, (bool, int)):
        return self._add_graph_dst_node_with_edge(
            node_label=f"And '{other}'",
            node_command=NodeCommands.logical_conjunction_number.name,
            node_command_src_key="left",
            node_command_kwargs={"right": other, "conjunction_type": "and"},
        )
    else:
        raise TransformationsOperationArgumentTypeNotAllowedException(
            function_name=self.__and__.__name__,
            argument_name="other",
            argument_type=type(other),
            supported_argument_types=[FederatedDataFrame, bool],
        )

__eq__(other) 🔗

Compare a single-column FederatedDataFrame with a constant using the operator '=='

Example

Assume the dummy data for 'data_cloudnode' looks like this:

   patient_id  age  weight
0           1   77      55
1           2   88      60
2           3   40      40

df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode')
df = df["age"] == df["weight"]
df.preprocess_on_dummy()

returns

0    False
1    False
2     True

Parameters:

Name Type Description Default
other

FederatedDataFrame or value to compare with

required

Returns:

Type Description
FederatedDataFrame

single column FederatedDataFrame with computation graph resulting in a

FederatedDataFrame

boolean Series.

Source code in .env/lib/python3.10/site-packages/apheris_stats/simple_stats/_internal/datatools/transformations/dataframe.py
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
def __eq__(self, other) -> FederatedDataFrame:
    """
    Compare a single-column FederatedDataFrame with a constant using the operator '=='

    Example:
        Assume the dummy data for 'data_cloudnode' looks like this:
        ```
           patient_id  age  weight
        0           1   77      55
        1           2   88      60
        2           3   40      40

        df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode')
        df = df["age"] == df["weight"]
        df.preprocess_on_dummy()
        ```

        returns
        ```
        0    False
        1    False
        2     True
        ```

    Args:
        other: FederatedDataFrame or value to compare with

    Returns:
        single column FederatedDataFrame with computation graph resulting in a
        boolean Series.

    """
    return self._comparison(other, ComparisonType.EQUAL_TO)

__ge__(other) 🔗

Compare a single-column FederatedDataFrame with a constant using the operator '>='

Example

Assume the dummy data for 'data_cloudnode' looks like this:

   patient_id  age  weight
0           1   77      55
1           2   88      60
2           3   40      40

df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode')
df = df["age"] >= df["weight"]
df.preprocess_on_dummy()

returns

0    True
1    True
2    True

Parameters:

Name Type Description Default
other

FederatedDataFrame or value to compare with

required

Returns:

Type Description
FederatedDataFrame

single column FederatedDataFrame with computation graph resulting in a

FederatedDataFrame

boolean Series.

Source code in .env/lib/python3.10/site-packages/apheris_stats/simple_stats/_internal/datatools/transformations/dataframe.py
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
def __ge__(self, other) -> FederatedDataFrame:
    """
    Compare a single-column FederatedDataFrame with a constant using the operator '>='

    Example:
        Assume the dummy data for 'data_cloudnode' looks like this:
        ```
           patient_id  age  weight
        0           1   77      55
        1           2   88      60
        2           3   40      40

        df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode')
        df = df["age"] >= df["weight"]
        df.preprocess_on_dummy()
        ```

        returns
        ```
        0    True
        1    True
        2    True
        ```

    Args:
        other: FederatedDataFrame or value to compare with

    Returns:
        single column FederatedDataFrame with computation graph resulting in a
        boolean Series.

    """
    return self._comparison(other, ComparisonType.GREATER_THAN_OR_EQUAL_TO)

__getitem__(key) 🔗

Example

Assume the dummy data for 'data_cloudnode' looks like this:

    patient_id  age  weight
0           1   77      55
1           2   88      60
2           3   93      83

df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode')
df = df["weight"]
df.preprocess_on_dummy()

results in

   weight
0    55
1    60
2    83

Args: key: column index or name or a boolean valued FederatedDataFrame as index mask.

Returns:

Type Description
'FederatedDataFrame'

new instance of the current object with updated graph. If the key was a

'FederatedDataFrame'

column identifier, the computation graph results in a single-column

'FederatedDataFrame'

FederatedDataFrame. If the key was an index mask the resulting computation

'FederatedDataFrame'

graph will produce a filtered FederatedDataFrame.

Source code in .env/lib/python3.10/site-packages/apheris_stats/simple_stats/_internal/datatools/transformations/dataframe.py
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
def __getitem__(
    self,
    key: Union[str, int, "FederatedDataFrame"],
) -> "FederatedDataFrame":
    """

    Example:
        Assume the dummy data for 'data_cloudnode' looks like this:
        ```
            patient_id  age  weight
        0           1   77      55
        1           2   88      60
        2           3   93      83

        df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode')
        df = df["weight"]
        df.preprocess_on_dummy()
        ```

        results in
        ```
           weight
        0    55
        1    60
        2    83
        ```
    Args:
        key: column index or name or a boolean valued FederatedDataFrame as index
        mask.

    Returns:
        new instance of the current object with updated graph. If the key was a
        column identifier, the computation graph results in a single-column
        FederatedDataFrame. If the key was an index mask the resulting computation
        graph will produce a filtered FederatedDataFrame.
    """
    if isinstance(key, (str, int)):
        # We want to get a column
        return self._add_graph_dst_node_with_edge(
            node_label=f"Get column '{key}'",
            node_command=NodeCommands.getitem.name,
            node_command_kwargs={
                "column": key,
            },
        )
    elif isinstance(key, FederatedDataFrame):
        # We want to select rows w.r.t. index `key`
        return self._add_graph_dst_node_with_multiple_edges(
            node_label="Filter using index_mask",
            other_srcs=key,
            node_command=NodeCommands.getitem_at_index_table.name,
            node_command_src_key="table",
            node_command_other_srcs_keys="index",
            edges_labels={key._uuid: "index_mask"},
        )
    else:
        raise TransformationsInputTypeException(
            function_name=self.__getitem__.__name__,
            argument_name="key",
            argument_type=type(key),
        )

__gt__(other) 🔗

Compare a single-column FederatedDataFrame with a constant using the operator '>'

Example

Assume the dummy data for 'data_cloudnode' looks like this:

   patient_id  age  weight
0           1   77      55
1           2   88      60
2           3   40      50

df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode')
df = df["age"] > df["weight"]
df.preprocess_on_dummy()

returns

0     True
1     True
2    False

Parameters:

Name Type Description Default
other

FederatedDataFrame or value to compare with

required

Returns:

Type Description
FederatedDataFrame

single column FederatedDataFrame with computation graph resulting in a

FederatedDataFrame

boolean Series.

Source code in .env/lib/python3.10/site-packages/apheris_stats/simple_stats/_internal/datatools/transformations/dataframe.py
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
def __gt__(self, other) -> FederatedDataFrame:
    """
    Compare a single-column FederatedDataFrame with a constant using the operator '>'

    Example:
        Assume the dummy data for 'data_cloudnode' looks like this:
        ```
           patient_id  age  weight
        0           1   77      55
        1           2   88      60
        2           3   40      50

        df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode')
        df = df["age"] > df["weight"]
        df.preprocess_on_dummy()
        ```

        returns
        ```
        0     True
        1     True
        2    False
        ```

    Args:
        other: FederatedDataFrame or value to compare with

    Returns:
        single column FederatedDataFrame with computation graph resulting in a
        boolean Series.


    """
    return self._comparison(other, ComparisonType.GREATER_THAN)

__init__(data_source, read_format=None, filename_in_zip=None) 🔗

Create a new data object

Example
  • via RemoteData object (recommended): assume your remote data id is 'data-cloudnode':
        rd = apheris_auth.RemoteData('data-cloudnode')
        df = FederatedDataFrame(rd)
    
  • via RemoteData id: assume your remote data id is 'data-cloudnode':
    df = FederatedDataFrame('data-cloudnode')
    
  • optional: for remote data containing multiple files, choose which file to read:
    df = FederatedDataFrame(apheris_auth.RemoteData('data-cloudnode'),
        filename_in_zip='patients.csv')

Parameters:

Name Type Description Default
data_source Union[str, RemoteData]

remote id or RemoteData object or path to a data file or graph

required
read_format Union[str, InputFormat, None]

format of data source

None
filename_in_zip Union[str, None]

used for ZIP format to identify which file out of ZIP to take The argument is optional, but must be specified for ZIP format. If read_format is ZIP, the value of this argument is used to read one CSV.

None
Source code in .env/lib/python3.10/site-packages/apheris_stats/simple_stats/_internal/datatools/transformations/dataframe.py
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
def __init__(
    self,
    data_source: Union[str, RemoteData],
    read_format: Union[str, InputFormat, None] = None,
    filename_in_zip: Union[str, None] = None,
):
    """
    Create a new data object

    Example:
        * via RemoteData object (recommended):
        assume your remote data id is 'data-cloudnode':
        ```
            rd = apheris_auth.RemoteData('data-cloudnode')
            df = FederatedDataFrame(rd)
        ```

        * via RemoteData id: assume your remote data id is 'data-cloudnode':
        ```
        df = FederatedDataFrame('data-cloudnode')
        ```

        * optional: for remote data containing multiple files,
        choose which file to read:

        ```
            df = FederatedDataFrame(apheris_auth.RemoteData('data-cloudnode'),
                filename_in_zip='patients.csv')
        ```

    Args:
        data_source: remote id or RemoteData object or path to a  data file or graph
        JSON file
        read_format: format of data source
        filename_in_zip: used for ZIP format to identify which file out of ZIP to take
            The argument is optional, but must be specified for ZIP format.
            If read_format is ZIP, the value of this argument is used to read one CSV.

    """
    self.str = _StringAccessor(self)
    self.special = _SpecialAccessor(self)
    nc = NodeCommands.datetime_like_properties
    remote_function_attrs = nc.get_supported_values_for_remote_function_attr(
        remote_function_attr="datetime_like_property"
    )
    for remote_function_attr in remote_function_attrs:
        _DatetimeLikeAccessor.fill_in_dt_properties(remote_function_attr)
        self.dt = _DatetimeLikeAccessor(self)

    self.remoteData = None
    if isinstance(data_source, RemoteData):
        self.remoteData = data_source
        data_source = data_source.id
    try:
        self._import_graph(graph_json=data_source)
    except TransformationsInvalidJSONFormatException:
        self.__nx_graph = DiGraph()
        self.__uuid_instance = NodeUUID()
        if data_source:
            if not read_format and filename_in_zip:
                read_format = InputFormat.ZIP
            elif not read_format:
                read_format = self._parse_file_extension(
                    filepath_or_filename=data_source,
                )
            self._validate_if_read_format_supported(
                read_format=read_format,
            )
            self._validate_if_filename_for_zip_provided(
                read_format=read_format,
                filename_in_zip=filename_in_zip,
            )
            self._read_data(
                src_node_uuid=self._uuid,
                data_source=data_source,
                read_format=read_format,
                read_args={"filename": filename_in_zip},
            )
    # cache to save lookup of dummy data paths when user defines remote data ids
    self._remote_data_to_path_cache = {}

__invert__() 🔗

Logical operator, which inverts bool values (known as tilde in pandas, ~).

Example

Assume the dummy data for 'data_cloudnode' looks like this:

   patient_id  age  weight  death
0           1   77    55.0   True
1           2   88    60.0  False
2           3   23     NaN   True
df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode'))
df["survival"] = ~df["death"]
df.preprocess_on_dummy()
returns
   patient_id  age  weight  death  survival
0           1   77    55.0   True     False
1           2   88    60.0  False      True
2           3   23     NaN   True     False

Returns:

Type Description
FederatedDataFrame

new instance of the current object with updated graph.

Source code in .env/lib/python3.10/site-packages/apheris_stats/simple_stats/_internal/datatools/transformations/dataframe.py
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
def __invert__(self) -> FederatedDataFrame:
    """
    Logical operator, which inverts bool values (known as tilde in pandas, ~).

    Example:
        Assume the dummy data for 'data_cloudnode' looks like this:
        ```
           patient_id  age  weight  death
        0           1   77    55.0   True
        1           2   88    60.0  False
        2           3   23     NaN   True
        df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode'))
        df["survival"] = ~df["death"]
        df.preprocess_on_dummy()
        ```
        returns
        ```
           patient_id  age  weight  death  survival
        0           1   77    55.0   True     False
        1           2   88    60.0  False      True
        2           3   23     NaN   True     False
        ```

    Returns:
        new instance of the current object with updated graph.
    """
    return self._add_graph_dst_node_with_edge(
        node_label="~",
        node_command=NodeCommands.invert.name,
        node_command_src_key="table",
    )

__le__(other) 🔗

Compare a single-column FederatedDataFrame with a constant using the operator '<='

Example

Assume the dummy data for 'data_cloudnode' looks like this:

   patient_id  age  weight
0           1   77      55
1           2   88      60
2           3   40      40

df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode')
df = df["age"] <= df["weight"]
df.preprocess_on_dummy()

returns

0    False
1    False
2     True

Parameters:

Name Type Description Default
other

FederatedDataFrame or value to compare with

required

Returns:

Type Description
FederatedDataFrame

single column FederatedDataFrame with computation graph resulting in a

FederatedDataFrame

boolean Series.

Source code in .env/lib/python3.10/site-packages/apheris_stats/simple_stats/_internal/datatools/transformations/dataframe.py
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
def __le__(self, other) -> FederatedDataFrame:
    """
    Compare a single-column FederatedDataFrame with a constant using the operator '<='

    Example:
        Assume the dummy data for 'data_cloudnode' looks like this:
        ```
           patient_id  age  weight
        0           1   77      55
        1           2   88      60
        2           3   40      40

        df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode')
        df = df["age"] <= df["weight"]
        df.preprocess_on_dummy()
        ```

        returns
        ```
        0    False
        1    False
        2     True
        ```

    Args:
        other: FederatedDataFrame or value to compare with

    Returns:
        single column FederatedDataFrame with computation graph resulting in a
        boolean Series.

    """
    return self._comparison(other, ComparisonType.LESS_THAN_OR_EQUAL_TO)

__lt__(other) 🔗

Compare a single-column FederatedDataFrame with a constant using the operator '<' Example: Assume the dummy data for 'data_cloudnode' looks like this:

   patient_id  age  weight
0           1   77      55
1           2   88      60
2           3   40      50

df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode')
df = df["age"] < df["weight"]
df.preprocess_on_dummy()
returns
```
0    False
1    False
2     True
```

Parameters:

Name Type Description Default
other

FederatedDataFrame or value to compare with

required

Returns:

Type Description
FederatedDataFrame

single column FederatedDataFrame with computation graph resulting in a

FederatedDataFrame

boolean Series.

Source code in .env/lib/python3.10/site-packages/apheris_stats/simple_stats/_internal/datatools/transformations/dataframe.py
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
def __lt__(self, other) -> FederatedDataFrame:
    """
    Compare a single-column FederatedDataFrame with a constant using the operator '<'
    Example:
        Assume the dummy data for 'data_cloudnode' looks like this:
        ```
           patient_id  age  weight
        0           1   77      55
        1           2   88      60
        2           3   40      50

        df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode')
        df = df["age"] < df["weight"]
        df.preprocess_on_dummy()
        ```

        returns
        ```
        0    False
        1    False
        2     True
        ```

    Args:
        other: FederatedDataFrame or value to compare with

    Returns:
        single column FederatedDataFrame with computation graph resulting in a
        boolean Series.

    """
    return self._comparison(other, ComparisonType.LESS_THAN)

__mul__(other) 🔗

Arithmetic operator, which multiplies FederatedDataFrame by a constant or another FederatedDataFrame.

Example

Assume the dummy data for 'data_cloudnode' looks like this:

    patient_id  age  weight
0           1   77      55
1           2   88      60
2           3   93      83
df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode')
df["new_weight"] = df["weight"] * 2
df.preprocess_on_dummy()
returns
    patient_id  age  weight  new_weight
0           1   77      55         110
1           2   88      60         120
2           3   93      83         166

df["new_weight"] = df["weight"] * df["patient_id"]
returns
   patient_id  age  weight  new_weight
0           1   77      55          55
1           2   88      60         120
2           3   93      83         249

Parameters:

Name Type Description Default
other Union[FederatedDataFrame, int, float, bool]

constant value or another FederatedDataFrame to multiply by.

required

Returns:

Type Description
FederatedDataFrame

new instance of the current object with updated graph.

Source code in .env/lib/python3.10/site-packages/apheris_stats/simple_stats/_internal/datatools/transformations/dataframe.py
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
def __mul__(
    self,
    other: Union[(FederatedDataFrame, int, float, bool)],
) -> FederatedDataFrame:
    """
    Arithmetic operator, which multiplies FederatedDataFrame by a constant or
    another FederatedDataFrame.

    Example:
        Assume the dummy data for 'data_cloudnode' looks like this:
        ```
            patient_id  age  weight
        0           1   77      55
        1           2   88      60
        2           3   93      83
        df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode')
        df["new_weight"] = df["weight"] * 2
        df.preprocess_on_dummy()
        ```
        returns
        ```
            patient_id  age  weight  new_weight
        0           1   77      55         110
        1           2   88      60         120
        2           3   93      83         166
        ```

        ```
        df["new_weight"] = df["weight"] * df["patient_id"]
        ```
        returns
        ```
           patient_id  age  weight  new_weight
        0           1   77      55          55
        1           2   88      60         120
        2           3   93      83         249
        ```

    Args:
        other: constant value or another FederatedDataFrame to multiply by.

    Returns:
        new instance of the current object with updated graph.


    """
    if isinstance(other, FederatedDataFrame):
        # We want to add two columns
        return self._add_graph_dst_node_with_multiple_edges(
            node_label="multiplicand * multiplier",
            other_srcs=other,
            node_command=NodeCommands.multiply.name,
            node_command_src_key="multiplicand",
            node_command_other_srcs_keys="multiplier",
            edges_labels={other._uuid: "multiplier"},
        )
    elif isinstance(other, (int, float, bool)):
        return self._add_graph_dst_node_with_edge(
            node_label=f"multiplicand / {other}",
            node_command=NodeCommands.multiply_by_constant.name,
            node_command_src_key="multiplicand",
            node_command_kwargs={
                "multiplier": other,
            },
        )
    else:
        raise TransformationsOperationArgumentTypeNotAllowedException(
            function_name=self.__mul__.__name__,
            argument_name="other",
            argument_type=type(other),
            supported_argument_types=[FederatedDataFrame, int, float, bool],
        )

__ne__(other) 🔗

Compare a single-column FederatedDataFrame with a constant using the operator '!='

Example

Assume the dummy data for 'data_cloudnode' looks like this:

   patient_id  age  weight
0           1   77      55
1           2   88      60
2           3   40      40

df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode')
df = df["age"] != df["weight"]
df.preprocess_on_dummy()

returns

0     True
1     True
2    False

Parameters:

Name Type Description Default
other

FederatedDataFrame or value to compare with

required

Returns:

Type Description
FederatedDataFrame

single column FederatedDataFrame with computation graph resulting in a

FederatedDataFrame

boolean Series.

Source code in .env/lib/python3.10/site-packages/apheris_stats/simple_stats/_internal/datatools/transformations/dataframe.py
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
def __ne__(self, other) -> FederatedDataFrame:
    """
    Compare a single-column FederatedDataFrame with a constant using the operator '!='

    Example:
        Assume the dummy data for 'data_cloudnode' looks like this:
        ```
           patient_id  age  weight
        0           1   77      55
        1           2   88      60
        2           3   40      40

        df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode')
        df = df["age"] != df["weight"]
        df.preprocess_on_dummy()
        ```

        returns
        ```
        0     True
        1     True
        2    False
        ```

    Args:
        other: FederatedDataFrame or value to compare with

    Returns:
        single column FederatedDataFrame with computation graph resulting in a
        boolean Series.

    """
    return self._comparison(other, ComparisonType.NOT_EQUAL_TO)

__neg__() 🔗

Logical operator, which negates values of a single column FederatedDataFrame. This operator is useful only in combination with setitem. In a privacy preserving mode use the neg function instead.

Example

Assume the dummy data for 'data_cloudnode' looks like this:

    patient_id  age  weight
0           1   77      55
1           2   88      60
2           3   93      83
df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode')
df["neg_age"] = - df["age"]
df.preprocess_on_dummy()
returns
    patient_id  age  weight  neg_age
0           1   77      55      -77
1           2   88      60      -88
2           3   93      83      -93

Returns:

Type Description
FederatedDataFrame

new instance of the current object with updated graph.

Source code in .env/lib/python3.10/site-packages/apheris_stats/simple_stats/_internal/datatools/transformations/dataframe.py
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
def __neg__(self) -> FederatedDataFrame:
    """
    Logical operator, which negates values of a single column
    FederatedDataFrame. This operator is
    useful only in combination with setitem. In a privacy preserving mode use
    the `neg` function instead.

    Example:
        Assume the dummy data for 'data_cloudnode' looks like this:
        ```
            patient_id  age  weight
        0           1   77      55
        1           2   88      60
        2           3   93      83
        df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode')
        df["neg_age"] = - df["age"]
        df.preprocess_on_dummy()
        ```
        returns
        ```
            patient_id  age  weight  neg_age
        0           1   77      55      -77
        1           2   88      60      -88
        2           3   93      83      -93
        ```

    Returns:
        new instance of the current object with updated graph.

    """
    return self._add_graph_dst_node_with_edge(
        node_label="Negate",
        node_command=NodeCommands.neg.name,
        node_command_src_key="table",
    )

__or__(other) 🔗

Logical operator, which conjuncts values of a single column FederatedDataFrame with a constant or another single column FederatedDataFrame.

Example

Assume the dummy data for 'data_cloudnode' looks like this:

   patient_id  age  death  infected
0           1   77      1         1
1           2   88      0         1
2           3   40      1         0
df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode')
df = df["death"] | df["infected"]
df.preprocess_on_dummy()
returns
0    1
1    1
2    1

Parameters:

Name Type Description Default
other Union[FederatedDataFrame, bool, int]

constant value or another FederatedDataFrame to logically conjunct

required

Returns:

Type Description
FederatedDataFrame

new instance of the current object with updated graph.

Source code in .env/lib/python3.10/site-packages/apheris_stats/simple_stats/_internal/datatools/transformations/dataframe.py
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
def __or__(self, other: Union[FederatedDataFrame, bool, int]) -> FederatedDataFrame:
    """
    Logical operator, which conjuncts values of a single column
    FederatedDataFrame with a constant or another single column
    FederatedDataFrame.

    Example:
        Assume the dummy data for 'data_cloudnode' looks like this:
        ```
           patient_id  age  death  infected
        0           1   77      1         1
        1           2   88      0         1
        2           3   40      1         0
        df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode')
        df = df["death"] | df["infected"]
        df.preprocess_on_dummy()
        ```
        returns
        ```
        0    1
        1    1
        2    1
        ```

    Args:
        other: constant value or another FederatedDataFrame to logically conjunct

    Returns:
        new instance of the current object with updated graph.
    """
    if isinstance(other, FederatedDataFrame):
        # We want to or-conjunct two columns
        return self._add_graph_dst_node_with_multiple_edges(
            node_label="Or",
            other_srcs=other,
            node_command=NodeCommands.logical_conjunction_table.name,
            node_command_src_key="left",
            node_command_other_srcs_keys="right",
            node_command_kwargs={"conjunction_type": "or"},
        )
    elif isinstance(other, (bool, int)):
        return self._add_graph_dst_node_with_edge(
            node_label=f"Or '{other}'",
            node_command=NodeCommands.logical_conjunction_number.name,
            node_command_src_key="left",
            node_command_kwargs={"right": other, "conjunction_type": "or"},
        )
    else:
        raise TransformationsOperationArgumentTypeNotAllowedException(
            function_name=self.__or__.__name__,
            argument_name="other",
            argument_type=type(other),
            supported_argument_types=[FederatedDataFrame, bool],
        )

__radd__(other) 🔗

Arithmetic operator, which adds a constant value or a single column FederatedDataFrame to a single column FederatedDataFrame from right. This operator is useful only in combination with setitem. In a privacy preserving mode use the add function instead.

Example

Assume the dummy data for 'data_cloudnode' looks like this:

    patient_id  age  weight
0           1   77      55
1           2   88      60
2           3   93      83
df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode')
df["new_weight"] = 100 + df["weight"]
df.preprocess_on_dummy()
returns
   patient_id  age  weight  new_weight
0           1   77      55         155
1           2   88      60         160
2           3   93      83         183

Parameters:

Name Type Description Default
other

constant value or a single column FederatedDataFrame to add.

required

Returns:

Type Description
FederatedDataFrame

new instance of the current object with updated graph.

Source code in .env/lib/python3.10/site-packages/apheris_stats/simple_stats/_internal/datatools/transformations/dataframe.py
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
def __radd__(self, other) -> FederatedDataFrame:
    """
    Arithmetic operator, which adds a constant value or a single column
    FederatedDataFrame to a single column FederatedDataFrame from right. This operator
    is useful only in combination with setitem. In a privacy preserving mode use
    the `add` function instead.

    Example:
        Assume the dummy data for 'data_cloudnode' looks like this:
        ```
            patient_id  age  weight
        0           1   77      55
        1           2   88      60
        2           3   93      83
        df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode')
        df["new_weight"] = 100 + df["weight"]
        df.preprocess_on_dummy()
        ```
        returns
        ```
           patient_id  age  weight  new_weight
        0           1   77      55         155
        1           2   88      60         160
        2           3   93      83         183
        ```


    Args:
        other: constant value or a single column FederatedDataFrame to add.

    Returns:
        new instance of the current object with updated graph.
    """
    return self.__add__(other)

__rmul__(other) 🔗

Arithmetic operator, which multiplies FederatedDataFrame by a constant or another FederatedDataFrame.

Example

Assume the dummy data for 'data_cloudnode' looks like this:

    patient_id  age  weight
0           1   77      55
1           2   88      60
2           3   93      83
df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode')
df["new_weight"] = 2 * df["weight"] * 2
df.preprocess_on_dummy()
returns
    patient_id  age  weight  new_weight
0           1   77      55         110
1           2   88      60         120
2           3   93      83         166

Parameters:

Name Type Description Default
other Union[FederatedDataFrame, int, float, bool]

constant value or another FederatedDataFrame to multiply by.

required

Returns: new instance of the current object with updated graph.

Source code in .env/lib/python3.10/site-packages/apheris_stats/simple_stats/_internal/datatools/transformations/dataframe.py
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
def __rmul__(
    self,
    other: Union[(FederatedDataFrame, int, float, bool)],
) -> FederatedDataFrame:
    """
    Arithmetic operator, which multiplies FederatedDataFrame by a constant or
    another FederatedDataFrame.

    Example:
        Assume the dummy data for 'data_cloudnode' looks like this:
        ```
            patient_id  age  weight
        0           1   77      55
        1           2   88      60
        2           3   93      83
        df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode')
        df["new_weight"] = 2 * df["weight"] * 2
        df.preprocess_on_dummy()
        ```
        returns
        ```
            patient_id  age  weight  new_weight
        0           1   77      55         110
        1           2   88      60         120
        2           3   93      83         166
        ```

    Args:
        other: constant value or another FederatedDataFrame to multiply by.
    Returns:
        new instance of the current object with updated graph.
    """
    return self.__mul__(other=other)

__rsub__(other) 🔗

Arithmetic operator, which subtracts a single column FederatedDataFrame from a constant value or a single column FederatedDataFrame. This operator is useful only in combination with setitem. In a privacy preserving mode use the sub function instead.

Parameters:

Name Type Description Default
other

constant value or a single column FederatedDataFrame from which to

required

Returns:

Type Description
FederatedDataFrame

new instance of the current object with updated graph.

Example

Assume the dummy data for 'data_cloudnode' looks like this:

    patient_id  age  weight
0           1   77      55
1           2   88      60
2           3   93      83

df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode'))
df["new_weight"] = 100 - df["weight"]
df.preprocess_on_dummy()

returns

   patient_id  age  weight  new_weight
0           1   77      55         45
1           2   88      60         40
2           3   93      83         17
Source code in .env/lib/python3.10/site-packages/apheris_stats/simple_stats/_internal/datatools/transformations/dataframe.py
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
def __rsub__(self, other) -> FederatedDataFrame:
    """
    Arithmetic operator, which subtracts a single column FederatedDataFrame from a
    constant value or a single column FederatedDataFrame. This operator is
    useful only in combination with setitem. In a privacy preserving mode use
    the `sub` function instead.

    Args:
        other: constant value or a single column FederatedDataFrame from which to
        subtract.

    Returns:
        new instance of the current object with updated graph.

    Example:
        Assume the dummy data for 'data_cloudnode' looks like this:
        ```
            patient_id  age  weight
        0           1   77      55
        1           2   88      60
        2           3   93      83

        df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode'))
        df["new_weight"] = 100 - df["weight"]
        df.preprocess_on_dummy()
        ```

        returns
        ```
           patient_id  age  weight  new_weight
        0           1   77      55         45
        1           2   88      60         40
        2           3   93      83         17
        ```
    """

    return self.__neg__().__add__(other)

__setitem__(index, value) 🔗

Manipulates values of a columns or rows of a FederatedDataFrame. This operation does not return a copy of the FederatedDataFrame object, instead this operation is implemented inplace. That means, the computation graph within the FederatedDataFrame object is modified on the object level. This function is not available in a privacy fully preserving mode.

Example:

Assume the dummy data for 'data_cloudnode' looks like this:

```
    patient_id  age  weight
0           1   77      55
1           2   88      60
2           3   93      83

df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode')
df["new column"] = df["weight"]
df.preprocess_on_dummy()
```

results in
```
   patient_id  age  weight  new_column
0           1   77      55          55
1           2   88      60          60
2           3   93      83          83
```

Parameters:

Name Type Description Default
index Union[str, int]

column index or name or a boolean valued FederatedDataFrame as index

required
value Union[ALL_TYPES]

a constant value or a single column FederatedDataFrame

required
Source code in .env/lib/python3.10/site-packages/apheris_stats/simple_stats/_internal/datatools/transformations/dataframe.py
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
def __setitem__(
    self,
    index: Union[str, int],
    value: Union[ALL_TYPES],
):
    """
    Manipulates values of a columns or rows of a FederatedDataFrame. This
    operation does not return a copy of the FederatedDataFrame object,
    instead this operation is implemented inplace.
    That means, the computation graph within the FederatedDataFrame
    object is modified on the object level.
    This function is not available in a privacy fully preserving mode.

    Example:

        Assume the dummy data for 'data_cloudnode' looks like this:

        ```
            patient_id  age  weight
        0           1   77      55
        1           2   88      60
        2           3   93      83

        df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode')
        df["new column"] = df["weight"]
        df.preprocess_on_dummy()
        ```

        results in
        ```
           patient_id  age  weight  new_column
        0           1   77      55          55
        1           2   88      60          60
        2           3   93      83          83
        ```

    Args:
        index: column index or name or a boolean valued FederatedDataFrame as index
        mask.
        value: a constant value or a single column FederatedDataFrame
    """
    if isinstance(value, FederatedDataFrame):
        self._add_graph_dst_node_with_multiple_edges(
            node_label=f"Set column '{index}'",
            other_srcs=value,
            node_command=NodeCommands.setitem.name,
            node_command_src_key="table",
            node_command_other_srcs_keys="column_to_add",
            node_command_kwargs={
                "index": index,
            },
            create_a_copy=False,  # This is an inplace operation
        )
    elif isinstance(value, (str, int, float)):
        value_for_label = f"'{value}'" if isinstance(value, str) else value
        self._add_graph_dst_node_with_edge(
            node_label=f"Set column '{index}' = {value_for_label}",
            node_command=NodeCommands.setitem.name,
            node_command_src_key="table",
            node_command_kwargs={"index": index, "value_to_add": value},
            create_a_copy=False,  # This is an inplace operation
        )
    else:
        raise TransformationsOperationArgumentTypeNotAllowedException(
            function_name=NodeCommands.setitem.name,
            argument_name="value",
            argument_type=type(value),
            supported_argument_types=[FederatedDataFrame, str, int, float],
        )

__sub__(other) 🔗

Arithmetic operator, which subtracts a constant value or a single column FederatedDataFrame to a single column FederatedDataFrame. This operator is useful only in combination with setitem. In a privacy preserving mode use the sub function instead.

Example

Assume the dummy data for 'data_cloudnode' looks like this:

    patient_id  age  weight
0           1   77      55
1           2   88      60
2           3   93      83
df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode'))
df["new_weight"] = df["weight"] - 100
df.preprocess_on_dummy()
returns
   patient_id  age  weight  new_weight
0           1   77      55         -45
1           2   88      60         -40
2           3   93      83         -17

df["new_weight"] = df["weight"] - df["age"]
returns
   patient_id  age  weight  new_weight
0           1   77      55         -22
1           2   88      60         -28
2           3   93      83         -10

Parameters:

Name Type Description Default
other

constant value or a single column FederatedDataFrame to subtract.

required

Returns:

Type Description
FederatedDataFrame

new instance of the current object with updated graph.

Source code in .env/lib/python3.10/site-packages/apheris_stats/simple_stats/_internal/datatools/transformations/dataframe.py
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
def __sub__(self, other) -> FederatedDataFrame:
    """
    Arithmetic operator, which subtracts a constant value or a single column
    FederatedDataFrame to a single column FederatedDataFrame. This operator is
    useful only in combination with setitem. In a privacy preserving mode use
    the `sub` function instead.

    Example:
        Assume the dummy data for 'data_cloudnode' looks like this:
        ```
            patient_id  age  weight
        0           1   77      55
        1           2   88      60
        2           3   93      83
        df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode'))
        df["new_weight"] = df["weight"] - 100
        df.preprocess_on_dummy()
        ```
        returns
        ```
           patient_id  age  weight  new_weight
        0           1   77      55         -45
        1           2   88      60         -40
        2           3   93      83         -17
        ```

        ```
        df["new_weight"] = df["weight"] - df["age"]
        ```
        returns
        ```
           patient_id  age  weight  new_weight
        0           1   77      55         -22
        1           2   88      60         -28
        2           3   93      83         -10
        ```


    Args:
        other: constant value or a single column FederatedDataFrame to subtract.

    Returns:
        new instance of the current object with updated graph.
    """
    return self.__add__(other.__neg__())

__truediv__(other) 🔗

Arithmetic operator, which divides FederatedDataFrame by a constant or another FederatedDataFrame.

Example

Assume the dummy data for 'data_cloudnode' looks like this:

    patient_id  age  weight
0           1   77      55
1           2   88      60
2           3   93      83
df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode')
df["new_weight"] = df["weight"] / 2
df.preprocess_on_dummy()
returns
    patient_id  age  weight  new_weight
0           1   77      55        27.5
1           2   88      60        30.0
2           3   93      83        41.5

df["new_weight"] = df["weight"] / df["patient_id"]
returns
   patient_id  age  weight  new_weight
0           1   77      55   55.000000
1           2   88      60   30.000000
2           3   93      83   27.666667

Parameters:

Name Type Description Default
other Union[FederatedDataFrame, int, float, bool]

constant value or another FederatedDataFrame to divide by.

required

Returns:

Type Description
FederatedDataFrame

new instance of the current object with updated graph.

Source code in .env/lib/python3.10/site-packages/apheris_stats/simple_stats/_internal/datatools/transformations/dataframe.py
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
def __truediv__(
    self,
    other: Union[(FederatedDataFrame, int, float, bool)],
) -> FederatedDataFrame:
    """
    Arithmetic operator, which divides FederatedDataFrame by a constant or
    another FederatedDataFrame.

    Example:
        Assume the dummy data for 'data_cloudnode' looks like this:
        ```
            patient_id  age  weight
        0           1   77      55
        1           2   88      60
        2           3   93      83
        df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode')
        df["new_weight"] = df["weight"] / 2
        df.preprocess_on_dummy()
        ```
        returns
        ```
            patient_id  age  weight  new_weight
        0           1   77      55        27.5
        1           2   88      60        30.0
        2           3   93      83        41.5
        ```

        ```
        df["new_weight"] = df["weight"] / df["patient_id"]
        ```
        returns
        ```
           patient_id  age  weight  new_weight
        0           1   77      55   55.000000
        1           2   88      60   30.000000
        2           3   93      83   27.666667
        ```


    Args:
        other: constant value or another FederatedDataFrame to divide by.

    Returns:
        new instance of the current object with updated graph.
    """
    if isinstance(other, FederatedDataFrame):
        # We want to add two columns
        return self._add_graph_dst_node_with_multiple_edges(
            node_label="dividend / divisor",
            other_srcs=other,
            node_command=NodeCommands.divide.name,
            node_command_src_key="dividend",
            node_command_other_srcs_keys="divisor",
            edges_labels={other._uuid: "divisor"},
        )
    elif isinstance(other, (int, float, bool)):
        return self._add_graph_dst_node_with_edge(
            node_label=f"dividend / {other}",
            node_command=NodeCommands.divide_by_constant.name,
            node_command_src_key="dividend",
            node_command_kwargs={
                "divisor": other,
            },
        )
    else:
        raise TransformationsOperationArgumentTypeNotAllowedException(
            function_name=self.__truediv__.__name__,
            argument_name="other",
            argument_type=type(other),
            supported_argument_types=[FederatedDataFrame, int, float, bool],
        )

add(left, right, result=None) 🔗

Privacy-preserving addition: to a column (left) add another column or constant value (right) and store the result in result. Adding arbitrary iterables would allow for singling out attacks and is therefore disallowed.

Example

Assume the dummy data for 'data_cloudnode' looks like this:

    patient_id  age  weight
0           1   77      55
1           2   88      60
2           3   93      83

df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode')
df.add("weight", 100, "new_weight")
df.preprocess_on_dummy()

returns

   patient_id  age  weight  new_weight
0           1   77      55         155
1           2   88      60         160
2           3   93      83         183

df.add("weight", "age", "new_weight")

returns

   patient_id  age  weight  new_weight
0           1   77      55         132
1           2   88      60         148
2           3   93      83         176

Parameters:

Name Type Description Default
left

a column identifier

required
right

a column identifier or constant value

required
result

name for the new result column can be set to None to overwrite the left column

None

Returns:

Type Description
FederatedDataFrame

new instance of the current object with updated graph.

Source code in .env/lib/python3.10/site-packages/apheris_stats/simple_stats/_internal/datatools/transformations/dataframe.py
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
def add(self, left, right, result=None) -> FederatedDataFrame:
    """Privacy-preserving addition: to a column (`left`)
    add another column or constant value (`right`)
    and store the result in `result`.
    Adding arbitrary iterables would allow for
    singling out attacks and is therefore disallowed.

    Example:
        Assume the dummy data for 'data_cloudnode' looks like this:
        ```
            patient_id  age  weight
        0           1   77      55
        1           2   88      60
        2           3   93      83

        df = FederatedDataFrame(apheris_auth.RemoteData('data_cloudnode')
        df.add("weight", 100, "new_weight")
        df.preprocess_on_dummy()
        ```

        returns
        ```
           patient_id  age  weight  new_weight
        0           1   77      55         155
        1           2   88      60         160
        2           3   93      83         183

        df.add("weight", "age", "new_weight")
        ```

        returns
        ```
           patient_id  age  weight  new_weight
        0           1   77      55         132
        1           2   88      60         148
        2           3   93      83         176
        ```

    Args:
        left: a column identifier
        right: a column identifier or constant value
        result: name for the new result column
            can be set to None to overwrite the left column

    Returns:
        new instance of the current object with updated graph.

    """
    if isinstance(right, FederatedDataFrame):
        raise TransformationsOperationArgumentTypeNotAllowedException(
            function_name=self.add.__name__,
            argument_name="right",
            argument_type=type(right),
            supported_argument_types=list(BASIC_TYPES),
        )
    if isinstance(left, FederatedDataFrame):
        raise TransformationsOperationArgumentTypeNotAllowedException(
            function_name=self.add.__name__,
            argument_name="left",
            argument_type=type(left),
            supported_argument_types=["column identifier"],
        )
    if result is None:
        result = left

    return self._add_graph_dst_node_with_edge(
        node_label=f"{result} = {left} + {right}",
        node_command=NodeCommands.addition.name,
        node_command_src_key="table",
        node_command_kwargs={
            "summand_column1": left,
            "summand2": right,
            "result_column": result,
        },
    )

astype(dtype, on_column=None, result_column=None) 🔗

Convert the entire table to the given datatype similarly to pandas' astype. The following arguments from pandas implementation are not supported: copy, errors Optionally arguments not present in pandas implementation: on_column