File size: 5,015 Bytes
a3c36fd
db41bee
4207871
b7541ec
db41bee
 
 
4207871
d710548
 
 
 
 
 
 
e57f927
ad5d094
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31db34d
bc45490
db41bee
ad5d094
 
 
bc45490
f671264
bc45490
 
5c5efaf
bc45490
ad5d094
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc45490
ad5d094
 
 
 
 
db41bee
 
25e01ad
db41bee
 
 
 
bdc21cd
31db34d
db41bee
 
 
 
 
 
23b96e5
 
 
 
db41bee
 
 
 
 
 
23b96e5
 
e57f927
db41bee
 
e57f927
23b96e5
bc45490
 
 
35a24b2
bc45490
e893f23
ad5d094
 
 
 
 
 
 
 
 
e893f23
bc45490
 
e893f23
2b58e9e
eba77c5
2b58e9e
e893f23
2b58e9e
 
e893f23
eba77c5
 
bc45490
e893f23
bc45490
 
e893f23
bc45490
e893f23
02bac7f
 
 
 
 
 
 
 
 
 
 
bc45490
e893f23
bc45490
e893f23
 
5c5efaf
02bac7f
bc45490
7e5c64b
33354da
e893f23
7e5c64b
bc45490
 
4207871
bc45490
4207871
a3c36fd
bc45490
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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
103
104
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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
import gradio as gr
import numpy as np
import os
import pandas as pd
import pysr
import tempfile
from typing import Optional

empty_df = pd.DataFrame(
    {
        "equation": [],
        "loss": [],
        "complexity": [],
    }
)

test_equations = {
    "Complex Polynomial": "3*x^3 + 2*x^2 - x + sin(x)",
    "Exponential and Logarithmic": "exp(-x) + log(x+1)",
    "Trigonometric Polynomial": "sin(x) + cos(2*x) + tan(x/3)",
    "Mixed Functions": "sqrt(x)*exp(-x) + cos(pi*x)",
    "Rational Function": "(x^2 + 1) / (x - 2)",
}


def generate_data(equation: str, num_points: int, noise_level: float):
    x = np.linspace(-10, 10, num_points)
    s = test_equations[equation]
    for (k, v) in {
        "sin": "np.sin",
        "cos": "np.cos",
        "exp": "np.exp",
        "log": "np.log",
        "tan": "np.tan",
        "^": "**",
    }.items():
        s = s.replace(k, v)
    y = eval(s)
    noise = np.random.normal(0, noise_level, y.shape)
    y_noisy = y + noise
    return pd.DataFrame({"x": x}), y_noisy


def greet(
    file_obj: Optional[tempfile._TemporaryFileWrapper],
    test_equation: str,
    num_points: int,
    noise_level: float,
    niterations: int,
    maxsize: int,
    binary_operators: list,
    unary_operators: list,
    force_run: bool,
):
    if file_obj is not None:
        if len(binary_operators) == 0 and len(unary_operators) == 0:
            return (
                empty_df,
                "Please select at least one operator!",
            )
        # Look at some statistics of the file:
        df = pd.read_csv(file_obj)
        if len(df) == 0:
            return (
                empty_df,
                "The file is empty!",
            )
        if len(df.columns) == 1:
            return (
                empty_df,
                "The file has only one column!",
            )
        if len(df) > 10_000 and not force_run:
            return (
                empty_df,
                "You have uploaded a file with more than 10,000 rows. "
                "This will take very long to run. "
                "Please upload a subsample of the data, "
                "or check the box 'Ignore Warnings'.",
            )

        col_to_fit = df.columns[-1]
        y = np.array(df[col_to_fit])
        X = df.drop([col_to_fit], axis=1)
    else:
        X, y = generate_data(test_equation, num_points, noise_level)

    model = pysr.PySRRegressor(
        bumper=True,
        maxsize=maxsize,
        niterations=niterations,
        binary_operators=binary_operators,
        unary_operators=unary_operators,
        timeout_in_seconds=1000,
    )
    model.fit(X, y)

    df = model.equations_[["equation", "loss", "complexity"]]
    # Convert all columns to string type:
    df = df.astype(str)
    msg = (
        "Success!\n"
        f"You may run the model locally (faster) with "
        f"the following parameters:"
        + f"""
model = PySRRegressor(
    niterations={niterations},
    binary_operators={str(binary_operators)},
    unary_operators={str(unary_operators)},
    maxsize={maxsize},
)
model.fit(X, y)"""
    )

    df.to_csv("pysr_output.csv", index=False)
    return df, msg


def main():
    demo = gr.Interface(
        fn=greet,
        description="Symbolic Regression with PySR. Watch search progress by following the logs.",
        inputs=[
            gr.File(label="Upload a CSV File"),
            gr.Radio(list(test_equations.keys()), label="Test Equation"),
            gr.Slider(
                minimum=10,
                maximum=1000,
                value=100,
                label="Number of Data Points",
                step=1,
            ),
            gr.Slider(minimum=0, maximum=1, value=0.1, label="Noise Level"),
            gr.Slider(
                minimum=1,
                maximum=1000,
                value=40,
                label="Number of Iterations",
                step=1,
            ),
            gr.Slider(
                minimum=7,
                maximum=35,
                value=20,
                label="Maximum Complexity",
                step=1,
            ),
            gr.CheckboxGroup(
                choices=["+", "-", "*", "/", "^"],
                label="Binary Operators",
                value=["+", "-", "*", "/"],
            ),
            gr.CheckboxGroup(
                choices=[
                    "sin",
                    "cos",
                    "exp",
                    "log",
                    "square",
                    "cube",
                    "sqrt",
                    "abs",
                    "tan",
                ],
                label="Unary Operators",
                value=[],
            ),
            gr.Checkbox(
                value=False,
                label="Ignore Warnings",
            ),
        ],
        outputs=[
            "dataframe",
            gr.Textbox(label="Error Log"),
        ],
    )
    # Add file to the demo:

    demo.launch()


if __name__ == "__main__":
    main()