Skip to content

Commit

Permalink
Edited docstrings and added some comments
Browse files Browse the repository at this point in the history
  • Loading branch information
cristianlacey committed Jan 10, 2019
1 parent 7a12be5 commit f88b334
Show file tree
Hide file tree
Showing 5 changed files with 31 additions and 23 deletions.
12 changes: 9 additions & 3 deletions gastop/genalg.py
Expand Up @@ -161,25 +161,27 @@ def run(self, num_generations=None, progress_fitness=None, progress_truss=None,
if progress_truss is None:
progress_truss = self.config['monitor_params']['progress_truss']

# initialize progress monitor object
# Initialize progress monitor object
progress = ProgMon(progress_fitness, progress_truss, num_generations, domain=self.random_params['domain'],
loads=self.config['evaluator_params']['boundary_conditions']['loads'],
fixtures=self.config['evaluator_params']['boundary_conditions']['fixtures'])

# Set chunksize used in multithreading based on size of population
if self.ga_params['pop_size'] < 1e4:
chunksize = int(np.amax((self.ga_params['pop_size']/100, 1)))
else:
chunksize = int(np.sqrt(self.ga_params['pop_size']))
# Loop over all generations:

# Loop over all generations, updating progress bar with tqdm:
for current_gen in tqdm(range(num_generations), desc='Overall', position=0):
self.ga_params['current_generation'] = current_gen
# no parallelization
# No parallelization
if num_threads == 1:
for current_truss in tqdm(self.population, desc='Evaluating', position=1):
self.evaluator(current_truss)
for current_truss in tqdm(self.population, desc='Scoring', position=1):
self.fitness_function(current_truss)
# With multithreading
else:
with Pool(num_threads) as pool:
self.population = list(tqdm(pool.imap(
Expand All @@ -189,12 +191,16 @@ def run(self, num_generations=None, progress_fitness=None, progress_truss=None,
self.fitness_function, self.population, chunksize),
total=self.ga_params['pop_size'], desc='Scoring', position=1))

# Sort population by fitness score (lowest score = most fit)
self.population.sort(key=lambda x: x.fitness_score)

# Update progress monitor plots
progress.progress_monitor(current_gen, self.population)

# Create next generation
self.update_population()

# Periodically save config and population to JSON files
if self.ga_params['save_frequency'] != 0 and (current_gen % self.ga_params['save_frequency']) == 0:
self.save_state(
dest_config=self.ga_params['config_save_name'], dest_pop=self.ga_params['pop_save_name'])
Expand Down
15 changes: 7 additions & 8 deletions gastop/selector.py
Expand Up @@ -76,14 +76,13 @@ def inverse_square_rank_probability(num_parents, population):
def tournament(num_parents, population, tourn_size, tourn_prob):
''' Selects parents according to tournament method.
(ASSUMES POPULATION IS SORTED BY FITNESS) Randomly selects truss
indices from population in groups called tournaments according to
"tourn_size." Each tournament is then sorted by index (lower means
more fit) in ascending order and a single index from each tournament
is selected. The selection from each tournament is chosen
probabilistically, assigning the first, most fit, index with probability
p = tourn_prob, and then subsequent indices by p*(1-p)^n. The winners
of each tournament are then returned as the parents array.
Randomly selects truss indices from population in groups called
tournaments according to "tourn_size." Each tournament is then sorted
by index (lower means more fit) in ascending order and a single index
from each tournament is selected. The selection from each tournament is
chosen probabilistically, assigning the first, most fit, index with
probability p = tourn_prob, and then subsequent indices by p*(1-p)^n.
The winners of each tournament are then returned as the parents array.
Args:
num_parents (int): The number of parents to select.
Expand Down
13 changes: 7 additions & 6 deletions gastop/utilities.py
Expand Up @@ -123,7 +123,8 @@ def init_file_parser(init_file_path): # Cristian
Creates ConfigObj object, which reads input parameters as a nested
dictionary of strings. The string are then converted to their correct types
using the ConfigObj walk method and a transform function.
using the ConfigObj walk method and a transform function. Defaults are then
set with if statements.
Args:
init_file_path (string): Path to the init file, relative to
Expand Down Expand Up @@ -178,7 +179,10 @@ def transform(section, key):
# transform function.
config.walk(transform)

# Parse 'properties' CSV file
properties_dict = beam_file_parser(config['general']['properties_path'])

# ---------------------------Set Defaults---------------------------------
user_spec_nodes = config['general']['user_spec_nodes']
num_user_nodes = user_spec_nodes.shape[0]
num_rand_nodes = config['general']['num_rand_nodes']
Expand All @@ -188,9 +192,6 @@ def transform(section, key):
loads = config['general']['loads']
fixtures = config['general']['fixtures']

# progress_fitness = config['monitor_params']['progress_fitness'] # sfr
# progress_truss = config['monitor_params']['progress_truss'] # sfr

if loads.ndim < 3:
loads = np.reshape(loads, (loads.shape + (1,)))
if fixtures.ndim < 3:
Expand Down Expand Up @@ -299,7 +300,7 @@ def save_progress_history(progress_history, path_progress_history='progress_hist
Returns:
Nothing
'''
# Save pop_progress data
# Save progress_history data
with open(path_progress_history, 'w') as f:
progress_history_dumped = json.dumps(
copy.deepcopy(progress_history), cls=encoders.PopulationEncoder)
Expand All @@ -316,7 +317,7 @@ def load_progress_history(path_progress_history='progress_history.json'):
progress_history (dict): History of each generation, including generation
number, fittest truss, etc.
'''
# Load pop_progress data
# Load progress_history data
with open(path_progress_history, 'r') as f:
progress_history_loaded = json.load(f)
progress_history = json.loads(
Expand Down
8 changes: 6 additions & 2 deletions tests/test_selector.py
Expand Up @@ -15,8 +15,11 @@


class TestSelector(unittest.TestCase): # Cristian
'''Tests for Selector() method_params
'''
def testInvSqrRankProp(self):
# Tests the inverse_square_rank_probability method of Selector()
'''Tests the inverse_square_rank_probability method of Selector()
'''
nodes = np.array([[1, 2, 3], [2, 3, 4]])
edges = np.array([[0, 1]])
properties = np.array([[0, 3]])
Expand Down Expand Up @@ -59,7 +62,8 @@ def testInvSqrRankProp(self):
self.assertEqual(num_parents, len(parents))

def testTournament(self):
# Tests the tournament method of Selector()
'''Tests the tournament method of Selector()
'''
nodes = np.array([[1, 2, 3], [2, 3, 4]])
edges = np.array([[0, 1]])
properties = np.array([[0, 3]])
Expand Down
6 changes: 2 additions & 4 deletions tests/test_utilities.py
Expand Up @@ -20,9 +20,7 @@ def testInitFileParser(self):

init_file_path = 'gastop-config/boolean_parse_test_init.txt'
config = utilities.init_file_parser(init_file_path)
# for key in config:
# print(key)
# print(config[key])

self.assertTrue(isinstance(config['ga_params']['num_elite'], int))
self.assertTrue(
isinstance(config['ga_params']['percent_crossover'], float))
Expand All @@ -40,7 +38,7 @@ def testInitFileParser(self):
self.assertEqual(config['ga_params']['save_frequency'], 0)

def testInitFileParser2(self):
"""tests edge cases for invalid file path"""
"""Tests edge cases for invalid file path"""

init_file_path = 'gastop-config/foo'
self.assertRaises(IOError, utilities.init_file_parser, init_file_path)
Expand Down

0 comments on commit f88b334

Please sign in to comment.