Skip to content

Commit

Permalink
Merge pull request #80 from BillMakwae/Adding-Bokeh-Simulation
Browse files Browse the repository at this point in the history
Adding bokeh simulation
  • Loading branch information
chrischang5 authored Nov 2, 2021
2 parents eeb41bd + bb55c7f commit cbdcc7f
Showing 1 changed file with 29 additions and 33 deletions.
62 changes: 29 additions & 33 deletions simulation/main/MainSimulation.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import json
import sys
import os
from bokeh.io.doc import curdoc
from dotenv import load_dotenv

import matplotlib.pyplot as plt
Expand All @@ -17,6 +18,11 @@
from simulation.config import settings_directory
from simulation.main.SimulationResult import SimulationResult

from bokeh.plotting import figure, show, output_file
from bokeh.layouts import gridplot
from bokeh.models import HoverTool

from bokeh.palettes import Bokeh8



Expand Down Expand Up @@ -251,7 +257,7 @@ def optimize(self, *args, **kwargs):
self.__plot_graph(arrays_to_plot.arrays,
["Optimized speed array", "Distance (km)", "SOC (%)", "Delta energy (J)",
"Solar irradiance (W/m^2)", "Wind speeds (km/h)", "Elevation (m)", "Cloud cover (%)"],
"Simulation Result")
"Optimized Result")

return optimizer.max

Expand All @@ -273,48 +279,38 @@ def __plot_graph(self, arrays_to_plot, array_labels, graph_title):
graph_title: A string that serves as the plot's main title
Result:
If number of plots is even, produces a 2 x (len(arrays_to_plot) / 2) plot
If number of plots is odd, produces a 1 x len(arrays_to_plot) plot
Produces a 3 x ceil(len(arrays_to_plot) / 3) plot
"""
compress_constant = int(self.timestamps.shape[0] / 5000)

sns.set_style("whitegrid")

# Wow I used the walrus operator here!
if (num_arrays := len(arrays_to_plot)) == 1:
f, axes = plt.subplots()
t = np.arange(0, len(arrays_to_plot[0]))
for index, array in enumerate(arrays_to_plot):
arrays_to_plot[index] = array[::compress_constant]

figures = list()

hover_tool = HoverTool()
hover_tool.formatters = {"x": "datetime"}
hover_tool.tooltips = [
("time", "$x"),
("data", "$y")
]

axes.plot(t, arrays_to_plot[0])
for (index, data_array) in enumerate(arrays_to_plot):
# create figures and put them in list
figures.append(figure(title=array_labels[index], x_axis_label="Time (hr)",
y_axis_label=array_labels[index], x_axis_type="datetime"))

axes.set(xlabel='time (s)', ylabel=array_labels[0],
title=graph_title)
axes.grid()
plt.show()
return
elif (num_arrays / 2) % 2 == 0:
f, axes = plt.subplots(int(num_arrays / 2), 2, figsize=(12, 8))
else:
f, axes = plt.subplots(int(num_arrays), 1, figsize=(12, 8))
# add line renderers to each figure
figures[index].line(self.timestamps[::compress_constant] * 1000 , data_array, line_color=Bokeh8[index], line_width=2)

for index, array in enumerate(arrays_to_plot):
arrays_to_plot[index] = array[::compress_constant]
figures[index].add_tools(hover_tool)

f.suptitle(f"{graph_title} ({self.race_type})", fontsize=16, weight="bold")
grid = gridplot(figures, sizing_mode="scale_both", ncols=3, plot_height=200, plot_width=300)

with tqdm(total=len(arrays_to_plot), file=sys.stdout, desc="Plotting data") as pbar:
for index, axis in enumerate(axes.flatten()):
df = pd.DataFrame(dict(time=self.timestamps[::compress_constant] / 3600, value=arrays_to_plot[index]))
g = sns.lineplot(x="time", y="value", data=df, ax=axis)
g.set(xlabel="time (hrs)", ylabel=array_labels[index])
pbar.update(1)
print()
output_file(filename=graph_title + '.html', title=graph_title)

sns.despine()
_ = plt.setp(axes)
_ = plt.tight_layout()
_ = plt.show()
show(grid)

def __run_simulation_calculations(self, speed_kmh, verbose=False):
"""
Expand Down

0 comments on commit cbdcc7f

Please sign in to comment.