-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.py
More file actions
196 lines (158 loc) · 6.44 KB
/
Copy pathindex.py
File metadata and controls
196 lines (158 loc) · 6.44 KB
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
186
187
188
189
190
191
192
193
194
195
196
import base64
import io
from flask import Flask, jsonify, request, send_from_directory
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
app = Flask(__name__, static_folder='static', static_url_path='/static')
EQUATION_DESCRIPTIONS = {
'linear': 'Single linear equation in the form y = mx + b',
'quadratic': 'Single quadratic equation in the form y = ax² + bx + c',
'pair-linear': 'Pair of linear equations in the form a₁x + b₁y + c₁ = 0 and a₂x + b₂y + c₂ = 0',
'pair-quadratic': 'Pair of quadratic equations in the form y = a₁x² + b₁x + c₁ and y = a₂x² + b₂x + c₂',
}
def _plot_to_base64(fig):
buffer = io.BytesIO()
fig.savefig(buffer, format='png', bbox_inches='tight')
buffer.seek(0)
data = base64.b64encode(buffer.read()).decode('ascii')
plt.close(fig)
return data
def _parse_coefficients(payload, names):
values = {}
for name in names:
if name not in payload:
raise ValueError(f'Missing coefficient: {name}')
try:
values[name] = float(payload[name])
except (TypeError, ValueError):
raise ValueError(f'Coefficient {name} must be a number')
return values
def _safe_range(center=0.0, span=20.0, count=400):
return np.linspace(center - span, center + span, count)
def plot_linear(coeffs):
m = coeffs['m']
b = coeffs['b']
x = _safe_range()
y = m * x + b
fig, ax = plt.subplots(figsize=(10, 5), dpi=120)
ax.plot(x, y, label=f'y = {m:.2f}x + {b:.2f}', color='#1f77b4')
ax.axhline(0, color='#333', linewidth=0.8)
ax.axvline(0, color='#333', linewidth=0.8)
ax.set_title('Linear equation graph')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.legend()
return _plot_to_base64(fig), f'Equation: y = {m:.2f}x + {b:.2f}'
def plot_quadratic(coeffs):
a = coeffs['a']
b = coeffs['b']
c = coeffs['c']
x = _safe_range()
y = a * x ** 2 + b * x + c
discriminant = b**2 - 4 * a * c
roots = 'No real roots'
if discriminant >= 0 and a != 0:
r1 = (-b + np.sqrt(discriminant)) / (2 * a)
r2 = (-b - np.sqrt(discriminant)) / (2 * a)
roots = f'Real roots at x = {r1:.2f}, {r2:.2f}'
fig, ax = plt.subplots(figsize=(10, 5), dpi=120)
ax.plot(x, y, label=f'y = {a:.2f}x² + {b:.2f}x + {c:.2f}', color='#2ca02c')
ax.axhline(0, color='#333', linewidth=0.8)
ax.axvline(0, color='#333', linewidth=0.8)
ax.set_title('Quadratic equation graph')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.legend()
return _plot_to_base64(fig), roots
def plot_pair_linear(coeffs):
a1, b1, c1 = coeffs['a1'], coeffs['b1'], coeffs['c1']
a2, b2, c2 = coeffs['a2'], coeffs['b2'], coeffs['c2']
denom = a1 * b2 - a2 * b1
if denom == 0:
raise ValueError('The two lines are parallel or coincident; no unique intersection.')
x_cross = (b1 * c2 - b2 * c1) / denom
y_cross = (a2 * c1 - a1 * c2) / denom
x = _safe_range(center=x_cross)
y1 = -(a1 * x + c1) / b1
y2 = -(a2 * x + c2) / b2
fig, ax = plt.subplots(figsize=(10, 5), dpi=120)
ax.plot(x, y1, label=f'{a1:.2f}x + {b1:.2f}y + {c1:.2f} = 0', color='#1f77b4')
ax.plot(x, y2, label=f'{a2:.2f}x + {b2:.2f}y + {c2:.2f} = 0', color='#ff7f0e')
ax.scatter([x_cross], [y_cross], color='#d62728', s=80, zorder=5)
ax.text(x_cross, y_cross, f' ({x_cross:.2f}, {y_cross:.2f})', fontsize=9, color='#d62728')
ax.axhline(0, color='#333', linewidth=0.8)
ax.axvline(0, color='#333', linewidth=0.8)
ax.set_title('Pair of linear equations')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.legend()
return _plot_to_base64(fig), f'Intersection at ({x_cross:.2f}, {y_cross:.2f})'
def plot_pair_quadratic(coeffs):
a1, b1, c1 = coeffs['a1'], coeffs['b1'], coeffs['c1']
a2, b2, c2 = coeffs['a2'], coeffs['b2'], coeffs['c2']
x = _safe_range()
y1 = a1 * x**2 + b1 * x + c1
y2 = a2 * x**2 + b2 * x + c2
da = a1 - a2
db = b1 - b2
dc = c1 - c2
discr = db**2 - 4 * da * dc
intersections = 'No real intersection points'
if da == 0 and db != 0:
xi = -dc / db
intersections = f'One intersection at x = {xi:.2f}'
elif da == 0 and db == 0:
intersections = 'The quadratics are identical or parallel.'
elif discr >= 0:
x_i1 = (-db + np.sqrt(discr)) / (2 * da)
x_i2 = (-db - np.sqrt(discr)) / (2 * da)
intersections = f'Intersections at x = {x_i1:.2f}, {x_i2:.2f}'
fig, ax = plt.subplots(figsize=(10, 5), dpi=120)
ax.plot(x, y1, label=f'y = {a1:.2f}x² + {b1:.2f}x + {c1:.2f}', color='#9467bd')
ax.plot(x, y2, label=f'y = {a2:.2f}x² + {b2:.2f}x + {c2:.2f}', color='#17becf')
ax.axhline(0, color='#333', linewidth=0.8)
ax.axvline(0, color='#333', linewidth=0.8)
ax.set_title('Pair of quadratic equations')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.legend()
return _plot_to_base64(fig), intersections
def build_response(eq_type, payload):
if eq_type == 'linear':
coeffs = _parse_coefficients(payload, ['m', 'b'])
image, text = plot_linear(coeffs)
elif eq_type == 'quadratic':
coeffs = _parse_coefficients(payload, ['a', 'b', 'c'])
image, text = plot_quadratic(coeffs)
elif eq_type == 'pair-linear':
coeffs = _parse_coefficients(payload, ['a1', 'b1', 'c1', 'a2', 'b2', 'c2'])
image, text = plot_pair_linear(coeffs)
elif eq_type == 'pair-quadratic':
coeffs = _parse_coefficients(payload, ['a1', 'b1', 'c1', 'a2', 'b2', 'c2'])
image, text = plot_pair_quadratic(coeffs)
else:
raise ValueError('Unknown equation type')
return {'image': image, 'result': text, 'description': EQUATION_DESCRIPTIONS.get(eq_type, '')}
@app.route('/')
def homepage():
return send_from_directory(app.static_folder, 'index.html')
@app.route('/api/graph', methods=['POST'])
def graph_api():
payload = request.get_json(force=True)
eq_type = payload.get('type')
if not eq_type:
return jsonify(success=False, error='No equation type provided'), 400
try:
response = build_response(eq_type, payload.get('coeffs', {}))
return jsonify(success=True, **response)
except ValueError as exc:
return jsonify(success=False, error=str(exc)), 400
@app.route('/api/code')
def code_api():
with open(__file__, 'r', encoding='utf-8') as file:
code = file.read()
return jsonify(code=code)
if __name__ == '__main__':
app.run(debug=True)