trasgoDP 0.0.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
trasgodp-0.0.1/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,99 @@
1
+ Metadata-Version: 2.4
2
+ Name: trasgoDP
3
+ Version: 0.0.1
4
+ Summary: Local differential privacy mechanisms
5
+ License: Apache-2.0
6
+ License-File: LICENSE
7
+ Keywords: data,privacy,differential-privacy
8
+ Author: Judith Sáinz-Pardo Díaz
9
+ Author-email: sainzpardo@ifca.unican.es
10
+ Maintainer: Judith Sáinz-Pardo Díaz
11
+ Maintainer-email: sainzpardo@ifca.unican.es
12
+ Requires-Python: >=3.10,<4.0
13
+ Classifier: Development Status :: 5 - Production/Stable
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Intended Audience :: Education
16
+ Classifier: Intended Audience :: Science/Research
17
+ Classifier: License :: OSI Approved :: Apache Software License
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Python :: 3.13
23
+ Classifier: Programming Language :: Python :: 3.14
24
+ Classifier: Programming Language :: Python :: 3 :: Only
25
+ Classifier: Topic :: Scientific/Engineering
26
+ Classifier: Topic :: Scientific/Engineering :: Mathematics
27
+ Classifier: Topic :: Security
28
+ Requires-Dist: numpy (==2.2.6)
29
+ Requires-Dist: pandas (==2.3.3)
30
+ Requires-Dist: typing_extensions (==4.15.0)
31
+ Project-URL: Repository, https://github.com/judithspd/siesta-ldp
32
+ Description-Content-Type: text/markdown
33
+
34
+ # TrasgoDP
35
+ [![License: Apache 2.0](https://img.shields.io/badge/License-Apache_2.0-green.svg)](https://github.com/judithspd/trasgodp/blob/main/LICENSE)
36
+ [![codecov](https://codecov.io/gh/judithspd/trasgodp/graph/badge.svg?token=RGO77BTPHZ)](https://codecov.io/gh/judithspd/trasgodp)
37
+ [![Documentation Status](https://readthedocs.org/projects/trasgodp/badge/?version=latest)](https://trasgodp.readthedocs.io/en/latest/?badge=latest)
38
+ [![CI/CD Pipeline](https://github.com/judithspd/trasgodp/actions/workflows/cicd.yml/badge.svg)](https://github.com/judithspd/trasgodp/actions/workflows/cicd.yml)
39
+ ![Python version](https://img.shields.io/badge/python-3.10|3.11|3.12|3.13|3.14-blue)
40
+
41
+ TrasgoDP implements different mechanims for ε-differential privacy and (ε, δ)-differential privacy. The mechanisms are implemented for being used under a local approach, adding noise directly to the raw data.
42
+ Two types of mechanims are implemented:
43
+ - For numerical records: _Laplace_ and _Gaussian mechanisms_. The implementation includes a final clipping applyied on the data with DP.
44
+ - For categorical records: _Exponential mechanism_.
45
+
46
+ This library provides dedicated function designed for being applied on both pandas dataframes and lists/numpy arrays.
47
+
48
+ ## Getting started
49
+ For applying DP mechanisms to a column of a dataframe you need to introduce:
50
+ * The **pandas dataframe** with the data.
51
+ * The **column** in the dataframe to be privatized.
52
+ * The **privacy budget (ε)**.
53
+ * The **probability of exceeding the privacy budget (δ)** in case of numerical attributes and the Gaussian mechanism.
54
+ * The **uper and lower bounds** for numerical attributes (optional).
55
+
56
+ **Example: apply DP to the [adult dataset](https://archive.ics.uci.edu/dataset/2/adult) with the Laplace mechanism for the column _age_ and the Exponential mechanism for the column _workclass_:**
57
+ ```python
58
+ import pandas as pd
59
+ from trasgodp.numerical import dp_clip_laplace
60
+ from trasgodp.categorical import dp_exponential
61
+
62
+ # Read and process the data
63
+ data = pd.read_csv("examples/adult.csv")
64
+ data.columns = data.columns.str.strip()
65
+ cols = [
66
+ "workclass",
67
+ "education",
68
+ "marital-status",
69
+ "occupation",
70
+ "sex",
71
+ "native-country",
72
+ ]
73
+ for col in cols:
74
+ data[col] = data[col].str.strip()
75
+
76
+ # Apply DP for the attribute age:
77
+ column_num = "age"
78
+ epsilon1 = 10
79
+ df = dp_clip_laplace(data, column_num, epsilon1, new_column=True)
80
+
81
+ # Apply DP for the attribute workclass:
82
+ column_cat = "workclass"
83
+ epsilon2 = 5
84
+ df = dp_exponential(data, column_cat, epsilon2, new_column=True)
85
+ ```
86
+
87
+ ### Warning
88
+ This project is under active development.
89
+
90
+ ## License
91
+ This project is licensed under the [Apache 2.0 license](https://github.com/judithspd/trasgodp/blob/main/LICENSE).
92
+
93
+ ## Funding and acknowledgments
94
+ This work is funded by European Union through the SIESTA project (Horizon Europe) under Grant number [101131957](https://cordis.europa.eu/project/id/101131957).
95
+ <p>
96
+ <img align="center" width="250" src="https://raw.githubusercontent.com/SIESTA-eu/.github/main/profile/EN-Funded.jpg">
97
+ <img align="center" width="250" src="https://raw.githubusercontent.com/SIESTA-eu/.github/main/profile/logo.png">
98
+ <p>
99
+
@@ -0,0 +1,65 @@
1
+ # TrasgoDP
2
+ [![License: Apache 2.0](https://img.shields.io/badge/License-Apache_2.0-green.svg)](https://github.com/judithspd/trasgodp/blob/main/LICENSE)
3
+ [![codecov](https://codecov.io/gh/judithspd/trasgodp/graph/badge.svg?token=RGO77BTPHZ)](https://codecov.io/gh/judithspd/trasgodp)
4
+ [![Documentation Status](https://readthedocs.org/projects/trasgodp/badge/?version=latest)](https://trasgodp.readthedocs.io/en/latest/?badge=latest)
5
+ [![CI/CD Pipeline](https://github.com/judithspd/trasgodp/actions/workflows/cicd.yml/badge.svg)](https://github.com/judithspd/trasgodp/actions/workflows/cicd.yml)
6
+ ![Python version](https://img.shields.io/badge/python-3.10|3.11|3.12|3.13|3.14-blue)
7
+
8
+ TrasgoDP implements different mechanims for ε-differential privacy and (ε, δ)-differential privacy. The mechanisms are implemented for being used under a local approach, adding noise directly to the raw data.
9
+ Two types of mechanims are implemented:
10
+ - For numerical records: _Laplace_ and _Gaussian mechanisms_. The implementation includes a final clipping applyied on the data with DP.
11
+ - For categorical records: _Exponential mechanism_.
12
+
13
+ This library provides dedicated function designed for being applied on both pandas dataframes and lists/numpy arrays.
14
+
15
+ ## Getting started
16
+ For applying DP mechanisms to a column of a dataframe you need to introduce:
17
+ * The **pandas dataframe** with the data.
18
+ * The **column** in the dataframe to be privatized.
19
+ * The **privacy budget (ε)**.
20
+ * The **probability of exceeding the privacy budget (δ)** in case of numerical attributes and the Gaussian mechanism.
21
+ * The **uper and lower bounds** for numerical attributes (optional).
22
+
23
+ **Example: apply DP to the [adult dataset](https://archive.ics.uci.edu/dataset/2/adult) with the Laplace mechanism for the column _age_ and the Exponential mechanism for the column _workclass_:**
24
+ ```python
25
+ import pandas as pd
26
+ from trasgodp.numerical import dp_clip_laplace
27
+ from trasgodp.categorical import dp_exponential
28
+
29
+ # Read and process the data
30
+ data = pd.read_csv("examples/adult.csv")
31
+ data.columns = data.columns.str.strip()
32
+ cols = [
33
+ "workclass",
34
+ "education",
35
+ "marital-status",
36
+ "occupation",
37
+ "sex",
38
+ "native-country",
39
+ ]
40
+ for col in cols:
41
+ data[col] = data[col].str.strip()
42
+
43
+ # Apply DP for the attribute age:
44
+ column_num = "age"
45
+ epsilon1 = 10
46
+ df = dp_clip_laplace(data, column_num, epsilon1, new_column=True)
47
+
48
+ # Apply DP for the attribute workclass:
49
+ column_cat = "workclass"
50
+ epsilon2 = 5
51
+ df = dp_exponential(data, column_cat, epsilon2, new_column=True)
52
+ ```
53
+
54
+ ### Warning
55
+ This project is under active development.
56
+
57
+ ## License
58
+ This project is licensed under the [Apache 2.0 license](https://github.com/judithspd/trasgodp/blob/main/LICENSE).
59
+
60
+ ## Funding and acknowledgments
61
+ This work is funded by European Union through the SIESTA project (Horizon Europe) under Grant number [101131957](https://cordis.europa.eu/project/id/101131957).
62
+ <p>
63
+ <img align="center" width="250" src="https://raw.githubusercontent.com/SIESTA-eu/.github/main/profile/EN-Funded.jpg">
64
+ <img align="center" width="250" src="https://raw.githubusercontent.com/SIESTA-eu/.github/main/profile/logo.png">
65
+ <p>
@@ -0,0 +1,81 @@
1
+ [tool.poetry]
2
+ name = "trasgoDP"
3
+ version = "0.0.1"
4
+ description = "Local differential privacy mechanisms"
5
+ authors = [
6
+ "Judith Sáinz-Pardo Díaz <sainzpardo@ifca.unican.es>",
7
+ "Álvaro López García <aloga@ifca.unican.es>"
8
+ ]
9
+ maintainers = ["Judith Sáinz-Pardo Díaz <sainzpardo@ifca.unican.es>"]
10
+ license = "Apache License 2.0"
11
+ readme = "README.md"
12
+ repository = "https://github.com/judithspd/siesta-ldp"
13
+ keywords = ["data", "privacy", "differential-privacy"]
14
+ classifiers = [
15
+ "Development Status :: 5 - Production/Stable",
16
+ "Intended Audience :: Developers",
17
+ "Intended Audience :: Education",
18
+ "Intended Audience :: Science/Research",
19
+ "License :: OSI Approved :: Apache Software License",
20
+ "Programming Language :: Python :: 3 :: Only",
21
+ "Programming Language :: Python :: 3",
22
+ "Programming Language :: Python :: 3.10",
23
+ "Programming Language :: Python :: 3.11",
24
+ "Programming Language :: Python :: 3.12",
25
+ "Programming Language :: Python :: 3.13",
26
+ "Programming Language :: Python :: 3.14",
27
+ "Topic :: Scientific/Engineering",
28
+ "Topic :: Scientific/Engineering :: Mathematics",
29
+ "Topic :: Security"
30
+ ]
31
+
32
+
33
+ [tool.poetry.dependencies]
34
+ python = "^3.10"
35
+ numpy = "2.2.6"
36
+ pandas = "2.3.3"
37
+ typing_extensions = "4.15.0"
38
+
39
+
40
+ [tool.poetry.group.dev.dependencies]
41
+ tox = "4.16.0"
42
+
43
+
44
+ [tool.poetry.group.test.dependencies]
45
+ pytest = ">=7.1.2,<10.0.0"
46
+ pytest-cov = ">=4,<7"
47
+
48
+
49
+ [tool.poetry.group.test-flake8.dependencies]
50
+ flake8 = ">=4,<8"
51
+ flake8-bugbear = ">=22.3,<25.0"
52
+ flake8-docstrings = "^1.6"
53
+ flake8-typing-imports = "^1.12"
54
+ flake8-colors = "^0.1"
55
+ pep8-naming = ">=0.12,<0.16"
56
+ pydocstyle = "^6.1"
57
+
58
+
59
+ [tool.poetry.group.test-black.dependencies]
60
+ black = ">=22.3,<27.0"
61
+
62
+
63
+ [tool.poetry.group.test-bandit.dependencies]
64
+ bandit = "1.8.6"
65
+
66
+
67
+ [tool.poetry.group.test-pip-missing-reqs.dependencies]
68
+ pip-check-reqs = "^2.5.3"
69
+
70
+
71
+ [tool.poetry.group.test-mypy.dependencies]
72
+ mypy = "1.17.1"
73
+
74
+
75
+ [tool.poetry.group.test-pypi.dependencies]
76
+ twine = ">=4.0.2,<7.0.0"
77
+
78
+
79
+ [build-system]
80
+ requires = ["poetry-core"]
81
+ build-backend = "poetry.core.masonry.api"
@@ -0,0 +1,19 @@
1
+ # -*- coding: utf-8 -*-
2
+
3
+ # Copyright 2026 Spanish National Research Council (CSIC)
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License"); you may
6
+ # not use this file except in compliance with the License. You may obtain
7
+ # a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13
+ # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14
+ # License for the specific language governing permissions and limitations
15
+ # under the License.
16
+
17
+ """Local differential privacy applied to the columns of a dataset."""
18
+
19
+ __version__ = "0.0.1"
@@ -0,0 +1,19 @@
1
+ # Copyright 2026 Spanish National Research Council (CSIC)
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License"); you may
4
+ # not use this file except in compliance with the License. You may obtain
5
+ # a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11
+ # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12
+ # License for the specific language governing permissions and limitations
13
+ # under the License.
14
+
15
+ """DP Exponential mechanism for categorical columns."""
16
+
17
+ from ._exponential import dp_exponential, dp_exponential_array
18
+
19
+ __all__ = ["dp_exponential", "dp_exponential_array"]
@@ -0,0 +1,129 @@
1
+ # -*- coding: utf-8 -*-
2
+
3
+ # Copyright 2026 Spanish National Research Council (CSIC)
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License"); you may
6
+ # not use this file except in compliance with the License. You may obtain
7
+ # a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13
+ # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14
+ # License for the specific language governing permissions and limitations
15
+ # under the License.
16
+
17
+ """Exponential mechanism for local DP."""
18
+
19
+ import numpy as np
20
+ import pandas as pd
21
+ import typing
22
+
23
+
24
+ def dp_exponential(
25
+ df: pd.DataFrame,
26
+ column: str,
27
+ epsilon: float,
28
+ new_column=False,
29
+ ) -> pd.DataFrame:
30
+ """Apply the Exponential mechanism to a categorical column of a dataframe.
31
+
32
+ :param df: dataframe with the data under study.
33
+ :type df: pandas dataframe
34
+
35
+ :param columm: column to which the DP mechanism will be applied.
36
+ :type columm: string
37
+
38
+ :param epsilon: privacy budget.
39
+ :type epsilon: float
40
+
41
+ :param new_column: boolean, default to False. If False, the new values obtained
42
+ with the mechanims applied are stored in the same column. If True, a new
43
+ column 'dp_{column}' is created with the new values.
44
+ :type new_column: boolean
45
+
46
+ :return: dataframe with the column transformed applying the mechanism.
47
+ :rtype: pandas dataframe.
48
+ """
49
+ if column not in df.keys():
50
+ raise ValueError("Column: {column} not in the dataframe.")
51
+
52
+ if isinstance(df[column].values[0], str) is False:
53
+ raise ValueError(
54
+ "Type of the column not allowed for the Exponential mechanism."
55
+ )
56
+
57
+ if epsilon <= 0:
58
+ raise ValueError("The privacy budget must be greater than 0.")
59
+
60
+ categories = np.unique(df[column].values)
61
+
62
+ dp_column = []
63
+ for i in range(len(df)):
64
+ original_value = df[column].iloc[i]
65
+ dp_value = _probability_exp(original_value, categories, epsilon)
66
+ dp_column.append(dp_value)
67
+
68
+ if new_column:
69
+ df[f"dp_{column}"] = dp_column
70
+ else:
71
+ df[column] = dp_column
72
+
73
+ return df
74
+
75
+
76
+ def dp_exponential_array(
77
+ data: typing.Union[typing.List, np.ndarray],
78
+ epsilon: float,
79
+ ) -> np.ndarray:
80
+ """Apply the Exponential mechanism to an array with categorical values.
81
+
82
+ :param data: dataset with the data under study.
83
+ :type data: list or numpy array
84
+
85
+ :param epsilon: privacy budget.
86
+ :type epsilon: float
87
+
88
+ :return: array with data transformed applying the mechanism.
89
+ :rtype: numpy array.
90
+ """
91
+ if isinstance(data[0], str) is False:
92
+ raise ValueError(
93
+ "Type of the column not allowed for the Exponential mechanism."
94
+ )
95
+
96
+ if isinstance(data, list):
97
+ data = np.array(data)
98
+
99
+ if epsilon <= 0:
100
+ raise ValueError("The privacy budget must be greater than 0.")
101
+
102
+ categories = np.unique(data)
103
+
104
+ dp_array = []
105
+ for original_value in data:
106
+ dp_value = _probability_exp(original_value, categories, epsilon)
107
+ dp_array.append(dp_value)
108
+
109
+ return np.array(dp_array)
110
+
111
+
112
+ def _probability_exp(value, categories, epsilon):
113
+ """
114
+ Probability of the output of the Exponential mechanism.
115
+
116
+ :param value: current value
117
+ :type value: str
118
+
119
+ :param categories: possible values of the data
120
+ :type categories: list of strings
121
+
122
+ :param epsilon: privacy budget.
123
+ :type epsilon: float
124
+ """
125
+ sensitivity = 1
126
+ scores = np.array([1 if value == c else 0 for c in categories])
127
+ exp_scores = np.exp((epsilon * scores) / 2 * sensitivity)
128
+ probs = exp_scores / sum(exp_scores)
129
+ return np.random.choice(categories, p=probs)
@@ -0,0 +1,20 @@
1
+ # Copyright 2026 Spanish National Research Council (CSIC)
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License"); you may
4
+ # not use this file except in compliance with the License. You may obtain
5
+ # a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11
+ # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12
+ # License for the specific language governing permissions and limitations
13
+ # under the License.
14
+
15
+ """DP mechanisms for numerical columns with clipped results."""
16
+
17
+ from ._gaussian import dp_clip_gaussian
18
+ from ._laplace import dp_clip_laplace
19
+
20
+ __all__ = ["dp_clip_gaussian", "dp_clip_laplace"]
@@ -0,0 +1,97 @@
1
+ # -*- coding: utf-8 -*-
2
+
3
+ # Copyright 2026 Spanish National Research Council (CSIC)
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License"); you may
6
+ # not use this file except in compliance with the License. You may obtain
7
+ # a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13
+ # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14
+ # License for the specific language governing permissions and limitations
15
+ # under the License.
16
+
17
+ """Gaussian mechanism for local DP."""
18
+
19
+ import numpy as np
20
+ import pandas as pd
21
+
22
+
23
+ def dp_clip_gaussian(
24
+ df: pd.DataFrame,
25
+ column: str,
26
+ epsilon: float,
27
+ delta=1e-3,
28
+ lower_bound=None,
29
+ upper_bound=None,
30
+ new_column=False,
31
+ ) -> pd.DataFrame:
32
+ """Apply the Gaussian mechanism to a dataframe numeric column and clip the result.
33
+
34
+ :param df: dataframe with the data under study.
35
+ :type df: pandas dataframe
36
+
37
+ :param columm: column to which the DP mechanism will be applied.
38
+ :type columm: string
39
+
40
+ :param epsilon: privacy budget.
41
+ :type epsilon: float
42
+
43
+ :param delta: probability of exceeding the privacy budget.
44
+ :type delta: float
45
+
46
+ :param lower_bound: lower bound for clipping and calculating the sensitivity.
47
+ :type lower_bound: float
48
+
49
+ :param upper_bound: upper bound for clipping and calculating the sensitivity.
50
+ :type upper_bound: float
51
+
52
+ :param new_column: boolean, default to False. If False, the new values obtained
53
+ with the mechanims applied are stored in the same column. If True,
54
+ a new column 'dp_{column}' is created with the new values.
55
+ :type new_column: boolean
56
+
57
+ :return: dataframe with the column transformed applying the mechanism.
58
+ :rtype: pandas dataframe.
59
+ """
60
+ if column not in df.keys():
61
+ raise ValueError("Column: {column} not in the dataframe.")
62
+
63
+ if epsilon <= 0:
64
+ raise ValueError("The privacy budget must be greater than 0.")
65
+
66
+ if delta <= 0 or delta >= 1:
67
+ raise ValueError("The value of delta must be between 0 and 1.")
68
+
69
+ if np.issubdtype(df[column].dtype, np.integer):
70
+ data = df[column].astype(int)
71
+ elif np.issubdtype(df[column].dtype, np.floating):
72
+ data = df[column].astype(float)
73
+ else:
74
+ raise ValueError("Type of the column not allowed for the Gaussian mechanism.")
75
+
76
+ if lower_bound is None:
77
+ lower_bound = min(data.values)
78
+ if upper_bound is None:
79
+ upper_bound = max(data.values)
80
+
81
+ clipped = data.clip(lower_bound, upper_bound)
82
+
83
+ sensitivity = upper_bound - lower_bound
84
+ sigma = (sensitivity * np.sqrt(2 * np.log(1.25 / delta))) / epsilon
85
+ noise = np.random.normal(0, sigma, size=len(clipped))
86
+
87
+ dp_column = clipped + noise
88
+ if np.issubdtype(df[column].dtype, np.integer):
89
+ dp_column = round(dp_column, 0).astype(int)
90
+
91
+ dp_column = np.clip(dp_column, lower_bound, upper_bound)
92
+ if new_column:
93
+ df[f"dp_{column}"] = dp_column
94
+ else:
95
+ df[column] = dp_column
96
+
97
+ return df
@@ -0,0 +1,91 @@
1
+ # -*- coding: utf-8 -*-
2
+
3
+ # Copyright 2026 Spanish National Research Council (CSIC)
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License"); you may
6
+ # not use this file except in compliance with the License. You may obtain
7
+ # a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13
+ # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14
+ # License for the specific language governing permissions and limitations
15
+ # under the License.
16
+
17
+ """Laplace mechanism for local DP."""
18
+
19
+ import numpy as np
20
+ import pandas as pd
21
+
22
+
23
+ def dp_clip_laplace(
24
+ df: pd.DataFrame,
25
+ column: str,
26
+ epsilon: float,
27
+ lower_bound=None,
28
+ upper_bound=None,
29
+ new_column=False,
30
+ ) -> pd.DataFrame:
31
+ """Apply the Laplace mechanism to a dataframe numeric column and clip the result.
32
+
33
+ :param df: dataframe with the data under study.
34
+ :type df: pandas dataframe
35
+
36
+ :param columm: column to which the DP mechanism will be applied.
37
+ :type columm: string
38
+
39
+ :param epsilon: privacy budget.
40
+ :type epsilon: float
41
+
42
+ :param lower_bound: lower bound for clipping and calculating the sensitivity.
43
+ :type lower_bound: float
44
+
45
+ :param upper_bound: upper bound for clipping and calculating the sensitivity.
46
+ :type upper_bound: float
47
+
48
+ :param new_column: boolean, default to False. If False, the new values obtained
49
+ with the mechanims applied are stored in the same column. If True, a new column
50
+ "dp_{column}" is created with the new values.
51
+ :type new_column: boolean
52
+
53
+ :return: dataframe with the column transformed applying the mechanism.
54
+ :rtype: pandas dataframe.
55
+ """
56
+ if column not in df.keys():
57
+ raise ValueError("Column: {column} not in the dataframe.")
58
+
59
+ if epsilon <= 0:
60
+ raise ValueError("The privacy budget must be greater than 0.")
61
+
62
+ if np.issubdtype(df[column].dtype, np.integer):
63
+ data = df[column].astype(int)
64
+ elif np.issubdtype(df[column].dtype, np.floating):
65
+ data = df[column].astype(float)
66
+ else:
67
+ raise ValueError("Type of the column not allowed for the Laplace mechanism.")
68
+
69
+ if lower_bound is None:
70
+ lower_bound = min(data.values)
71
+ if upper_bound is None:
72
+ upper_bound = max(data.values)
73
+
74
+ clipped = data.clip(lower_bound, upper_bound)
75
+
76
+ sensitivity = upper_bound - lower_bound
77
+ scale = sensitivity / epsilon
78
+ noise = np.random.laplace(0, scale, size=len(clipped))
79
+
80
+ dp_column = clipped + noise
81
+
82
+ if np.issubdtype(df[column].dtype, np.integer):
83
+ dp_column = round(dp_column, 0).astype(int)
84
+
85
+ dp_column = np.clip(dp_column, lower_bound, upper_bound)
86
+ if new_column:
87
+ df[f"dp_{column}"] = dp_column
88
+ else:
89
+ df[column] = dp_column
90
+
91
+ return df