TroglodyteDerivations commited on
Commit
a82f0ee
1 Parent(s): 2b1d24e

Updated with plot_positions, plot_3d_meshgrid_contour methods, optimize function leveraging the functionality spawning from the methods, and created the gr.components.Image functionality fostering the visualizations populating

Browse files
Files changed (1) hide show
  1. app.py +111 -1
app.py CHANGED
@@ -485,6 +485,108 @@ class GWO:
485
  #plt.close() # Close the figure to free up memory
486
  #return Image.open(buf)
487
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
488
 
489
 
490
  def optimize(npart, ndim, max_iter):
@@ -513,12 +615,18 @@ def optimize(npart, ndim, max_iter):
513
  # Plot the dispersion heatmap
514
  dispersion_heatmap_plot = gwo.plot_dispersion_heatmap(x_range=(-6,6), y_range=(-6,6))
515
 
 
 
 
 
 
 
516
  # Format the output strings
517
  best_fitness_text = f"Best Fitness: {best_fitness_npy}"
518
  best_positions_text = f"Best Positions: {best_positions_npy}"
519
 
520
  # Return the images and text
521
- return plot_contour_and_wolves, dispersion_plot, dispersion_heatmap_plot, best_fitness_text, best_positions_text, best_fitness_npy, best_positions_npy, dispersion_text
522
 
523
 
524
 
@@ -535,6 +643,8 @@ iface = gr.Interface(
535
  gr.components.Image(type="pil", label="Contour Map of Wolves Oscillating Over Search Space"),
536
  gr.components.Image(type="pil", label="Dispersion Plot"),
537
  gr.components.Image(type="pil", label="Dispersion Heatmap Plot"),
 
 
538
  gr.components.Textbox(label="Dispersion Values"),
539
  gr.components.Textbox(label="Best Positions"),
540
  gr.components.Textbox(label="Best Fitness")
 
485
  #plt.close() # Close the figure to free up memory
486
  #return Image.open(buf)
487
 
488
+ def plot_positions(self, iterations=[0, 3, 7, 11]):
489
+ """Plot the positions of the particles over the specified iterations"""
490
+ # Load the all_positions data from the .npy file
491
+ all_positions = np.load('all_positions.npy', allow_pickle=True)
492
+
493
+ # Create a figure with the correct number of subplots
494
+ num_iterations = len(iterations)
495
+ fig, axs = plt.subplots(num_iterations, figsize=(6, 4 * num_iterations))
496
+
497
+ # If there is only one subplot, make it an array to simplify the loop
498
+ if num_iterations == 1:
499
+ axs = [axs]
500
+
501
+ # Iterate over the subplots and the specified iterations to plot
502
+ for i, ax in enumerate(axs):
503
+ # Plot the particles' positions at the specified iteration
504
+ iteration = iterations[i]
505
+ if iteration < len(all_positions):
506
+ positions = all_positions[iteration]
507
+ ax.scatter(positions[:, 0], positions[:, 1], c='r', alpha=0.5)
508
+
509
+ # Set plot title and labels
510
+ ax.set_title(f'Iteration {iteration}')
511
+ ax.set_xlabel('X')
512
+ ax.set_ylabel('Y')
513
+ else:
514
+ ax.axis('off') # Hide the subplot if the iteration is out of range
515
+
516
+ plt.tight_layout()
517
+
518
+ # Save the plot to a BytesIO object
519
+ buf = BytesIO()
520
+ plt.savefig(buf, format='png')
521
+ buf.seek(0)
522
+ image = Image.open(buf)
523
+ plt.close()
524
+
525
+ return image
526
+
527
+ def plot_3d_meshgrid_contour(self, obj):
528
+ """Plot the 3D meshgrid with a 2D contour on the base"""
529
+ # Define the range for the x and y axis
530
+ x_range = np.linspace(self.bounds.Lower()[0], self.bounds.Upper()[0], 100)
531
+ y_range = np.linspace(self.bounds.Lower()[1], self.bounds.Upper()[1], 100)
532
+
533
+ # Create a grid of points
534
+
535
+ X, Y = np.meshgrid(x_range, y_range)
536
+ Z = np.zeros_like(X)
537
+
538
+ # Evaluate the objective function on the grid
539
+ for i in range(X.shape[0]):
540
+ for j in range(X.shape[1]):
541
+ Z[i, j] = obj.Evaluate(np.array([X[i, j], Y[i, j]]))
542
+
543
+ # Create a 3D plot with subplots for each rotation
544
+ fig, axs = plt.subplots(2, 2, figsize=(14, 10), subplot_kw={'projection': '3d'})
545
+ plt.subplots_adjust(wspace=0.1, hspace=0.1)
546
+
547
+ # Define the rotations for each subplot
548
+ rotations = [(30, 45), (30, 135), (30, -45), (30, -135)]
549
+
550
+ for i, ax in enumerate(axs.flatten()):
551
+ # Plot the meshgrid
552
+ ax.plot_surface(X, Y, Z, cmap='viridis', alpha=0.5)
553
+
554
+ # Plot the contour
555
+ ax.contour(X, Y, Z, levels=20, colors='k', alpha=0.5)
556
+
557
+ # Plot the best positions found by the algorithm
558
+ best_positions = np.array(self.gpos)
559
+ ax.plot(best_positions[:, 0], best_positions[:, 1], self.gbest, 'g*', markersize=4)
560
+
561
+ # Set labels and title
562
+ ax.set_xlabel('X Position')
563
+ ax.set_ylabel('Y Position')
564
+ ax.set_zlabel('Z Position')
565
+ ax.set_title(f'GWO Optimization Process in 3D - Rotation {i+1}')
566
+
567
+ # Set the limits of the plot to match the bounds
568
+ ax.set_xlim(self.bounds.Lower()[0], self.bounds.Upper()[0])
569
+ ax.set_ylim(self.bounds.Lower()[1], self.bounds.Upper()[1])
570
+ ax.set_zlim(np.min(Z), np.max(Z))
571
+
572
+ # Change the background color to light blue
573
+ ax.set_facecolor('lightblue')
574
+
575
+ # Apply the rotation
576
+ ax.view_init(*rotations[i])
577
+
578
+ # Show the plot
579
+ plt.show()
580
+
581
+ # Save the plot to a BytesIO object
582
+ buf = BytesIO()
583
+ plt.savefig(buf, format='png')
584
+ buf.seek(0)
585
+ image = Image.open(buf)
586
+ plt.close()
587
+
588
+ return image
589
+
590
 
591
 
592
  def optimize(npart, ndim, max_iter):
 
615
  # Plot the dispersion heatmap
616
  dispersion_heatmap_plot = gwo.plot_dispersion_heatmap(x_range=(-6,6), y_range=(-6,6))
617
 
618
+ # Plot the plot_positions
619
+ plot_positions = gwo.plot_positions(iterations=[0,2,9,11])
620
+
621
+ # Plot the plot_3d_meshgrid_contour
622
+ plot_3d_meshgrid_contour = gwo.plot_3d_meshgrid_contour(obj=obj)
623
+
624
  # Format the output strings
625
  best_fitness_text = f"Best Fitness: {best_fitness_npy}"
626
  best_positions_text = f"Best Positions: {best_positions_npy}"
627
 
628
  # Return the images and text
629
+ return plot_contour_and_wolves, dispersion_plot, dispersion_heatmap_plot, plot_positions, plot_3d_meshgrid_contour, best_fitness_text, best_positions_text, best_fitness_npy, best_positions_npy, dispersion_text
630
 
631
 
632
 
 
643
  gr.components.Image(type="pil", label="Contour Map of Wolves Oscillating Over Search Space"),
644
  gr.components.Image(type="pil", label="Dispersion Plot"),
645
  gr.components.Image(type="pil", label="Dispersion Heatmap Plot"),
646
+ gr.components.Image(type="pil", label="Best Positions Plot"),
647
+ gr.components.Image(type="pil", label="Plot 3D Meshgrid Contour"),
648
  gr.components.Textbox(label="Dispersion Values"),
649
  gr.components.Textbox(label="Best Positions"),
650
  gr.components.Textbox(label="Best Fitness")