pyeggp 1.0.0__cp311-cp311-macosx_14_0_x86_64.whl

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.
Binary file
pyeggp/__init__.py ADDED
@@ -0,0 +1,114 @@
1
+ import atexit
2
+ from contextlib import contextmanager
3
+ from threading import Lock
4
+ from typing import Iterator, List
5
+ from io import StringIO
6
+ import tempfile
7
+ import csv
8
+
9
+ import numpy as np
10
+ import pandas as pd
11
+ from sklearn.base import BaseEstimator, RegressorMixin
12
+ from sklearn.utils.validation import check_X_y, check_array, check_is_fitted
13
+ from sklearn.metrics import mean_squared_error, r2_score
14
+
15
+ from ._binding import (
16
+ unsafe_hs_pyeggp_version,
17
+ unsafe_hs_pyeggp_main,
18
+ unsafe_hs_pyeggp_run,
19
+ unsafe_hs_pyeggp_init,
20
+ unsafe_hs_pyeggp_exit,
21
+ )
22
+
23
+ VERSION: str = "1.3.0"
24
+
25
+
26
+ _hs_rts_init: bool = False
27
+ _hs_rts_lock: Lock = Lock()
28
+
29
+
30
+ def hs_rts_exit() -> None:
31
+ global _hs_rts_lock
32
+ with _hs_rts_lock:
33
+ unsafe_hs_pyeggp_exit()
34
+
35
+
36
+ @contextmanager
37
+ def hs_rts_init(args: List[str] = []) -> Iterator[None]:
38
+ global _hs_rts_init
39
+ global _hs_rts_lock
40
+ with _hs_rts_lock:
41
+ if not _hs_rts_init:
42
+ _hs_rts_init = True
43
+ unsafe_hs_pyeggp_init(args)
44
+ atexit.register(hs_rts_exit)
45
+ yield None
46
+
47
+
48
+ def version() -> str:
49
+ with hs_rts_init():
50
+ return unsafe_hs_pyeggp_version()
51
+
52
+
53
+ def main(args: List[str] = []) -> int:
54
+ with hs_rts_init(args):
55
+ return unsafe_hs_pyeggp_main()
56
+
57
+ def pyeggp_run(dataset: str, gen: int, nPop: int, maxSize: int, nTournament: int, pc: float, pm: float, nonterminals: str, loss: str, optIter: int, optRepeat: int, nParams: int, split: int, simplify: int, dumpTo: str, loadFrom: str) -> str:
58
+ with hs_rts_init():
59
+ return unsafe_hs_pyeggp_run(dataset, gen, nPop, maxSize, nTournament, pc, pm, nonterminals, loss, optIter, optRepeat, nParams, split, simplify, dumpTo, loadFrom)
60
+
61
+ class PyEGGP(BaseEstimator, RegressorMixin):
62
+ def __init__(self, gen = 100, nPop = 100, maxSize = 15, nTournament = 3, pc = 0.9, pm = 0.3, nonterminals = "add,sub,mul,div", loss = "MSE", optIter = 50, optRepeat = 2, nParams = -1, split = 1, simplify = False, dumpTo = "", loadFrom = ""):
63
+ self.gen = gen
64
+ self.nPop = nPop
65
+ self.maxSize = maxSize
66
+ self.nTournament = nTournament
67
+ self.pc = pc
68
+ self.pm = pm
69
+ self.nonterminals = nonterminals
70
+ self.loss = loss
71
+ self.optIter = optIter
72
+ self.optRepeat = optRepeat
73
+ self.nParams = nParams
74
+ self.split = split
75
+ self.simplify = int(simplify)
76
+ self.dumpTo = dumpTo
77
+ self.loadFrom = loadFrom
78
+ self.is_fitted_ = False
79
+
80
+ def fit(self, X, y):
81
+ if X.ndim == 1:
82
+ X = X.reshape(-1,1)
83
+ y = y.reshape(-1, 1)
84
+ combined = np.hstack([X, y])
85
+ header = [f"x{i}" for i in range(X.shape[1])] + ["y"]
86
+ with tempfile.NamedTemporaryFile(mode='w+', newline='', delete=False, suffix='.csv') as temp_file:
87
+ writer = csv.writer(temp_file)
88
+ writer.writerow(header)
89
+ writer.writerows(combined)
90
+ dataset = temp_file.name
91
+
92
+ csv_data = pyeggp_run(dataset, self.gen, self.nPop, self.maxSize, self.nTournament, self.pc, self.pm, self.nonterminals, self.loss, self.optIter, self.optRepeat, self.nParams, self.split, self.simplify, self.dumpTo, self.loadFrom)
93
+ if len(csv_data) > 0:
94
+ csv_io = StringIO(csv_data.strip())
95
+ self.results = pd.read_csv(csv_io, header=0)
96
+ self.is_fitted_ = True
97
+ return self
98
+
99
+ def predict(self, X):
100
+ check_is_fitted(self)
101
+ return self.evaluate_best_model(self.model_, X)
102
+ def evaluate_best_model(self, x):
103
+ if x.ndim == 1:
104
+ x = x.reshape(-1,1)
105
+ t = np.array(list(map(float, self.results.iloc[-1].theta.split(";"))))
106
+ return eval(self.results.iloc[-1].Numpy)
107
+ def evaluate_model(self, ix, x):
108
+ if x.ndim == 1:
109
+ x = x.reshape(-1,1)
110
+ t = np.array(list(map(float, self.results.iloc[-1].theta.split(";"))))
111
+ return eval(self.results.iloc[i].Numpy)
112
+ def score(self, X, y):
113
+ ypred = self.evaluate_best_model(X)
114
+ return r2_score(y, ypred)
pyeggp/__main__.py ADDED
@@ -0,0 +1,11 @@
1
+ import sys
2
+ from typing import NoReturn
3
+ import pyeggp
4
+
5
+
6
+ def main() -> NoReturn:
7
+ sys.exit(pyeggp.main(sys.argv))
8
+
9
+
10
+ if __name__ == "__main__":
11
+ main()
Binary file
pyeggp/_binding.py ADDED
@@ -0,0 +1,20 @@
1
+ def __bootstrap__():
2
+ global __bootstrap__, __file__, __loader__
3
+ import sys, os, pkg_resources, importlib.util
4
+ __file__ = pkg_resources.resource_filename(__name__,'_binding.cpython-311-darwin.so')
5
+ del __bootstrap__
6
+ if '__loader__' in globals():
7
+ del __loader__
8
+
9
+ old_dir = os.getcwd()
10
+ try:
11
+ os.chdir(os.path.dirname(__file__))
12
+
13
+ spec = importlib.util.spec_from_file_location(
14
+ __name__, __file__)
15
+ mod = importlib.util.module_from_spec(spec)
16
+ spec.loader.exec_module(mod)
17
+ finally:
18
+
19
+ os.chdir(old_dir)
20
+ __bootstrap__()
pyeggp/_binding.pyi ADDED
@@ -0,0 +1,7 @@
1
+ from typing import List
2
+
3
+ def unsafe_hs_pyeggp_version() -> str: ...
4
+ def unsafe_hs_pyeggp_main() -> int: ...
5
+ def unsafe_hs_pyeggp_run(dataset: str, gen: int, nPop: int, maxSize: int, nTournament: int, pc: float, pm: float, nonterminals: str, loss: str, optIter: int, optRepeat: int, nParams: int, split: int, simplify: int, dumpTo: str, loadFrom: str) -> str: ...
6
+ def unsafe_hs_pyeggp_init(args: List[str]) -> None: ...
7
+ def unsafe_hs_pyeggp_exit() -> None: ...
pyeggp/binding.i ADDED
@@ -0,0 +1,64 @@
1
+ %module binding
2
+ %{
3
+ #include "Pyeggp_stub.h"
4
+
5
+ char * unsafe_hs_pyeggp_version() {
6
+ return hs_pyeggp_version();
7
+ }
8
+
9
+ int unsafe_hs_pyeggp_main() {
10
+ return hs_pyeggp_main();
11
+ }
12
+
13
+ char * unsafe_hs_pyeggp_run( char *dataset, int gens, int nPop, int maxSize, int nTournament, double pc, double pm, char *nonterminals, char *loss, int optIter, int optRepeat, int nParams, int split, int simplify, char *dumpTo, char *loadFrom ) {
14
+ return hs_pyeggp_run(dataset, gens, nPop, maxSize, nTournament, pc, pm, nonterminals, loss, optIter, optRepeat, nParams, split, simplify, dumpTo, loadFrom);
15
+ }
16
+
17
+ void unsafe_hs_pyeggp_init(int argc, char **argv) {
18
+ hs_init(&argc, &argv);
19
+ }
20
+
21
+ void unsafe_hs_pyeggp_exit() {
22
+ hs_exit();
23
+ }
24
+
25
+ void unsafe_py_write_stdout( char * str) {
26
+ PySys_FormatStdout("%s", str);
27
+ }
28
+
29
+ void unsafe_py_write_stderr( char * str) {
30
+ PySys_FormatStderr("%s", str);
31
+ }
32
+ %}
33
+
34
+ %typemap(in) (int argc, char **argv) {
35
+ /* Check if is a list */
36
+ if (PyList_Check($input)) {
37
+ int i;
38
+ $1 = PyList_Size($input);
39
+ $2 = (char **) malloc(($1+1)*sizeof(char *));
40
+ for (i = 0; i < $1; i++) {
41
+ PyObject *o = PyList_GetItem($input, i);
42
+ if (PyUnicode_Check(o)) {
43
+ $2[i] = (char *) PyUnicode_AsUTF8AndSize(o, 0);
44
+ } else {
45
+ PyErr_SetString(PyExc_TypeError, "list must contain strings");
46
+ SWIG_fail;
47
+ }
48
+ }
49
+ $2[i] = 0;
50
+ } else {
51
+ PyErr_SetString(PyExc_TypeError, "not a list");
52
+ SWIG_fail;
53
+ }
54
+ }
55
+
56
+ %typemap(freearg) (int argc, char **argv) {
57
+ free((char *) $2);
58
+ }
59
+
60
+ char * unsafe_hs_pyeggp_version();
61
+ int unsafe_hs_pyeggp_main();
62
+ char * unsafe_hs_pyeggp_run( char *dataset, int gens, int nPop, int maxSize, int nTournament, double p, double pm, char *nonterminals, char *loss, int optIter, int optRepeat, int nParams, int split, int simplify, char *dumpTo, char *loadFrom);
63
+ void unsafe_hs_pyeggp_init(int argc, char **argv);
64
+ void unsafe_hs_pyeggp_exit();
pyeggp/binding.py ADDED
@@ -0,0 +1,76 @@
1
+ # This file was automatically generated by SWIG (https://www.swig.org).
2
+ # Version 4.3.0
3
+ #
4
+ # Do not make changes to this file unless you know what you are doing - modify
5
+ # the SWIG interface file instead.
6
+
7
+ from sys import version_info as _swig_python_version_info
8
+ # Import the low-level C/C++ module
9
+ if __package__ or "." in __name__:
10
+ from . import _binding
11
+ else:
12
+ import _binding
13
+
14
+ try:
15
+ import builtins as __builtin__
16
+ except ImportError:
17
+ import __builtin__
18
+
19
+ def _swig_repr(self):
20
+ try:
21
+ strthis = "proxy of " + self.this.__repr__()
22
+ except __builtin__.Exception:
23
+ strthis = ""
24
+ return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,)
25
+
26
+
27
+ def _swig_setattr_nondynamic_instance_variable(set):
28
+ def set_instance_attr(self, name, value):
29
+ if name == "this":
30
+ set(self, name, value)
31
+ elif name == "thisown":
32
+ self.this.own(value)
33
+ elif hasattr(self, name) and isinstance(getattr(type(self), name), property):
34
+ set(self, name, value)
35
+ else:
36
+ raise AttributeError("You cannot add instance attributes to %s" % self)
37
+ return set_instance_attr
38
+
39
+
40
+ def _swig_setattr_nondynamic_class_variable(set):
41
+ def set_class_attr(cls, name, value):
42
+ if hasattr(cls, name) and not isinstance(getattr(cls, name), property):
43
+ set(cls, name, value)
44
+ else:
45
+ raise AttributeError("You cannot add class attributes to %s" % cls)
46
+ return set_class_attr
47
+
48
+
49
+ def _swig_add_metaclass(metaclass):
50
+ """Class decorator for adding a metaclass to a SWIG wrapped class - a slimmed down version of six.add_metaclass"""
51
+ def wrapper(cls):
52
+ return metaclass(cls.__name__, cls.__bases__, cls.__dict__.copy())
53
+ return wrapper
54
+
55
+
56
+ class _SwigNonDynamicMeta(type):
57
+ """Meta class to enforce nondynamic attributes (no new attributes) for a class"""
58
+ __setattr__ = _swig_setattr_nondynamic_class_variable(type.__setattr__)
59
+
60
+
61
+
62
+ def unsafe_hs_pyeggp_version():
63
+ return _binding.unsafe_hs_pyeggp_version()
64
+
65
+ def unsafe_hs_pyeggp_main():
66
+ return _binding.unsafe_hs_pyeggp_main()
67
+
68
+ def unsafe_hs_pyeggp_run(dataset, gens, nPop, maxSize, nTournament, p, pm, nonterminals, loss, optIter, optRepeat, nParams, split, simplify, dumpTo, loadFrom):
69
+ return _binding.unsafe_hs_pyeggp_run(dataset, gens, nPop, maxSize, nTournament, p, pm, nonterminals, loss, optIter, optRepeat, nParams, split, simplify, dumpTo, loadFrom)
70
+
71
+ def unsafe_hs_pyeggp_init(argc):
72
+ return _binding.unsafe_hs_pyeggp_init(argc)
73
+
74
+ def unsafe_hs_pyeggp_exit():
75
+ return _binding.unsafe_hs_pyeggp_exit()
76
+
pyeggp/typing.py ADDED
@@ -0,0 +1,14 @@
1
+ import sys
2
+
3
+ from typing import List
4
+
5
+ if sys.version_info < (3, 8):
6
+ from typing_extensions import Protocol
7
+ else:
8
+ from typing import Protocol
9
+
10
+
11
+ class Session(Protocol):
12
+ def version(self) -> str: ...
13
+ def main(self, args: List[str] = []) -> int: ...
14
+ def pyeggp_run(self, dataset: str, gen: int, nPop: int, maxSize: int, nTournament: int, pc: float, pm: float, nonterminals: str, loss: str, optIter: int, optRepeat: int, nParams: int, split: int, simplify: int, dumpTo: str, loadFrom: str) -> str: ...