Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
…into dev
  • Loading branch information
Susan Redmond authored and Susan Redmond committed Jan 6, 2019
2 parents feddf67 + 8a8e996 commit 960deb2
Show file tree
Hide file tree
Showing 4 changed files with 81 additions and 6 deletions.
2 changes: 1 addition & 1 deletion gastop/evaluator.py
Expand Up @@ -428,6 +428,6 @@ def __call__(self, truss):
truss, self.boundary_conditions, self.properties_dict)
truss.mass = self.mass_solver(truss, self.properties_dict)
truss.cost = self.cost_solver(truss, self.properties_dict)
truss.interferences = self.interferences_solver(truss)
truss.interference = self.interferences_solver(truss)

return truss
40 changes: 39 additions & 1 deletion gastop/utilities.py
Expand Up @@ -8,13 +8,14 @@

import numpy as np
import configobj
import json
import ast
import os
import imageio
import matplotlib.pyplot as plt
import shutil

from gastop import Truss, ProgMon
from gastop import Truss, ProgMon, encoders


def save_gif(progress_history, progress_fitness, progress_truss, animation_path, num_gens,config):
Expand Down Expand Up @@ -256,3 +257,40 @@ def transform(section, key):
config['monitor_params']['progress_truss'] = False

return config

def save_progress_history(progress_history, path_progress_history='progress_history.json'):
'''Saves the population history (progress_history) to a JSON file.
Args:
progress_history (dict): History of each generation, including generation
number, fittest truss, etc.
path_progress_history (string): Path to save progress_history data file. If file
doesn't exist, creates it.
Returns:
Nothing
'''
# Save pop_progress data
with open(path_progress_history, 'w') as f:
progress_history_dumped = json.dumps(progress_history, cls=encoders.PopulationEncoder)
json.dump(progress_history_dumped, f)

def load_progress_history(path_progress_history='progress_history.json'):
'''Loads the population history (progress_history) from a JSON file.
Args:
path_progress_history (string): Path to progress_history data file.
Returns:
progress_history (dict): History of each generation, including generation
number, fittest truss, etc.
'''
# Load pop_progress data
with open(path_progress_history, 'r') as f:
progress_history_loaded = json.load(f)
progress_history = json.loads(progress_history_loaded, object_hook=encoders.numpy_decoder)
# Bundle truss dictionaries as Truss objects
for gen in progress_history.keys():
progress_history[gen]['Best Truss'] = Truss(**progress_history[gen]['Best Truss'])

return progress_history
8 changes: 5 additions & 3 deletions tests/test_genalg.py
Expand Up @@ -28,6 +28,8 @@

class TestGenAlg_Cristian(unittest.TestCase): # Cristian
def testUpdatePopulation(self):
'''Tests that the population correctly updates every generation.
'''
# Create GenAlg object and assign random fitness scores
pop_size = int(1e4)
ga = GenAlg(init_file_path)
Expand All @@ -51,6 +53,9 @@ def testUpdatePopulation(self):
self.assertTrue(isinstance(truss.properties,np.ndarray))

def testSaveLoadState(self):
'''Tests that config and population can be saved to and loaded from
JSON files.
'''
# Parse input parameters from init file
init_file_path = 'gastop-config/struct_making_test_init.txt'
config = utilities.init_file_parser(init_file_path)
Expand All @@ -62,7 +67,6 @@ def testSaveLoadState(self):

# Save and reload
ga.save_state()
# config, population = ga.load_state()
ga_loaded = ga.load_state()
config = ga_loaded.config
population = ga_loaded.population
Expand All @@ -83,8 +87,6 @@ def testSaveLoadState(self):
self.assertTrue(isinstance(truss.rand_nodes,np.ndarray))
self.assertTrue(isinstance(truss.edges,np.ndarray))
self.assertTrue(isinstance(truss.properties,np.ndarray))
# print(config)
# print([truss for truss in population])


class TestGenAlg_Dan(unittest.TestCase):
Expand Down
37 changes: 36 additions & 1 deletion tests/test_utilities.py
Expand Up @@ -9,7 +9,7 @@

import unittest
import numpy as np
from gastop import Truss, utilities
from gastop import Truss, utilities, ProgMon, GenAlg


class TestUtilities_Cristian(unittest.TestCase): # Cristian
Expand Down Expand Up @@ -46,6 +46,41 @@ def testInitFileParser2(self):
self.assertRaises(IOError, utilities.init_file_parser, init_file_path)


def testSaveLoadPopProgress(self):
'''Tests that the pop_progress dictionary is correctly saved to and
loaded from a JSON file.
'''
# Parse input paramters from init.txt file
init_file_path = 'gastop-config/struct_making_test_init.txt'
config = utilities.init_file_parser(init_file_path)

progress_fitness = False
progress_truss = False
num_threads = 1
num_generations = 3
pop_size = 5

# Create the Genetic Algorithm Object
ga = GenAlg(config)
ga.initialize_population(pop_size)
best, progress_history = ga.run(num_generations=num_generations,
progress_fitness=progress_fitness,
progress_truss=progress_truss,
num_threads=num_threads)

# Save and load pop_progress to/from JSON file
utilities.save_progress_history(progress_history)
loaded_progress_history = utilities.load_progress_history()
print(loaded_progress_history)

for gen in loaded_progress_history.keys():
self.assertTrue(isinstance(loaded_progress_history[gen]['Generation'],int))
self.assertTrue(isinstance(loaded_progress_history[gen]['Best Truss'],Truss))
self.assertTrue(isinstance(loaded_progress_history[gen]['Best Fitness Score'],float))
self.assertTrue(isinstance(loaded_progress_history[gen]['Population Median Fitness Score'],float))
self.assertTrue(isinstance(loaded_progress_history[gen]['Population Fitness Score Range'],float))


class TestTrussPlot(unittest.TestCase):
"""Test for plot and print methods. Doesn't assert, visual inspection used for pass/fail"""

Expand Down

0 comments on commit 960deb2

Please sign in to comment.