Page MenuHomec4science

plotting.py
No OneTemporary

File Metadata

Created
Mon, May 6, 04:05

plotting.py

import numpy as np
import sys
import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
from quadratic_function import quadratic_function
# This function plots the S(x) surface and includes the path taken by the minimizer
def plotting(dim, steps, x0, *args):
# If we are just dealing with scalars
if dim == 1:
# Create figure
fig = plt.figure(figsize=(14,8))
axe = fig.add_subplot(111)
# Discretization of plot
num_of_points = 100
# Upper and lower bound of plot
xmin = min(x0[0], -5)
xmax = max(x0[0], +5)
# Discretized x
X = np.linspace(xmin,xmax,num_of_points)
# Initialize S(x)
Z = np.zeros_like(X)
# Fill S(x)
for i in range(0,num_of_points):
Z[i] = quadratic_function( np.array([ X[i] ]), *args )
# Make the plot of S(x)
sp = axe.plot(X, Z, 'b-')
# Initialize step values
step_value = np.zeros(steps.shape[0])
# Fill step values
for i in range(0, steps.shape[0]):
step_value[i] = quadratic_function( np.array([ steps[i, 0] ]), *args )
# Plot the steps taken in the same plot
axe.plot(steps[:,0], step_value, 'r*--')
# Set label and save plot
axe.set_xlabel('x', fontsize=15)
axe.set_ylabel('S(x)', fontsize=15)
plt.savefig("plot_1d.png")
# If \bf{x} = (x, y)
elif dim == 2:
# Create figure
fig = plt.figure(figsize=(14,8))
axe = fig.add_subplot(111, projection="3d")
# Discretization of plot
num_of_points = 100
# Upper and lower bound of plot
xmin = min(x0[0], -5)
xmax = max(x0[0], +5)
ymin = min(x0[1], -5)
ymax = max(x0[1], +5)
# Discretized x on a mesh
X, Y = np.meshgrid(np.linspace(xmin,xmax,num_of_points), np.linspace(ymin,ymax,num_of_points))
# Initialize S(x,y)
Z = np.zeros_like(X)
# Fill S(x, y)
for i in range(0,num_of_points):
for j in range(0, num_of_points):
Z[i,j] = quadratic_function( np.array([X[i,j], Y[i,j]]), *args )
# Make the plot of S(x)
sp = axe.plot_surface(X, Y, Z, cmap=cm.coolwarm)
axe.view_init(60, 100)
fig.colorbar(sp)
# Initialize step values
step_value = np.zeros(steps.shape[0])
# Fill step values
for i in range(0, steps.shape[0]):
step_value[i] = quadratic_function( np.array([steps[i, 0], steps[i, 1]]), *args )
# Plot the steps taken in the same plot
axe.plot(steps[:,0], steps[:,1], step_value, 'r*--')
# Set label and save plot
axe.set_xlabel('x', fontsize=15)
axe.set_ylabel('y', fontsize=15)
axe.set_zlabel(' S(x,y)', fontsize=15)
axe.zaxis.set_rotate_label(False)
plt.savefig("plot_2d.png")
# If higher dimensions
else:
print("Cannot make a high dimensional plot")

Event Timeline