learningmachine 0.2.2__tar.gz → 0.2.3__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.
Files changed (32) hide show
  1. {learningmachine-0.2.2 → learningmachine-0.2.3}/PKG-INFO +2 -2
  2. learningmachine-0.2.3/learningmachine/base.py +75 -0
  3. learningmachine-0.2.3/learningmachine/basemodels.py +231 -0
  4. {learningmachine-0.2.2 → learningmachine-0.2.3}/learningmachine.egg-info/PKG-INFO +2 -2
  5. learningmachine-0.2.3/setup.py +131 -0
  6. learningmachine-0.2.2/learningmachine/base.py +0 -18
  7. learningmachine-0.2.2/learningmachine/basemodels.py +0 -112
  8. learningmachine-0.2.2/setup.py +0 -175
  9. {learningmachine-0.2.2 → learningmachine-0.2.3}/CONTRIBUTING.rst +0 -0
  10. {learningmachine-0.2.2 → learningmachine-0.2.3}/HISTORY.rst +0 -0
  11. {learningmachine-0.2.2 → learningmachine-0.2.3}/LICENSE +0 -0
  12. {learningmachine-0.2.2 → learningmachine-0.2.3}/MANIFEST.in +0 -0
  13. {learningmachine-0.2.2 → learningmachine-0.2.3}/README.rst +0 -0
  14. {learningmachine-0.2.2 → learningmachine-0.2.3}/docs/Makefile +0 -0
  15. {learningmachine-0.2.2 → learningmachine-0.2.3}/docs/conf.py +0 -0
  16. {learningmachine-0.2.2 → learningmachine-0.2.3}/docs/contributing.rst +0 -0
  17. {learningmachine-0.2.2 → learningmachine-0.2.3}/docs/history.rst +0 -0
  18. {learningmachine-0.2.2 → learningmachine-0.2.3}/docs/index.rst +0 -0
  19. {learningmachine-0.2.2 → learningmachine-0.2.3}/docs/installation.rst +0 -0
  20. {learningmachine-0.2.2 → learningmachine-0.2.3}/docs/make.bat +0 -0
  21. {learningmachine-0.2.2 → learningmachine-0.2.3}/docs/readme.rst +0 -0
  22. {learningmachine-0.2.2 → learningmachine-0.2.3}/docs/usage.rst +0 -0
  23. {learningmachine-0.2.2 → learningmachine-0.2.3}/learningmachine/__init__.py +0 -0
  24. {learningmachine-0.2.2 → learningmachine-0.2.3}/learningmachine/utils.py +0 -0
  25. {learningmachine-0.2.2 → learningmachine-0.2.3}/learningmachine.egg-info/SOURCES.txt +0 -0
  26. {learningmachine-0.2.2 → learningmachine-0.2.3}/learningmachine.egg-info/dependency_links.txt +0 -0
  27. {learningmachine-0.2.2 → learningmachine-0.2.3}/learningmachine.egg-info/not-zip-safe +0 -0
  28. {learningmachine-0.2.2 → learningmachine-0.2.3}/learningmachine.egg-info/requires.txt +0 -0
  29. {learningmachine-0.2.2 → learningmachine-0.2.3}/learningmachine.egg-info/top_level.txt +0 -0
  30. {learningmachine-0.2.2 → learningmachine-0.2.3}/setup.cfg +0 -0
  31. {learningmachine-0.2.2 → learningmachine-0.2.3}/tests/__init__.py +0 -0
  32. {learningmachine-0.2.2 → learningmachine-0.2.3}/tests/test_learningmachine.py +0 -0
@@ -1,8 +1,8 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: learningmachine
3
- Version: 0.2.2
3
+ Version: 0.2.3
4
4
  Summary: Machine Learning with uncertainty quantification and interpretability
5
- Home-page: https://github.com/Techtonique/learningmachine
5
+ Home-page: https://github.com/Techtonique/learningmachine_python
6
6
  Author: T. Moudiki
7
7
  Author-email: thierry.moudiki@gmail.com
8
8
  License: BSD Clause Clear license
@@ -0,0 +1,75 @@
1
+ import subprocess
2
+ from functools import lru_cache
3
+ from rpy2.robjects import r
4
+ from rpy2.robjects.packages import importr
5
+ from rpy2.robjects.vectors import StrVector
6
+ from sklearn.base import BaseEstimator
7
+
8
+ base = importr("base")
9
+ stats = importr("stats")
10
+
11
+
12
+ @lru_cache(maxsize=32)
13
+ def load_learningmachine():
14
+ # Install R packages
15
+ commands1_lm = 'base::system.file(package = "learningmachine")' # check "learningmachine" is installed
16
+ commands2_lm = 'base::system.file("learningmachine_r", package = "learningmachine")' # check "learningmachine" is installed locally
17
+ exec_commands1_lm = subprocess.run(
18
+ ["Rscript", "-e", commands1_lm], capture_output=True, text=True
19
+ )
20
+ exec_commands2_lm = subprocess.run(
21
+ ["Rscript", "-e", commands2_lm], capture_output=True, text=True
22
+ )
23
+ if (
24
+ len(exec_commands1_lm.stdout) == 7
25
+ and len(exec_commands2_lm.stdout) == 7
26
+ ): # kind of convoluted, but works
27
+ print("Installing R packages along with 'learningmachine'...")
28
+ commands1 = [
29
+ 'try(utils::install.packages(c("R6", "Rcpp", "skimr"), repos="https://cloud.r-project.org", dependencies = TRUE), silent=TRUE)',
30
+ 'try(utils::install.packages("learningmachine", repos="https://techtonique.r-universe.dev", dependencies = TRUE), silent=TRUE)',
31
+ ]
32
+ commands2 = [
33
+ 'try(utils::install.packages(c("R6", "Rcpp", "skimr"), lib="./learningmachine_r", repos="https://cloud.r-project.org", dependencies = TRUE), silent=TRUE)',
34
+ 'try(utils::install.packages("learningmachine", lib="./learningmachine_r", repos="https://techtonique.r-universe.dev", dependencies = TRUE), silent=TRUE)',
35
+ ]
36
+ try:
37
+ for cmd in commands1:
38
+ subprocess.run(["Rscript", "-e", cmd])
39
+ except Exception as e: # can't install packages globally
40
+ subprocess.run(["mkdir", "learningmachine_r"])
41
+ for cmd in commands2:
42
+ subprocess.run(["Rscript", "-e", cmd])
43
+
44
+ try:
45
+ base.library(StrVector(["learningmachine"]))
46
+ except (
47
+ Exception
48
+ ) as e1: # can't load the package from the global environment
49
+ try:
50
+ base.library(
51
+ StrVector(["learningmachine"]), lib_loc="learningmachine_r"
52
+ )
53
+ except Exception as e2: # well, we tried
54
+ try:
55
+ r("try(library('learningmachine'), silence=TRUE)")
56
+ except (
57
+ NotImplementedError
58
+ ) as e3: # well, we tried everything at this point
59
+ r(
60
+ "try(library('learningmachine', lib.loc='learningmachine_r'), silence=TRUE)"
61
+ )
62
+
63
+
64
+ class Base(BaseEstimator):
65
+ """
66
+ Base class.
67
+ """
68
+
69
+ def __init__(self):
70
+ """
71
+ Initialize the model.
72
+ """
73
+ self.type_fit = None
74
+ self.obj = None
75
+ load_learningmachine()
@@ -0,0 +1,231 @@
1
+ import numpy as np
2
+ import sklearn.metrics as skm
3
+ from subprocess import run
4
+ from rpy2.robjects import r
5
+ from rpy2.robjects.packages import importr
6
+ from rpy2.robjects.vectors import (
7
+ FloatMatrix,
8
+ FloatVector,
9
+ IntVector,
10
+ StrVector,
11
+ )
12
+ from sklearn.base import RegressorMixin, ClassifierMixin
13
+ from .base import Base
14
+
15
+ base = importr("base")
16
+ stats = importr("stats")
17
+ utils = importr("utils")
18
+
19
+
20
+ class BaseRegressor(Base, RegressorMixin):
21
+ """
22
+ Base Regressor.
23
+ """
24
+
25
+ def __init__(self):
26
+ """
27
+ Initialize the model.
28
+ """
29
+ super().__init__()
30
+ self.type_fit = "regression"
31
+ self.obj = r("learningmachine::BaseRegressor$new()")
32
+
33
+ def fit(self, X, y):
34
+ """
35
+ Fit the model according to the given training data.
36
+ """
37
+ self.obj["fit"](
38
+ r.matrix(
39
+ FloatVector(X), byrow=True, nrow=X.shape[0], ncol=X.shape[1]
40
+ ),
41
+ FloatVector(y),
42
+ )
43
+ return self
44
+
45
+ def predict(self, X):
46
+ """
47
+ Predict using the model.
48
+ """
49
+ return np.asarray(
50
+ self.obj["predict"](
51
+ r.matrix(
52
+ FloatMatrix(X), byrow=True, nrow=X.shape[0], ncol=X.shape[1]
53
+ )
54
+ )
55
+ )
56
+
57
+ def score(self, X, y, scoring=None, **kwargs):
58
+ """Score the model on test set features X and response y.
59
+
60
+ Parameters:
61
+
62
+ X: {array-like}, shape = [n_samples, n_features]
63
+ Training vectors, where n_samples is the number
64
+ of samples and n_features is the number of features
65
+
66
+ y: array-like, shape = [n_samples]
67
+ Target values
68
+
69
+ scoring: str
70
+ must be in ('explained_variance', 'neg_mean_absolute_error',
71
+ 'neg_mean_squared_error', 'neg_mean_squared_log_error',
72
+ 'neg_median_absolute_error', 'r2')
73
+
74
+ **kwargs: additional parameters to be passed to scoring functions
75
+
76
+ Returns:
77
+
78
+ model scores: {array-like}
79
+
80
+ """
81
+
82
+ preds = self.predict(X)
83
+
84
+ if type(preds) == tuple: # if there are std. devs in the predictions
85
+ preds = preds[0]
86
+
87
+ if scoring is None:
88
+ scoring = "neg_mean_squared_error"
89
+
90
+ # check inputs
91
+ assert scoring in (
92
+ "explained_variance",
93
+ "neg_mean_absolute_error",
94
+ "neg_mean_squared_error",
95
+ "neg_mean_squared_log_error",
96
+ "neg_median_absolute_error",
97
+ "r2",
98
+ ), "'scoring' should be in ('explained_variance', 'neg_mean_absolute_error', \
99
+ 'neg_mean_squared_error', 'neg_mean_squared_log_error', \
100
+ 'neg_median_absolute_error', 'r2')"
101
+
102
+ scoring_options = {
103
+ "explained_variance": skm.explained_variance_score,
104
+ "neg_mean_absolute_error": skm.median_absolute_error,
105
+ "neg_mean_squared_error": skm.mean_squared_error,
106
+ "neg_mean_squared_log_error": skm.mean_squared_log_error,
107
+ "neg_median_absolute_error": skm.median_absolute_error,
108
+ "r2": skm.r2_score,
109
+ }
110
+
111
+ return scoring_options[scoring](y, preds, **kwargs)
112
+
113
+
114
+ class BaseClassifier(Base, ClassifierMixin):
115
+ """
116
+ Base Classifier.
117
+ """
118
+
119
+ def __init__(self):
120
+ """
121
+ Initialize the model.
122
+ """
123
+ super().__init__()
124
+ self.type_fit = "classification"
125
+ self.obj = r("learningmachine::BaseClassifier$new()")
126
+
127
+ def fit(self, X, y):
128
+ """
129
+ Fit the model according to the given training data.
130
+ """
131
+ self.obj["fit"](
132
+ r.matrix(
133
+ FloatMatrix(X), byrow=True, nrow=X.shape[0], ncol=X.shape[1]
134
+ ),
135
+ base.as_factor(IntVector(y)),
136
+ )
137
+ self.classes_ = np.unique(y)
138
+ return self
139
+
140
+ def predict(self, X):
141
+ """
142
+ Predict classes using the model.
143
+ """
144
+ return np.asarray(
145
+ self.obj["predict"](
146
+ r.matrix(
147
+ FloatMatrix(X), byrow=True, nrow=X.shape[0], ncol=X.shape[1]
148
+ )
149
+ )
150
+ )
151
+
152
+ def predict_proba(self, X):
153
+ """
154
+ Predict probabilities using the model.
155
+ """
156
+ return np.asarray(
157
+ self.obj["predict_proba"](
158
+ r.matrix(
159
+ FloatMatrix(X), byrow=True, nrow=X.shape[0], ncol=X.shape[1]
160
+ )
161
+ )
162
+ )
163
+
164
+ def score(self, X, y, scoring=None, **kwargs):
165
+ """Score the model on test set features X and response y.
166
+
167
+ Parameters:
168
+
169
+ X: {array-like}, shape = [n_samples, n_features]
170
+ Training vectors, where n_samples is the number
171
+ of samples and n_features is the number of features
172
+
173
+ y: array-like, shape = [n_samples]
174
+ Target values
175
+
176
+ scoring: str
177
+ must be in ('accuracy', 'average_precision',
178
+ 'brier_score_loss', 'f1', 'f1_micro',
179
+ 'f1_macro', 'f1_weighted', 'f1_samples',
180
+ 'neg_log_loss', 'precision', 'recall',
181
+ 'roc_auc')
182
+
183
+ **kwargs: additional parameters to be passed to scoring functions
184
+
185
+ Returns:
186
+
187
+ model scores: {array-like}
188
+
189
+ """
190
+
191
+ preds = self.predict(X)
192
+
193
+ if scoring is None:
194
+ scoring = "accuracy"
195
+
196
+ # check inputs
197
+ assert scoring in (
198
+ "accuracy",
199
+ "average_precision",
200
+ "brier_score_loss",
201
+ "f1",
202
+ "f1_micro",
203
+ "f1_macro",
204
+ "f1_weighted",
205
+ "f1_samples",
206
+ "neg_log_loss",
207
+ "precision",
208
+ "recall",
209
+ "roc_auc",
210
+ ), "'scoring' should be in ('accuracy', 'average_precision', \
211
+ 'brier_score_loss', 'f1', 'f1_micro', \
212
+ 'f1_macro', 'f1_weighted', 'f1_samples', \
213
+ 'neg_log_loss', 'precision', 'recall', \
214
+ 'roc_auc')"
215
+
216
+ scoring_options = {
217
+ "accuracy": skm.accuracy_score,
218
+ "average_precision": skm.average_precision_score,
219
+ "brier_score_loss": skm.brier_score_loss,
220
+ "f1": skm.f1_score,
221
+ "f1_micro": skm.f1_score,
222
+ "f1_macro": skm.f1_score,
223
+ "f1_weighted": skm.f1_score,
224
+ "f1_samples": skm.f1_score,
225
+ "neg_log_loss": skm.log_loss,
226
+ "precision": skm.precision_score,
227
+ "recall": skm.recall_score,
228
+ "roc_auc": skm.roc_auc_score,
229
+ }
230
+
231
+ return scoring_options[scoring](y, preds, **kwargs)
@@ -1,8 +1,8 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: learningmachine
3
- Version: 0.2.2
3
+ Version: 0.2.3
4
4
  Summary: Machine Learning with uncertainty quantification and interpretability
5
- Home-page: https://github.com/Techtonique/learningmachine
5
+ Home-page: https://github.com/Techtonique/learningmachine_python
6
6
  Author: T. Moudiki
7
7
  Author-email: thierry.moudiki@gmail.com
8
8
  License: BSD Clause Clear license
@@ -0,0 +1,131 @@
1
+ #!/usr/bin/env python
2
+
3
+ # 1 - import Python packages -----------------------------------------------
4
+
5
+ import subprocess
6
+
7
+ subprocess.run(["pip", "install", "rpy2"])
8
+
9
+ from os import path
10
+ import platform
11
+ from setuptools import setup, find_packages
12
+
13
+
14
+ # 2 - utility functions -----------------------------------------------
15
+
16
+ def check_r_installed():
17
+ current_platform = platform.system()
18
+
19
+ if current_platform == "Windows":
20
+ # Check if R is installed on Windows by checking the registry
21
+ try:
22
+ subprocess.run(
23
+ ["reg", "query", "HKLM\\Software\\R-core\\R"], check=True
24
+ )
25
+ print("R is already installed on Windows.")
26
+ return True
27
+ except subprocess.CalledProcessError:
28
+ print(
29
+ "R is required but not installed on Windows (check manually: https://cloud.r-project.org/)."
30
+ )
31
+ return False
32
+
33
+ elif current_platform == "Linux":
34
+ # Check if R is installed on Linux by checking if the 'R' executable is available
35
+ try:
36
+ subprocess.run(["which", "R"], check=True)
37
+ print("R is already installed on Linux.")
38
+ return True
39
+ except subprocess.CalledProcessError:
40
+ print(
41
+ "R is required but not installed on Linux (check manually: https://cloud.r-project.org/)."
42
+ )
43
+ return False
44
+
45
+ elif current_platform == "Darwin": # macOS
46
+ # Check if R is installed on macOS by checking if the 'R' executable is available
47
+ try:
48
+ subprocess.run(["which", "R"], check=True)
49
+ print("R is already installed on macOS.")
50
+ return True
51
+ except subprocess.CalledProcessError:
52
+ print(
53
+ "R is required but not installed on macOS (check manually: https://cloud.r-project.org/)."
54
+ )
55
+ return False
56
+
57
+ else:
58
+ print("Unsupported platform (check manually: https://cloud.r-project.org/)")
59
+ return False
60
+
61
+ def install_r():
62
+ current_platform = platform.system()
63
+
64
+ if current_platform == "Windows":
65
+ # Install R on Windows using PowerShell
66
+ install_command = "Start-Process powershell -Verb runAs -ArgumentList '-Command \"& {Invoke-WebRequest https://cran.r-project.org/bin/windows/base/R-4.1.2-win.exe -OutFile R.exe}; Start-Process R.exe -ArgumentList '/SILENT' -Wait}'"
67
+ subprocess.run(install_command, shell=True)
68
+
69
+ elif current_platform == "Linux":
70
+ # Install R on Linux using the appropriate package manager (e.g., apt-get)
71
+ install_command = (
72
+ "sudo apt update -qq && sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys E298A3A825C0D65DFD57CBB651716619E084DAB9"
73
+ + "&& sudo add-apt-repository 'deb https://cloud.r-project.org/bin/linux/ubuntu focal-cran40/'"
74
+ + "&& sudo apt update"
75
+ + "&& sudo apt install r-base"
76
+ )
77
+ try:
78
+ subprocess.run(install_command, shell=True)
79
+ except Exception as e:
80
+ print("Error installing R on this Linux distribution. Please check manually: https://cloud.r-project.org/")
81
+
82
+ elif current_platform == "Darwin": # macOS
83
+ # Install R on macOS using Homebrew
84
+ install_command = "brew install r"
85
+ try:
86
+ subprocess.run(install_command, shell=True)
87
+ except Exception as e:
88
+ print("Error installing R on macOS. Please check manually: https://cloud.r-project.org/")
89
+
90
+ else:
91
+ print("Unsupported platform. Unable to install R.")
92
+
93
+
94
+ # 3 - check if R is installed -----------------------------------------------
95
+
96
+ if not check_r_installed():
97
+ install_r()
98
+ else:
99
+ print("R is already installed.")
100
+
101
+ # 4 - Package setup -----------------------------------------------
102
+
103
+ """The setup script."""
104
+
105
+ setup(
106
+ author="T. Moudiki",
107
+ author_email="thierry.moudiki@gmail.com",
108
+ python_requires=">=3.6",
109
+ classifiers=[
110
+ "Development Status :: 2 - Pre-Alpha",
111
+ "Intended Audience :: Developers",
112
+ "License :: OSI Approved :: BSD License",
113
+ "Natural Language :: English",
114
+ "Programming Language :: Python :: 3",
115
+ "Programming Language :: Python :: 3.6",
116
+ "Programming Language :: Python :: 3.7",
117
+ "Programming Language :: Python :: 3.8",
118
+ ],
119
+ description="Machine Learning with uncertainty quantification and interpretability",
120
+ install_requires=['numpy', 'pandas', 'rpy2>=3.4.5', 'scikit-learn', 'scipy'],
121
+ license="BSD Clause Clear license",
122
+ long_description="Machine Learning with uncertainty quantification and interpretability.",
123
+ include_package_data=True,
124
+ keywords="learningmachine",
125
+ name="learningmachine",
126
+ packages=find_packages(include=["learningmachine", "learningmachine.*"]),
127
+ test_suite="tests",
128
+ url="https://github.com/Techtonique/learningmachine_python",
129
+ version="0.2.3",
130
+ zip_safe=False,
131
+ )
@@ -1,18 +0,0 @@
1
- from rpy2.robjects import r
2
- from rpy2.robjects.packages import importr
3
- from .utils import check_install_r_pkg
4
-
5
- base = importr("base")
6
- stats = importr("stats")
7
-
8
-
9
- class Base(object):
10
- """
11
- Base class.
12
- """
13
-
14
- def __init__(self):
15
- """
16
- Initialize the model.
17
- """
18
- self.obj = None
@@ -1,112 +0,0 @@
1
- from subprocess import run
2
- from rpy2.robjects import r
3
- from rpy2.robjects.packages import importr
4
- from rpy2.robjects.vectors import (
5
- FloatMatrix,
6
- FloatVector,
7
- IntVector,
8
- StrVector,
9
- )
10
-
11
- from sklearn.base import BaseEstimator, RegressorMixin, ClassifierMixin
12
- from .base import Base
13
-
14
- base = importr("base")
15
- stats = importr("stats")
16
- utils = importr("utils")
17
-
18
-
19
- class BaseRegressor(Base, BaseEstimator, RegressorMixin):
20
- """
21
- Base Regressor.
22
- """
23
-
24
- def __init__(self):
25
- """
26
- Initialize the model.
27
- """
28
-
29
- super(Base, self).__init__()
30
-
31
- try:
32
- self.obj = r("learningmachine::BaseRegressor$new()")
33
- except NotImplementedError as e: # doesn't work yet
34
- self.obj = run(
35
- ["Rscript", "-e", "learningmachine::BaseRegressor$new()"],
36
- capture_output=True,
37
- )
38
-
39
- def fit(self, X, y):
40
- """
41
- Fit the model according to the given training data.
42
- """
43
- self.obj["fit"](
44
- r.matrix(
45
- FloatVector(X), byrow=True, nrow=X.shape[0], ncol=X.shape[1]
46
- ),
47
- FloatVector(y),
48
- )
49
- return self
50
-
51
- def predict(self, X):
52
- """
53
- Predict using the model.
54
- """
55
- return self.obj["predict"](
56
- r.matrix(
57
- FloatMatrix(X), byrow=True, nrow=X.shape[0], ncol=X.shape[1]
58
- )
59
- )
60
-
61
-
62
- class BaseClassifier(Base, BaseEstimator, ClassifierMixin):
63
- """
64
- Base Classifier.
65
- """
66
-
67
- def __init__(self):
68
- """
69
- Initialize the model.
70
- """
71
-
72
- super(Base, self).__init__()
73
-
74
- try:
75
- self.obj = r("learningmachine::BaseClassifier$new()")
76
- except NotImplementedError as e: # doesn't work yet
77
- self.obj = run(
78
- ["Rscript", "-e", "learningmachine::BaseClassifier$new()"],
79
- capture_output=True,
80
- )
81
-
82
- def fit(self, X, y):
83
- """
84
- Fit the model according to the given training data.
85
- """
86
- self.obj["fit"](
87
- r.matrix(
88
- FloatMatrix(X), byrow=True, nrow=X.shape[0], ncol=X.shape[1]
89
- ),
90
- base.as_factor(IntVector(y)),
91
- )
92
- return self
93
-
94
- def predict(self, X):
95
- """
96
- Predict classes using the model.
97
- """
98
- return self.obj["predict"](
99
- r.matrix(
100
- FloatMatrix(X), byrow=True, nrow=X.shape[0], ncol=X.shape[1]
101
- )
102
- )
103
-
104
- def predict_proba(self, X):
105
- """
106
- Predict probabilities using the model.
107
- """
108
- return self.obj["predict_proba"](
109
- r.matrix(
110
- FloatMatrix(X), byrow=True, nrow=X.shape[0], ncol=X.shape[1]
111
- )
112
- )
@@ -1,175 +0,0 @@
1
- #!/usr/bin/env python
2
-
3
- # 1 - import Python packages -----------------------------------------------
4
-
5
- import platform
6
- import subprocess
7
- from os import path
8
- from rpy2.robjects.packages import importr
9
- from setuptools import setup, find_packages
10
- from rpy2.robjects.vectors import StrVector
11
- from rpy2.robjects import r
12
-
13
- # 2 - utility functions -----------------------------------------------
14
-
15
- def check_r_installed():
16
- current_platform = platform.system()
17
-
18
- if current_platform == "Windows":
19
- # Check if R is installed on Windows by checking the registry
20
- try:
21
- subprocess.run(
22
- ["reg", "query", "HKLM\\Software\\R-core\\R"], check=True
23
- )
24
- print("R is already installed on Windows.")
25
- return True
26
- except subprocess.CalledProcessError:
27
- print("R is not installed on Windows.")
28
- return False
29
-
30
- elif current_platform == "Linux":
31
- # Check if R is installed on Linux by checking if the 'R' executable is available
32
- try:
33
- subprocess.run(["which", "R"], check=True)
34
- print("R is already installed on Linux.")
35
- return True
36
- except subprocess.CalledProcessError:
37
- print("R is not installed on Linux.")
38
- return False
39
-
40
- elif current_platform == "Darwin": # macOS
41
- # Check if R is installed on macOS by checking if the 'R' executable is available
42
- try:
43
- subprocess.run(["which", "R"], check=True)
44
- print("R is already installed on macOS.")
45
- return True
46
- except subprocess.CalledProcessError:
47
- print("R is not installed on macOS.")
48
- return False
49
-
50
- else:
51
- print("Unsupported platform. Unable to check for R installation.")
52
- return False
53
-
54
-
55
- def install_r():
56
- current_platform = platform.system()
57
-
58
- if current_platform == "Windows":
59
- # Install R on Windows using PowerShell
60
- install_command = "Start-Process powershell -Verb runAs -ArgumentList '-Command \"& {Invoke-WebRequest https://cran.r-project.org/bin/windows/base/R-4.1.2-win.exe -OutFile R.exe}; Start-Process R.exe -ArgumentList '/SILENT' -Wait}'"
61
- subprocess.run(install_command, shell=True)
62
-
63
- elif current_platform == "Linux":
64
- # Install R on Linux using the appropriate package manager (e.g., apt-get)
65
- install_command = (
66
- "sudo apt update -qq && sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys E298A3A825C0D65DFD57CBB651716619E084DAB9"
67
- + "&& sudo add-apt-repository 'deb https://cloud.r-project.org/bin/linux/ubuntu focal-cran40/'"
68
- + "&& sudo apt update"
69
- + "&& sudo apt install r-base"
70
- )
71
- subprocess.run(install_command, shell=True)
72
-
73
- elif current_platform == "Darwin": # macOS
74
- # Install R on macOS using Homebrew
75
- install_command = "brew install r"
76
- subprocess.run(install_command, shell=True)
77
-
78
- else:
79
- print("Unsupported platform. Unable to install R.")
80
-
81
- # 3 - Install packages -----------------------------------------------
82
-
83
- # Check if R is installed; if not, install it
84
- if not check_r_installed():
85
- print("Installing R...")
86
- install_r()
87
- else:
88
- print("No installation needed.")
89
-
90
- # Install R packages
91
- commands1_lm = 'base::system.file(package = "learningmachine")' # check is installed
92
- commands2_lm = 'base::system.file("learningmachine_r", package = "learningmachine")' # check is installed locally
93
- exec_commands1_lm = subprocess.run(['Rscript', '-e', commands1_lm], capture_output=True, text=True)
94
- exec_commands2_lm = subprocess.run(['Rscript', '-e', commands2_lm], capture_output=True, text=True)
95
- if (len(exec_commands1_lm.stdout) == 7 and len(exec_commands2_lm.stdout) == 7): # kind of convoluted, but works
96
- print("Installing R packages...")
97
- commands1 = ['try(utils::install.packages("R6", repos="https://cloud.r-project.org", dependencies = TRUE), silent=FALSE)',
98
- 'try(utils::install.packages("Rcpp", repos="https://cloud.r-project.org", dependencies = TRUE), silent=FALSE)',
99
- 'try(utils::install.packages("skimr", repos="https://cloud.r-project.org", dependencies = TRUE), silent=FALSE)',
100
- 'try(utils::install.packages("learningmachine", repos="https://techtonique.r-universe.dev", dependencies = TRUE), silent=FALSE)']
101
- commands2 = ['try(utils::install.packages("R6", lib="./learningmachine_r", repos="https://cloud.r-project.org", dependencies = TRUE), silent=FALSE)',
102
- 'try(utils::install.packages("Rcpp", lib="./learningmachine_r", repos="https://cloud.r-project.org", dependencies = TRUE), silent=FALSE)',
103
- 'try(utils::install.packages("skimr", lib="./learningmachine_r", repos="https://cloud.r-project.org", dependencies = TRUE), silent=FALSE)',
104
- 'try(utils::install.packages("learningmachine", lib="./learningmachine_r", repos="https://techtonique.r-universe.dev", dependencies = TRUE), silent=FALSE)']
105
- try:
106
- for cmd in commands1:
107
- subprocess.run(['Rscript', '-e', cmd])
108
- except Exception as e:
109
- subprocess.run(['mkdir', 'learningmachine_r'])
110
- for cmd in commands2:
111
- subprocess.run(['Rscript', '-e', cmd])
112
-
113
- base = importr("base")
114
-
115
- try:
116
- base.library(StrVector(["learningmachine"]))
117
- except Exception as e1:
118
- try:
119
- base.library(
120
- StrVector(["learningmachine"]), lib_loc="learningmachine_r"
121
- )
122
- except Exception as e2:
123
- try:
124
- r("try(library('learningmachine'), silence=TRUE)")
125
- except NotImplementedError as e3:
126
- r(
127
- "try(library('learningmachine', lib.loc='learningmachine_r'), silence=TRUE)"
128
- )
129
-
130
-
131
- """The setup script."""
132
- here = path.abspath(path.dirname(__file__))
133
-
134
- # get the dependencies and installs
135
- with open(
136
- path.join(here, "requirements.txt"), encoding="utf-8"
137
- ) as f:
138
- all_reqs = f.read().split("\n")
139
-
140
- install_requires = [
141
- x.strip() for x in all_reqs if "git+" not in x
142
- ]
143
- dependency_links = [
144
- x.strip().replace("git+", "")
145
- for x in all_reqs
146
- if x.startswith("git+")
147
- ]
148
-
149
- setup(
150
- author="T. Moudiki",
151
- author_email='thierry.moudiki@gmail.com',
152
- python_requires='>=3.6',
153
- classifiers=[
154
- 'Development Status :: 2 - Pre-Alpha',
155
- 'Intended Audience :: Developers',
156
- 'License :: OSI Approved :: BSD License',
157
- 'Natural Language :: English',
158
- 'Programming Language :: Python :: 3',
159
- 'Programming Language :: Python :: 3.6',
160
- 'Programming Language :: Python :: 3.7',
161
- 'Programming Language :: Python :: 3.8',
162
- ],
163
- description="Machine Learning with uncertainty quantification and interpretability",
164
- install_requires=install_requires,
165
- license="BSD Clause Clear license",
166
- long_description="Machine Learning with uncertainty quantification and interpretability.",
167
- include_package_data=True,
168
- keywords='learningmachine',
169
- name='learningmachine',
170
- packages=find_packages(include=['learningmachine', 'learningmachine.*']),
171
- test_suite='tests',
172
- url='https://github.com/Techtonique/learningmachine',
173
- version='0.2.2',
174
- zip_safe=False,
175
- )
File without changes