import numpy as np
import matplotlib.pyplot as plt
import os

os.makedirs("img", exist_ok=True)

fig, ax = plt.subplots(figsize=(7.0, 5.2))

O  = np.array([0.0, 0.0])   # mass M sits at the origin
rm = np.array([3.5, 2.2])   # position of mass m

def arrow(p, q, color, lw=2.0):
    ax.annotate("", xy=q, xytext=p,
                arrowprops=dict(arrowstyle="-|>", color=color, lw=lw,
                                shrinkA=0, shrinkB=0, mutation_scale=18))

rhat = rm / np.linalg.norm(rm)
n    = np.array([-rhat[1], rhat[0]])   # unit normal to the line joining

# position vector r_ij from m_i (origin) to m_j
arrow(O, rm, "#1f77b4")
# attractive force on m_i due to m_j: acts at m_i and points toward m_j,
# offset slightly so it stays clear of the position vector
off = 0.25 * n
arrow(O + off, O + 1.3 * rhat + off, "#7e22ce", lw=2.8)

# masses
ax.scatter(*O, s=170, color="#2ca02c", zorder=5)
ax.text(O[0] - 0.12, O[1] - 0.36, r"$m_i$", color="#2ca02c", fontsize=18, weight="bold")
ax.scatter(*rm, s=95, color="#1f77b4", zorder=5)
ax.text(rm[0] + 0.14, rm[1] + 0.12, r"$m_j$", color="#1f77b4", fontsize=18)

# vector labels
ax.text(*(0.5 * rm + np.array([-0.45, 0.14])), r"$\mathbf{r}_{ij}$", color="#1f77b4", fontsize=18)
ax.text(*(0.75 * rhat + off + np.array([-0.30, 0.16])),
        r"$\mathbf{F}_{ij}$", color="#7e22ce", fontsize=18)

ax.set_xlim(-0.9, 4.4)
ax.set_ylim(-0.8, 3.1)
ax.set_aspect("equal")
ax.axis("off")
plt.tight_layout()
fig.savefig("img/fig-gravity-force.png", dpi=160, bbox_inches="tight")
plt.close(fig)
