import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from os.path import exists
import scipy.stats as stats

TFILE = "../tugs.csv"
tugs = pd.read_csv(TFILE)

velocities = pd.Series([])
df = pd.DataFrame()

mmsi = tugs["MMSI"].dropna().astype(np.int32)
for idx in mmsi:
	fname = "../results-de/%s-de.csv" % str(idx)
	if not exists(fname):
		continue
	tug = pd.read_csv(fname)
	# df = pd.concat([df, tug], ignore_index=True)
	d = tug["distance"]  # meters
	t = (tug["end"] - tug["start"]) / 1000  # seconds
	v = d / t
	v.replace([np.inf, -np.inf], np.nan, inplace=True)
	v.dropna(inplace=True)
	velocities = pd.concat([velocities, v], ignore_index=True)

velocities.dropna(inplace=True)
# df.sort_values(by=["start"], inplace=True)
# df.to_csv("../results-de/IVEF.csv", index=False)

# raise 4

fig, ax1 = plt.subplots()
ax1.set_xlabel("velocity (m/s)")
ax2 = ax1.twinx()
ax1.set_ylabel("amount")
# ax2.set_ylabel("", color="tab:red")
ax2.tick_params(axis='y', labelcolor='r')

def plot(series):
	buckets = {}

	for v in series:
		vr = round(v, 6)
		buckets.setdefault(vr, 0)
		buckets[vr] += 1

	if 0 in buckets:
		del buckets[0]

	ax1.bar(buckets.keys(), buckets.values(), 0.1)
	ax1.set_ylim((0, 1.1 * max(buckets.values())))

	mu = series.mean()
	std = series.std()
	mx = int(np.ceil(series.max()))

	print(mu, std, mx)

	beta = mu / std**2
	alpha = mu * beta

	x = np.linspace(0, mx, mx * 2)
	# y1 = stats.gamma.pdf(x, a=alpha, scale=1./beta)
	y1 = stats.norm.pdf(x, mu, std)
	ax2.plot(x, y1, c='r', label=r"$\Gamma(%.3f, %.3f)$" % (mu, std))
	ax2.set_ylim((0, 1.1 * y1.max()))

plot(velocities)
plt.show()