least squares

Introduction

This will only work if you have Mathematica installed in your machine. Python can interface with Wolfram Mathematica, taking advantage of its awesome power.

The curve inside the square is a parabola: $$ y = ax^2 + bx + c $$

This parabola passes through the points $(0.3, 0)$ and $(1, 1)$, and it's derivative at $(0.3, 0)$ is zero. We use Mathematica to figure out what are the parameters $a,b,c$. Finally, we transpose the line when plotting, i.e., $x$ is in the vertical axis, and $y$ is in the horizontal axis.

The code

%matplotlib inline

import matplotlib.pyplot as plt
import numpy as np
from wolframclient.language import wl
from wolframclient.evaluation import WolframLanguageSession
from wolframclient.language import wl, wlexpr

w = 20
plt.rc('axes', linewidth=w)
fig=plt.figure(1, (5, 5))

fig.subplots_adjust(left=0.0, right=1.0, top=1.0, bottom=0.0,
                    hspace=0, wspace=0)
ax = plt.Axes(fig, [0., 0., 1., 1.])
fig.add_axes(ax)

session = WolframLanguageSession()
session.evaluate(wlexpr('y[x_] := a x^2 + b x + c'))
session.evaluate(wlexpr('p1 = {0.3, 0}'))
session.evaluate(wlexpr('p2 = {1, 1}'))
session.evaluate(wlexpr('sol1 = Solve[ {y[p1[[1]]] == p1[[2]],  y[p2[[1]]] == p2[[2]]}, {a, b, c}][[1]]'))
session.evaluate(wlexpr('sol2 = Solve[(D[(y[x] /. sol1), x] /. x -> 0.3) == 0, a][[1]]'))
par = list(session.evaluate(wlexpr('{a, b, c} /. sol1 /. sol2')))

x0 = 0.3
x=np.linspace(x0, 1, 1001)
a, b, c = par# [2.08163, -1.24898, 0.167347]
y = lambda x: a*x**2 + b*x + c

c1 = 'white'  # bottom right
c2 = 'white'  # top left



# c1 = '#6c7053'  # bottom right
# c2 = '#6e0014'  # top left
# ax.fill_between(y(x), x, y2=0, facecolor=c1,
#                 edgecolor='black') # bottom right
# ax.fill_between(y(x), x, y2=1, facecolor=c2,
#                 edgecolor="black", linewidth=10) # top left

ax.plot(y(x), x, color="black", lw=w)

ax.set_xlim([0,1])
ax.set_ylim([0,1])
ax.set_xticks([])
ax.set_yticks([])

fig.savefig("./python_figures/site-logo.png", resolution=600, transparent=True, bbox_inches="tight")
fig.savefig("./python_figures/site-logo.svg")
plt.show()
Equations may not give solutions for all "solve" variables.
Equations may not give solutions for all "solve" variables.
session = WolframLanguageSession()
session.evaluate(wlexpr('y[x_] := a x^2 + b x + c'))
session.evaluate(wlexpr('p1 = {0.3, -0.02}'))
session.evaluate(wlexpr('p2 = {1, 1}'))
session.evaluate(wlexpr('sol1 = Solve[ {y[p1[[1]]] == p1[[2]],  y[p2[[1]]] == p2[[2]]}, {a, b, c}][[1]]'))
session.evaluate(wlexpr('sol2 = Solve[(D[(y[x] /. sol1), x] /. x -> 0.3) == 0, a][[1]]'))
par = list(session.evaluate(wlexpr('{a, b, c} /. sol1 /. sol2')))
Equations may not give solutions for all "solve" variables.
Equations may not give solutions for all "solve" variables.
par
[2.0816326530612246, -1.2489795918367346, 0.16734693877551027]