# Code examples from lab: plotting with matplotlib

# Friday, February 17 (week 4)

import random

#----------------------------------------------------------------
# file I/O without using with

def write_data(filename, numlines=100):
    file = open(filename, 'w')
    for i in range(numlines):
        a = random.uniform(-10, 10)
        b = random.uniform(50, 200)
        file.write(f"{i:5} {a:10.3f} {b:10.3f}\n")
    print(f"wrote {numlines} lines of data to {filename}")
    file.close() # don't forget!

def read_data(filename):
    file = open(filename, 'r')
    all_lines = file.readlines()
    for line in all_lines:
        x, y, z = line.split()
        i = int(x)
        a = float(y)
        b = float(z)
        print(f"{i:5} {a:10.3f} {b:10.3f}")
    file.close()

#----------------------------------------------------------------
# plotting with matplotlib

import numpy as np
import matplotlib.pyplot as plt

# x values default to 0, 1, 2, 3, 4
plt.plot([1, 4, 9, 16, 25])

# explicitly use x values 1, 2, 3, 4, 5
plt.plot([1, 2, 3, 4, 5], [1, 4, 9, 16, 25])

# two ways to create an array of x values
x = np.arange(0, 10, 0.2)    # interval size 0.2
x = np.linspace(0, 10, 100)  # 100 equally-spaced data points

# plot the function x**2 as a red solid line
plt.plot(x, x**2, 'r-')
plt.show()

# plot x**2 and x**3 on the same graph
x = np.arange(0, 10, 0.2)
plt.plot(x, x**2, 'r--')  # red dashed line
plt.plot(x, x**3, 'bo')   # blue circles
plt.xlim(0, 10)   # set x-axis min and max
plt.ylim(0, 500)  # set y-axis min and max
plt.show()

# plot the function x + |sin(8x)| from 0 < x < pi
x = np.linspace(0, np.pi, 1000)
plt.plot(x, x+np.abs(np.sin(8*x)), 'm-')
plt.title("Graph of f(x) = x + |sin(8x)|")
plt.show()

#---------------------------------------------------
# reading data from a file into a numpy array

# create a data file
write_data("mydata.txt")

data = np.loadtxt("mydata.txt")

# the first column (generation number)
data[:,0]

# the second column (average fitness)
data[:,1]

# the third column (best fitness)
data[:,2]

#---------------------------------------------------
# plot the data

def make_plot(filename):
    data = np.loadtxt(filename)
    plt.plot(data[:,0], data[:,1], 'b-', label="average fitness")
    plt.plot(data[:,0], data[:,2], 'g-', label="best fitness")
    plt.legend()
    plt.title("Experiment 1")
    plt.xlim(0, 100)
    plt.xlabel("generation")
    plt.ylim(-50, 300)
    plt.ylabel("fitness")
    plt.show()

make_plot("mydata")
