MilesCranmer commited on
Commit
b896bd3
1 Parent(s): c822df8

Mypy compatibility

Browse files
.github/workflows/CI.yml CHANGED
@@ -143,3 +143,29 @@ jobs:
143
  run: |
144
  pip install coveralls
145
  coveralls --finish
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
143
  run: |
144
  pip install coveralls
145
  coveralls --finish
146
+
147
+ types:
148
+ name: Check types
149
+ runs-on: ubuntu-latest
150
+ defaults:
151
+ run:
152
+ shell: bash -l {0}
153
+ strategy:
154
+ matrix:
155
+ python-version: ['3.10']
156
+
157
+ steps:
158
+ - uses: actions/checkout@v3
159
+ - name: "Set up Python"
160
+ uses: actions/setup-python@v4
161
+ with:
162
+ python-version: ${{ matrix.python-version }}
163
+ cache: pip
164
+ - name: "Install PySR and all dependencies"
165
+ run: |
166
+ python -m pip install --upgrade pip
167
+ pip install -r requirements.txt
168
+ pip install mypy jax jaxlib torch
169
+ python setup.py install
170
+ - name: "Run mypy"
171
+ run: mypy --install-types --non-interactive pysr
mypy.ini ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ [mypy]
2
+ warn_return_any = True
3
+
4
+ [mypy-sklearn.*]
5
+ ignore_missing_imports = True
6
+
7
+ [mypy-julia.*]
8
+ ignore_missing_imports = True
pysr/export_latex.py CHANGED
@@ -1,5 +1,5 @@
1
  """Functions to help export PySR equations to LaTeX."""
2
- from typing import List
3
 
4
  import pandas as pd
5
  import sympy
@@ -19,14 +19,16 @@ class PreciseLatexPrinter(LatexPrinter):
19
  return super()._print_Float(reduced_float)
20
 
21
 
22
- def sympy2latex(expr, prec=3, full_prec=True, **settings):
23
  """Convert sympy expression to LaTeX with custom precision."""
24
  settings["full_prec"] = full_prec
25
  printer = PreciseLatexPrinter(settings=settings, prec=prec)
26
  return printer.doprint(expr)
27
 
28
 
29
- def generate_table_environment(columns=["equation", "complexity", "loss"]):
 
 
30
  margins = "c" * len(columns)
31
  column_map = {
32
  "complexity": "Complexity",
@@ -58,12 +60,12 @@ def generate_table_environment(columns=["equation", "complexity", "loss"]):
58
 
59
  def sympy2latextable(
60
  equations: pd.DataFrame,
61
- indices: List[int] = None,
62
  precision: int = 3,
63
- columns=["equation", "complexity", "loss", "score"],
64
  max_equation_length: int = 50,
65
  output_variable_name: str = "y",
66
- ):
67
  """Generate a booktabs-style LaTeX table for a single set of equations."""
68
  assert isinstance(equations, pd.DataFrame)
69
 
@@ -71,7 +73,7 @@ def sympy2latextable(
71
  latex_table_content = []
72
 
73
  if indices is None:
74
- indices = range(len(equations))
75
 
76
  for i in indices:
77
  latex_equation = sympy2latex(
@@ -126,11 +128,11 @@ def sympy2latextable(
126
 
127
  def sympy2multilatextable(
128
  equations: List[pd.DataFrame],
129
- indices: List[List[int]] = None,
130
  precision: int = 3,
131
- columns=["equation", "complexity", "loss", "score"],
132
- output_variable_names: str = None,
133
- ):
134
  """Generate multiple latex tables for a list of equation sets."""
135
  # TODO: Let user specify custom output variable
136
 
 
1
  """Functions to help export PySR equations to LaTeX."""
2
+ from typing import List, Optional, Tuple
3
 
4
  import pandas as pd
5
  import sympy
 
19
  return super()._print_Float(reduced_float)
20
 
21
 
22
+ def sympy2latex(expr, prec=3, full_prec=True, **settings) -> str:
23
  """Convert sympy expression to LaTeX with custom precision."""
24
  settings["full_prec"] = full_prec
25
  printer = PreciseLatexPrinter(settings=settings, prec=prec)
26
  return printer.doprint(expr)
27
 
28
 
29
+ def generate_table_environment(
30
+ columns: List[str] = ["equation", "complexity", "loss"]
31
+ ) -> Tuple[str, str]:
32
  margins = "c" * len(columns)
33
  column_map = {
34
  "complexity": "Complexity",
 
60
 
61
  def sympy2latextable(
62
  equations: pd.DataFrame,
63
+ indices: Optional[List[int]] = None,
64
  precision: int = 3,
65
+ columns: List[str] = ["equation", "complexity", "loss", "score"],
66
  max_equation_length: int = 50,
67
  output_variable_name: str = "y",
68
+ ) -> str:
69
  """Generate a booktabs-style LaTeX table for a single set of equations."""
70
  assert isinstance(equations, pd.DataFrame)
71
 
 
73
  latex_table_content = []
74
 
75
  if indices is None:
76
+ indices = list(equations.index)
77
 
78
  for i in indices:
79
  latex_equation = sympy2latex(
 
128
 
129
  def sympy2multilatextable(
130
  equations: List[pd.DataFrame],
131
+ indices: Optional[List[List[int]]] = None,
132
  precision: int = 3,
133
+ columns: List[str] = ["equation", "complexity", "loss", "score"],
134
+ output_variable_names: Optional[List[str]] = None,
135
+ ) -> str:
136
  """Generate multiple latex tables for a list of equation sets."""
137
  # TODO: Let user specify custom output variable
138
 
pysr/export_sympy.py CHANGED
@@ -51,14 +51,14 @@ sympy_mappings = {
51
 
52
 
53
  def create_sympy_symbols(
54
- feature_names_in: Optional[List[str]] = None,
55
  ) -> List[sympy.Symbol]:
56
  return [sympy.Symbol(variable) for variable in feature_names_in]
57
 
58
 
59
  def pysr2sympy(
60
  equation: str, *, extra_sympy_mappings: Optional[Dict[str, Callable]] = None
61
- ) -> sympy.Expr:
62
  local_sympy_mappings = {
63
  **(extra_sympy_mappings if extra_sympy_mappings else {}),
64
  **sympy_mappings,
 
51
 
52
 
53
  def create_sympy_symbols(
54
+ feature_names_in: List[str],
55
  ) -> List[sympy.Symbol]:
56
  return [sympy.Symbol(variable) for variable in feature_names_in]
57
 
58
 
59
  def pysr2sympy(
60
  equation: str, *, extra_sympy_mappings: Optional[Dict[str, Callable]] = None
61
+ ):
62
  local_sympy_mappings = {
63
  **(extra_sympy_mappings if extra_sympy_mappings else {}),
64
  **sympy_mappings,
pysr/feature_selection.py CHANGED
@@ -2,7 +2,7 @@
2
  import numpy as np
3
 
4
 
5
- def run_feature_selection(X, y, select_k_features, random_state=None) -> np.ndarray:
6
  """
7
  Find most important features.
8
 
 
2
  import numpy as np
3
 
4
 
5
+ def run_feature_selection(X, y, select_k_features, random_state=None):
6
  """
7
  Find most important features.
8
 
pysr/sr.py CHANGED
@@ -11,6 +11,7 @@ from datetime import datetime
11
  from io import StringIO
12
  from multiprocessing import cpu_count
13
  from pathlib import Path
 
14
 
15
  import numpy as np
16
  import pandas as pd
@@ -1781,10 +1782,10 @@ class PySRRegressor(MultiOutputMixin, RegressorMixin, BaseEstimator):
1781
  y,
1782
  Xresampled=None,
1783
  weights=None,
1784
- variable_names=None,
1785
- X_units=None,
1786
- y_units=None,
1787
- ):
1788
  """
1789
  Search for equations to fit the dataset and store them in `self.equations_`.
1790
 
@@ -2371,7 +2372,7 @@ class PySRRegressor(MultiOutputMixin, RegressorMixin, BaseEstimator):
2371
  return "\n".join(preamble_string + [table_string])
2372
 
2373
 
2374
- def idx_model_selection(equations: pd.DataFrame, model_selection: str) -> int:
2375
  """Select an expression and return its index."""
2376
  if model_selection == "accuracy":
2377
  chosen_idx = equations["loss"].idxmin()
 
11
  from io import StringIO
12
  from multiprocessing import cpu_count
13
  from pathlib import Path
14
+ from typing import List, Optional
15
 
16
  import numpy as np
17
  import pandas as pd
 
1782
  y,
1783
  Xresampled=None,
1784
  weights=None,
1785
+ variable_names: Optional[List[str]] = None,
1786
+ X_units: Optional[List[str]] = None,
1787
+ y_units: Optional[List[str]] = None,
1788
+ ) -> "PySRRegressor":
1789
  """
1790
  Search for equations to fit the dataset and store them in `self.equations_`.
1791
 
 
2372
  return "\n".join(preamble_string + [table_string])
2373
 
2374
 
2375
+ def idx_model_selection(equations: pd.DataFrame, model_selection: str):
2376
  """Select an expression and return its index."""
2377
  if model_selection == "accuracy":
2378
  chosen_idx = equations["loss"].idxmin()