code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
if len(lower_bounds) != solution_size or len(upper_bounds) != solution_size:
raise ValueError(
"Lower and upper bounds much have a length equal to the problem size."
)
return common.make_population(population_size, common.random_real_solution,
... | def _initial_population_gsa(population_size, solution_size, lower_bounds,
upper_bounds) | Create a random initial population of floating point values.
Args:
population_size: an integer representing the number of solutions in the population.
problem_size: the number of values in each solution.
lower_bounds: a list, each value is a lower bound for the corresponding
... | 3.546753 | 3.902716 | 0.908791 |
# Update the gravitational constant, and the best and worst of the population
# Calculate the mass and acceleration for each solution
# Update the velocity and position of each solution
population_size = len(population)
solution_size = len(population[0])
# In GSA paper, grav is G
grav ... | def _new_population_gsa(population, fitnesses, velocities, lower_bounds,
upper_bounds, grav_initial, grav_reduction_rate,
iteration, max_iterations) | Generate a new population as given by GSA algorithm.
In GSA paper, grav_initial is G_i | 3.139868 | 3.056599 | 1.027242 |
return grav_initial * math.exp(
-grav_reduction_rate * iteration / float(max_iterations)) | def _next_grav_gsa(grav_initial, grav_reduction_rate, iteration,
max_iterations) | Calculate G as given by GSA algorithm.
In GSA paper, grav is G | 3.547425 | 4.477486 | 0.79228 |
# Obtain constants
best_fitness = max(fitnesses)
worst_fitness = min(fitnesses)
fitness_range = best_fitness - worst_fitness
# Calculate raw masses for each solution
raw_masses = []
for fitness in fitnesses:
# Epsilon is added to prevent divide by zero errors
raw_masses... | def _get_masses(fitnesses) | Convert fitnesses into masses, as given by GSA algorithm. | 2.971659 | 2.901157 | 1.024301 |
position_diff = numpy.subtract(position_j, position_i)
distance = numpy.linalg.norm(position_diff)
# The first 3 terms give the magnitude of the force
# The last term is a vector that provides the direction
# Epsilon prevents divide by zero errors
return grav * (mass_i * mass_j) / (distan... | def _gsa_force(grav, mass_i, mass_j, position_i, position_j) | Gives the force of solution j on solution i.
Variable name in GSA paper given in ()
args:
grav: The gravitational constant. (G)
mass_i: The mass of solution i (derived from fitness). (M_i)
mass_j: The mass of solution j (derived from fitness). (M_j)
position_i: The position of ... | 5.02235 | 5.428835 | 0.925125 |
if len(force_vectors) == 0:
return [0.0] * vector_length
# The GSA algorithm specifies that the total force in each dimension
# is a random sum of the individual forces in that dimension.
# For this reason we sum the dimensions individually instead of simply
# using vec_a+vec_b
tota... | def _gsa_total_force(force_vectors, vector_length) | Return a randomly weighted sum of the force vectors.
args:
force_vectors: A list of force vectors on solution i.
returns:
numpy.array; The total force on solution i. | 3.415038 | 3.677368 | 0.928664 |
# The GSA algorithm specifies that the new velocity for each dimension
# is a sum of a random fraction of its current velocity in that dimension,
# and its acceleration in that dimension
# For this reason we sum the dimensions individually instead of simply
# using vec_a+vec_b
new_velocity... | def _gsa_update_velocity(velocity, acceleration) | Stochastically update velocity given acceleration.
In GSA paper, velocity is v_i, acceleration is a_i | 5.922002 | 6.193501 | 0.956164 |
# Selection
# Create the population of parents that will be crossed and mutated.
intermediate_population = selection_function(population, fitnesses)
# Crossover
new_population = _crossover(intermediate_population, crossover_chance,
crossover_function)
# Mut... | def _new_population_genalg(population,
fitnesses,
mutation_chance=0.02,
crossover_chance=0.7,
selection_function=gaoperators.tournament_selection,
crossover_function=gaoperators.one_poi... | Perform all genetic algorithm operations on a population, and return a new population.
population must have an even number of chromosomes.
Args:
population: A list of binary lists, ex. [[0,1,1,0], [1,0,1,0]]
fitness: A list of fitnesses that correspond with chromosomes in the population,
... | 3.960755 | 4.364309 | 0.907533 |
new_population = []
for i in range(0, len(population), 2): # For every other index
# Take parents from every set of 2 in the population
# Wrap index if out of range
try:
parents = (population[i], population[i + 1])
except IndexError:
parents = (popul... | def _crossover(population, crossover_chance, crossover_operator) | Perform crossover on a population, return the new crossed-over population. | 3.172264 | 3.110704 | 1.01979 |
return [
random.uniform(lower_bounds[i], upper_bounds[i])
for i in range(solution_size)
] | def random_real_solution(solution_size, lower_bounds, upper_bounds) | Make a list of random real numbers between lower and upper bounds. | 2.183162 | 2.046851 | 1.066596 |
return [
solution_generator(*args, **kwargs) for _ in range(population_size)
] | def make_population(population_size, solution_generator, *args, **kwargs) | Make a population with the supplied generator. | 2.968879 | 2.822238 | 1.051959 |
# Optimization if diversity factor is disabled
if diversity_weight <= 0.0:
fitness_pop = zip(fitnesses,
population) # Zip for easy fitness comparison
# Get num_competitors random chromosomes, then add best to result,
# by taking max fitness and getting ch... | def tournament_selection(population,
fitnesses,
num_competitors=2,
diversity_weight=0.0) | Create a list of parents with tournament selection.
Args:
population: A list of solutions.
fitnesses: A list of fitness values corresponding to solutions in population.
num_competitors: Number of solutions to compare every round.
Best solution among competitors is selected.
... | 4.850502 | 4.71158 | 1.029485 |
pop_size = len(population)
probabilities = _fitnesses_to_probabilities(fitnesses)
# Create selection list (for stochastic universal sampling)
selection_list = []
selection_spacing = 1.0 / pop_size
selection_start = random.uniform(0.0, selection_spacing)
for i in range(pop_size):
... | def stochastic_selection(population, fitnesses) | Create a list of parents with stochastic universal sampling. | 2.829669 | 2.739012 | 1.033099 |
probabilities = _fitnesses_to_probabilities(fitnesses)
intermediate_population = []
for _ in range(len(population)):
# Choose a random individual
selection = random.uniform(0.0, 1.0)
# Iterate over probabilities list
for i, probability in enumerate(probabilities):
... | def roulette_selection(population, fitnesses) | Create a list of parents with roulette selection. | 3.579788 | 3.53331 | 1.013154 |
# Subtract min, making smallest value 0
min_val = min(vector)
vector = [v - min_val for v in vector]
# Divide by max, making largest value 1
max_val = float(max(vector))
try:
return [v / max_val for v in vector]
except ZeroDivisionError: # All values are the same
retur... | def _rescale(vector) | Scale values in vector to the range [0, 1].
Args:
vector: A list of real values. | 3.178751 | 3.218361 | 0.987692 |
# Edge case for empty population
# If there are no other solutions, the given solution has maximum diversity
if population == []:
return 1.0
return (
sum([_manhattan_distance(solution, other) for other in population])
# Normalize (assuming each value in solution is in range... | def _diversity_metric(solution, population) | Return diversity value for solution compared to given population.
Metric is sum of distance between solution and each solution in population,
normalized to [0.0, 1.0]. | 6.293969 | 5.772027 | 1.090426 |
if len(vec_a) != len(vec_b):
raise ValueError('len(vec_a) must equal len(vec_b)')
return sum(map(lambda a, b: abs(a - b), vec_a, vec_b)) | def _manhattan_distance(vec_a, vec_b) | Return manhattan distance between two lists of numbers. | 2.053229 | 1.800551 | 1.140334 |
# Do not allow negative fitness values
min_fitness = min(fitnesses)
if min_fitness < 0.0:
# Make smallest fitness value 0
fitnesses = map(lambda f: f - min_fitness, fitnesses)
fitness_sum = sum(fitnesses)
# Generate probabilities
# Creates a list of increasing values.
... | def _fitnesses_to_probabilities(fitnesses) | Return a list of probabilities proportional to fitnesses. | 3.42889 | 3.372561 | 1.016702 |
# The point that the chromosomes will be crossed at (see Ex. above)
crossover_point = random.randint(1, len(parents[0]) - 1)
return (_one_parent_crossover(parents[0], parents[1], crossover_point),
_one_parent_crossover(parents[1], parents[0], crossover_point)) | def one_point_crossover(parents) | Perform one point crossover on two parent chromosomes.
Select a random position in the chromosome.
Take genes to the left from one parent and the rest from the other parent.
Ex. p1 = xxxxx, p2 = yyyyy, position = 2 (starting at 0), child = xxyyy | 3.511214 | 3.928682 | 0.893738 |
chromosome_length = len(parents[0])
children = [[], []]
for i in range(chromosome_length):
selected_parent = random.randint(0, 1)
# Take from the selected parent, and add it to child 1
# Take from the other parent, and add it to child 2
children[0].append(parents[sele... | def uniform_crossover(parents) | Perform uniform crossover on two parent chromosomes.
Randomly take genes from one parent or the other.
Ex. p1 = xxxxx, p2 = yyyyy, child = xyxxy | 2.641672 | 2.639406 | 1.000858 |
for chromosome in population: # For every chromosome in the population
for i in range(len(chromosome)): # For every bit in the chromosome
# If mutation takes place
if random.uniform(0.0, 1.0) <= mutation_chance:
chromosome[i] = 1 - chromosome[i] | def random_flip_mutate(population, mutation_chance) | Mutate every chromosome in a population, list is modified in place.
Mutation occurs by randomly flipping bits (genes). | 2.588896 | 2.637138 | 0.981707 |
item_indices = {}
for i, item in enumerate(list_):
try:
item_indices[item].append(i)
except KeyError: # First time seen
item_indices[item] = [i]
return item_indices | def _duplicates(list_) | Return dict mapping item -> indices. | 2.661853 | 1.984396 | 1.341392 |
# WARNING: meta_parameters is modified inline
locked_values = {}
if parameter_locks:
for name in parameter_locks:
# Store the current optimzier value
# and remove from our dictionary of paramaters to optimize
locked_values[name] = getattr(optimizer, name)
... | def _parse_parameter_locks(optimizer, meta_parameters, parameter_locks) | Synchronize meta_parameters and locked_values.
The union of these two sets will have all necessary parameters.
locked_values will have the parameters specified in parameter_locks. | 7.59353 | 7.303898 | 1.039654 |
# WARNING: meta_parameters is modified inline
solution_size = 0
for _, parameters in meta_parameters.iteritems():
if parameters['type'] == 'discrete':
# Binary encoding of discrete values -> log_2 N
num_values = len(parameters['values'])
binary_size = helper... | def _get_hyperparameter_solution_size(meta_parameters) | Determine size of binary encoding of parameters.
Also adds binary size information for each parameter. | 3.99592 | 3.81376 | 1.047764 |
# Locked parameters are also returned by decode function, but are not
# based on solution
def decode(solution):
# Start with out stationary (locked) paramaters
hyperparameters = copy.deepcopy(locked_values)
# Obtain moving hyperparameters from binary solution
... | def _make_hyperparameter_decode_func(locked_values, meta_parameters) | Create a function that converts the binary solution to parameters. | 3.610339 | 3.399155 | 1.062128 |
# Create the optimizer with parameters encoded in solution
optimizer = copy.deepcopy(_optimizer)
optimizer._set_hyperparameters(parameters)
optimizer.logging = False
# Preload fitness dictionary from master, and disable clearing dict
# NOTE: master_fitness_dict will be modified inline, and... | def _meta_fitness_func(parameters,
_optimizer,
_problems,
_master_fitness_dict,
_runs=20) | Test a metaheuristic with parameters encoded in solution.
Our goal is to minimize number of evaluation runs until a solution is found,
while maximizing chance of finding solution to the underlying problem
NOTE: while meta optimization requires a 'known' solution, this solution
can be an estimate to pro... | 6.964772 | 6.261477 | 1.112321 |
if fitness_function is None:
fitness_function = self._fitness_function
if decode_function is None:
decode_function = self._decode_function
if fitness_args is None:
fitness_args = self._fitness_args
if decode_args is None:
decode_ar... | def copy(self,
fitness_function=None,
decode_function=None,
fitness_args=None,
decode_args=None,
fitness_kwargs=None,
decode_kwargs=None) | Return a copy of this problem.
Optionally replace this problems arguments with those passed in. | 1.323544 | 1.279009 | 1.03482 |
return self._fitness_function(solution, *self._fitness_args,
**self._fitness_kwargs) | def get_fitness(self, solution) | Return fitness for the given solution. | 4.854525 | 3.990703 | 1.216459 |
return self._decode_function(encoded_solution, *self._decode_args,
**self._decode_kwargs) | def decode_solution(self, encoded_solution) | Return solution from an encoded representation. | 4.659289 | 4.257683 | 1.094325 |
if not isinstance(problem, Problem):
raise TypeError('problem must be an instance of Problem class')
# Prepare pool for multiprocessing
if n_processes > 0:
try:
pool = multiprocessing.Pool(processes=n_processes)
except NameError:
... | def optimize(self, problem, max_iterations=100, max_seconds=float('inf'),
cache_encoded=True, cache_solution=False, clear_cache=True,
logging_func=_print_fitnesses,
n_processes=0) | Find the optimal inputs for a given fitness function.
Args:
problem: An instance of Problem. The problem to solve.
max_iterations: The number of iterations to optimize before stopping.
max_seconds: Maximum number of seconds to optimize for, before stopping.
N... | 3.339907 | 3.26942 | 1.02156 |
self.iteration = 0
self.fitness_runs = 0
self.best_solution = None
self.best_fitness = None
self.solution_found = False | def _reset_bookkeeping(self) | Reset bookkeeping parameters to initial values.
Call before beginning optimization. | 5.019402 | 4.526923 | 1.108789 |
if keys is not None: # Otherwise, cannot hash items
# Remove duplicates first (use keys)
# Create mapping (dict) of key to list of indices
key_indices = _duplicates(keys).values()
else: # Cannot hash items
# Assume no duplicates
key_... | def _pmap(self, func, items, keys, pool, bookkeeping_dict=None) | Efficiently map func over all items.
Calls func only once for duplicate items.
Item duplicates are detected by corresponding keys.
Unless keys is None.
Serial if pool is None, but still skips duplicates. | 4.474423 | 4.400955 | 1.016694 |
for name, value in parameters.iteritems():
try:
getattr(self, name)
except AttributeError:
raise ValueError(
'Each parameter in parameters must be an attribute. '
'{} is not.'.format(name))
setat... | def _set_hyperparameters(self, parameters) | Set internal optimization parameters. | 3.731776 | 3.459814 | 1.078606 |
hyperparameters = {}
for key in self._hyperparameters:
hyperparameters[key] = getattr(self, key)
return hyperparameters | def _get_hyperparameters(self) | Get internal optimization parameters. | 3.106309 | 2.69789 | 1.151385 |
if smoothing <= 0:
raise ValueError('smoothing must be > 0')
# problems supports either one or many problem instances
if isinstance(problems, collections.Iterable):
for problem in problems:
if not isinstance(problem, Problem):
... | def optimize_hyperparameters(self,
problems,
parameter_locks=None,
smoothing=20,
max_iterations=100,
_meta_optimizer=None,
... | Optimize hyperparameters for a given problem.
Args:
parameter_locks: a list of strings, each corresponding to a hyperparamter
that should not be optimized.
problems: Either a single problem, or a list of problem instances,
allowing optim... | 5.038613 | 5.05813 | 0.996141 |
if not (isinstance(optimizers, collections.Iterable)
or isinstance(problems, collections.Iterable)):
raise TypeError('optimizers or problems must be iterable')
# If optimizers is not a list, repeat into list for each problem
if not isinstance(optimizers, collections.Iterable):
... | def compare(optimizers, problems, runs=20, all_kwargs={}) | Compare a set of optimizers.
Args:
optimizers: list/Optimizer; Either a list of optimizers to compare,
or a single optimizer to test on each problem.
problems: list/Problem; Either a problem instance or a list of problem instances,
one for each optimizer.
all_kwargs:... | 2.731803 | 2.673008 | 1.021996 |
stats = {'runs': []}
# Disable logging, to avoid spamming the user
# TODO: Maybe we shouldn't disable by default?
kwargs = copy.copy(kwargs)
kwargs['logging_func'] = None
# Determine effectiveness of metaheuristic over many runs
# The stochastic nature of metaheuristics make this nece... | def benchmark(optimizer, problem, runs=20, **kwargs) | Run an optimizer through a problem multiple times.
Args:
optimizer: Optimizer; The optimizer to benchmark.
problem: Problem; The problem to benchmark on.
runs: int > 0; Number of times that optimize is called on problem.
Returns:
dict; A dictionary of various statistics. | 7.367486 | 7.717766 | 0.954614 |
aggregate_stats = {'means': [], 'standard_deviations': []}
for optimizer_key in all_stats:
# runs is the mean, for add_mean_sd function
mean_stats = copy.deepcopy(all_stats[optimizer_key]['mean'])
mean_stats['name'] = optimizer_key
aggregate_stats['means'].append(mean_stats)... | def aggregate(all_stats) | Combine stats for multiple optimizers to obtain one mean and sd.
Useful for combining stats for the same optimizer class and multiple problems.
Args:
all_stats: dict; output from compare. | 3.244045 | 3.230903 | 1.004067 |
num_runs = len(stats[key])
first = stats[key][0]
mean = {}
for stat_key in first:
# Skip non numberic attributes
if isinstance(first[stat_key], numbers.Number):
mean[stat_key] = sum(run[stat_key]
for run in stats[key]) / float(num_runs)... | def _mean_of_runs(stats, key='runs') | Obtain the mean of stats.
Args:
stats: dict; A set of stats, structured as above.
key: str; Optional key to determine where list of runs is found in stats | 3.350061 | 3.747424 | 0.893964 |
num_runs = len(stats[key])
first = stats[key][0]
standard_deviation = {}
for stat_key in first:
# Skip non numberic attributes
if isinstance(first[stat_key], numbers.Number):
standard_deviation[stat_key] = math.sqrt(
sum((run[stat_key] - mean[stat_key])... | def _sd_of_runs(stats, mean, key='runs') | Obtain the standard deviation of stats.
Args:
stats: dict; A set of stats, structured as above.
mean: dict; Mean for each key in stats.
key: str; Optional key to determine where list of runs is found in stats | 2.8613 | 3.146411 | 0.909385 |
return map(int,
numpy.random.random(probability_vec.size) <= probability_vec) | def _sample(probability_vec) | Return random binary string, with given probabilities. | 8.048223 | 7.019969 | 1.146476 |
best_solution = max(zip(fitnesses, population))[1]
# Shift probabilities towards best solution
return _adjust(probability_vec, best_solution, adjust_rate) | def _adjust_probability_vec_best(population, fitnesses, probability_vec,
adjust_rate) | Shift probabilities towards the best solution. | 6.726266 | 4.887636 | 1.37618 |
bits_to_mutate = numpy.random.random(probability_vec.size) <= mutation_chance
probability_vec[bits_to_mutate] = _adjust(
probability_vec[bits_to_mutate],
numpy.random.random(numpy.sum(bits_to_mutate)), mutation_adjust_rate) | def _mutate_probability_vec(probability_vec, mutation_chance, mutation_adjust_rate) | Randomly adjust probabilities.
WARNING: Modifies probability_vec argument. | 2.833557 | 3.073611 | 0.921899 |
# Update probability vector
self._probability_vec = _adjust_probability_vec_best(
population, fitnesses, self._probability_vec, self._adjust_rate)
# Mutate probability vector
_mutate_probability_vec(self._probability_vec, self._mutation_chance,
... | def next_population(self, population, fitnesses) | Make a new population after each optimization iteration.
Args:
population: The population current population of solutions.
fitnesses: The fitness associated with each solution in the population
Returns:
list; a list of solutions. | 4.568827 | 4.944593 | 0.924005 |
# Get our benchmark stats
all_stats = benchmark.compare(optimizer, PROBLEMS, runs=100)
return benchmark.aggregate(all_stats) | def benchmark_multi(optimizer) | Benchmark an optimizer configuration on multiple functions. | 13.309964 | 14.041458 | 0.947905 |
population = []
for _ in range(population_size):
solution = []
for probability in probabilities:
# probability of 1.0: always 1
# probability of 0.0: always 0
if random.uniform(0.0, 1.0) < probability:
solution.append(1)
else:
... | def _sample(probabilities, population_size) | Return a random population, drawn with regard to a set of probabilities | 2.313186 | 2.220696 | 1.041649 |
# 1.0 - abs(bit - p) gives probability of bit given p
return _prod([1.0 - abs(bit - p) for bit, p in zip(solution, pdf)]) | def _chance(solution, pdf) | Return the chance of obtaining a solution from a pdf.
The probability of many independant weighted "coin flips" (one for each bit) | 7.894166 | 8.208694 | 0.961684 |
# Add the chance of obtaining a solution from the pdf
# when the fitness for that solution exceeds a threshold
value = 0.0
for solution, fitness in zip(population, fitnesses):
if fitness >= fitness_threshold:
# 1.0 + chance to avoid issues with chance of 0
value += m... | def _pdf_value(pdf, population, fitnesses, fitness_threshold) | Give the value of a pdf.
This represents the likelihood of a pdf generating solutions
that exceed the threshold. | 9.429694 | 9.535213 | 0.988934 |
# First we determine a fitness threshold based on a quantile of fitnesses
fitness_threshold = _get_quantile_cutoff(fitnesses, quantile)
# Then check all of our possible pdfs with a stochastic program
return _best_pdf(pdfs, population, fitnesses, fitness_threshold) | def _update_pdf(population, fitnesses, pdfs, quantile) | Find a better pdf, based on fitnesses. | 8.363179 | 7.465424 | 1.120255 |
# Edge case for empty binary_list
if binary_list == []:
# With 0 bits, only one value can be represented,
# and we default to lower_bound
return lower_bound
# A little bit of math gets us a floating point
# number between upper and lower bound
# We look at the relative... | def binary_to_float(binary_list, lower_bound, upper_bound) | Return a floating point number between lower and upper bounds, from binary.
Args:
binary_list: list<int>; List of 0s and 1s.
The number of bits in this list determine the number of possible
values between lower and upper bound.
Increase the size of binary_list for more p... | 6.668513 | 6.580466 | 1.01338 |
# Edge case for empty binary_list
if binary_list == []:
# With 0 bits, only one value can be represented,
# and we default to lower_bound
return lower_bound
else:
# The builtin int construction can take a base argument,
# but it requires a string,
# so we... | def binary_to_int(binary_list, lower_bound=0, upper_bound=None) | Return the base 10 integer corresponding to a binary list.
The maximum value is determined by the number of bits in binary_list,
and upper_bound. The greater allowed by the two.
Args:
binary_list: list<int>; List of 0s and 1s.
lower_bound: Minimum value for output, inclusive.
A b... | 5.415735 | 4.110843 | 1.317427 |
binary_list = map(int, format(integer, 'b'))
if size is None:
return binary_list
else:
if len(binary_list) > size:
# Too long, take only last n
return binary_list[len(binary_list)-size:]
elif size > len(binary_list):
# Too short, pad
... | def _int_to_binary(integer, size=None) | Return bit list representation of integer.
If size is given, binary string is padded with 0s, or clipped to the size. | 2.635563 | 2.758444 | 0.955453 |
return common.make_population(self._population_size,
self._generate_solution) | def next_population(self, population, fitnesses) | Make a new population after each optimization iteration.
Args:
population: The population current population of solutions.
fitnesses: The fitness associated with each solution in the population
Returns:
list; a list of solutions. | 15.41732 | 19.243692 | 0.801162 |
return common.random_real_solution(
self._solution_size, self._lower_bounds, self._upper_bounds) | def _generate_solution(self) | Return a single random solution. | 9.556029 | 6.266217 | 1.525008 |
return [self._next_solution() for _ in range(self._population_size)] | def next_population(self, population, fitnesses) | Make a new population after each optimization iteration.
Args:
population: The population current population of solutions.
fitnesses: The fitness associated with each solution in the population
Returns:
list; a list of solutions. | 5.939965 | 6.830631 | 0.869607 |
groups = self._groups or self.get_children_paths(self.root_path)
for group in groups:
node = Node(name=group, parent=self.root)
self.root.children.append(node)
self._init_sub_groups(node) | def _build_tree(self) | Build a full or a partial tree, depending on the groups/sub-groups specified. | 4.866901 | 4.062959 | 1.197871 |
if self._sub_groups:
for sub_group in self._sub_groups:
for component in split_path_components(sub_group):
fp = os.path.join(parent.full_path, component)
if os.path.exists(fp):
node = Node(name=component, paren... | def _init_sub_groups(self, parent) | Initialise sub-groups, and create any that do not already exist. | 3.456556 | 3.403509 | 1.015586 |
for dir_name in self.get_children_paths(parent.full_path):
child = Node(name=dir_name, parent=parent)
parent.children.append(child)
self._init_children(child) | def _init_children(self, parent) | Initialise each node's children - essentially build the tree. | 3.587498 | 3.219149 | 1.114424 |
if self.parent:
return os.path.join(self.parent.full_path, self.name)
return self.name | def full_path(self) | Absolute system path to the node | 3.36552 | 3.043421 | 1.105835 |
if self.parent:
try:
parent_path = self.parent.path.encode()
except AttributeError:
parent_path = self.parent.path
return os.path.join(parent_path, self.name)
return b"/" | def path(self) | Node's relative path from the root node | 3.532244 | 3.086197 | 1.14453 |
if self.parent is None:
return self.NODE_ROOT
elif self.parent.node_type == self.NODE_ROOT:
return self.NODE_CONTROLLER_ROOT
elif b".slice" in self.name or b'.partition' in self.name:
return self.NODE_SLICE
elif b".scope" in self.name:
... | def _get_node_type(self) | Returns the current node's type | 3.979071 | 3.73784 | 1.064538 |
if self.node_type == self.NODE_CONTROLLER_ROOT and self.name in self.CONTROLLERS:
return self.name
elif self.parent:
return self.parent.controller_type
else:
return None | def _get_controller_type(self) | Returns the current node's controller type | 5.547673 | 4.369713 | 1.269574 |
node = Node(name, parent=self)
if node in self.children:
raise RuntimeError('Node {} already exists under {}'.format(name, self.path))
name = name.encode()
fp = os.path.join(self.full_path, name)
os.mkdir(fp)
self.children.append(node)
return... | def create_cgroup(self, name) | Create a cgroup by name and attach it under this node. | 3.855501 | 3.517298 | 1.096154 |
name = name.encode()
fp = os.path.join(self.full_path, name)
if os.path.exists(fp):
os.rmdir(fp)
node = Node(name, parent=self)
try:
self.children.remove(node)
except ValueError:
return | def delete_cgroup(self, name) | Delete a cgroup by name and detach it from this node.
Raises OSError if the cgroup is not empty. | 3.613364 | 3.799039 | 0.951126 |
for child in self.children:
child.delete_empty_children()
try:
if os.path.exists(child.full_path):
os.rmdir(child.full_path)
except OSError: pass
else: self.children.remove(child) | def delete_empty_children(self) | Walk through the children of this node and delete any that are empty. | 2.665764 | 2.436436 | 1.094124 |
if self.controllers.get(node.controller_type, None):
raise RuntimeError("Cannot add node {} to the node group. A node for {} group is already assigned".format(
node,
node.controller_type
))
self.nodes.append(node)
if node.controlle... | def add_node(self, node) | A a Node object to the group. Only one node per cgroup is supported | 3.912154 | 3.779196 | 1.035182 |
tasks = set()
for node in walk_tree(self):
for ctrl in node.controllers.values():
tasks.update(ctrl.tasks)
return tasks | def group_tasks(self) | All tasks in the hierarchy, affected by this group. | 6.295978 | 5.724887 | 1.099756 |
tasks = set()
for ctrl in self.controllers.values():
tasks.update(ctrl.tasks)
return tasks | def tasks(self) | Tasks in this exact group | 4.848139 | 4.413859 | 1.09839 |
return os.path.join(self.node.full_path, filename) | def filepath(self, filename) | The full path to a file | 9.058199 | 9.48872 | 0.954628 |
with open(self.filepath(filename)) as f:
return f.read().strip() | def get_property(self, filename) | Opens the file and reads the value | 5.829428 | 5.596986 | 1.04153 |
with open(self.filepath(filename), "w") as f:
return f.write(str(value)) | def set_property(self, filename, value) | Opens the file and writes the value | 5.258518 | 4.852909 | 1.083581 |
yield root
for child in root.children:
for el in walk_tree(child):
yield el | def walk_tree(root) | Pre-order depth-first | 3.213095 | 3.448675 | 0.93169 |
for child in root.children:
for el in walk_up_tree(child):
yield el
yield root | def walk_up_tree(root) | Post-order depth-first | 3.577699 | 3.630008 | 0.98559 |
stat = os.lstat(dev_path)
return os.major(stat.st_rdev), os.minor(stat.st_rdev) | def get_device_major_minor(dev_path) | Returns the device (major, minor) tuple for simplicity
:param dev_path: Path to the device
:return: (device major, device minor)
:rtype: (int, int) | 2.662945 | 3.014637 | 0.883339 |
schema = Schema(self.__class__.SCHEMA)
resolver = RefResolver.from_schema(
schema,
store=REGISTRY,
)
validate(self, schema, resolver=resolver) | def validate(self) | Validate that this instance matches its schema. | 6.503329 | 5.501337 | 1.182136 |
with closing(StringIO()) as fileobj:
self.dump(fileobj)
return fileobj.getvalue() | def dumps(self) | Dump this instance as YAML. | 4.231208 | 3.853137 | 1.09812 |
with closing(StringIO(s)) as fileobj:
return cls.load(fileobj) | def loads(cls, s) | Load an instance of this class from YAML. | 4.994169 | 5.13394 | 0.972775 |
schema = self.__class__.SCHEMA
# first try plain properties
plain_schema = schema.get("properties", {}).get(key)
if plain_schema is not None:
return plain_schema
# then try pattern properties
pattern_properties = schema.get("patternProperties", {})
... | def property_schema(self, key) | Lookup the schema for a specific property. | 3.254154 | 3.201818 | 1.016346 |
return type(class_name, (base,), dict(SCHEMA=schema)) | def make(class_name, base, schema) | Create a new schema aware type. | 4.791976 | 4.732973 | 1.012466 |
class_name = make_class_name(name)
cls = register(make(class_name, base, schema))
globals()[class_name] = cls | def make_definition(name, base, schema) | Create a new definition. | 5.427961 | 5.639076 | 0.962562 |
definition_name = make_definition_name(cls.__name__)
REGISTRY[definition_name] = cls
return cls | def register(cls) | Register a class. | 5.465171 | 5.475899 | 0.998041 |
if not isinstance(schema, dict) or "$ref" not in schema:
return None
ref = schema["$ref"]
return REGISTRY.get(ref) | def lookup(schema) | Lookup a class by property schema. | 4.015959 | 3.563607 | 1.126937 |
if self._connected or self.is_alive():
raise ConnectionExistsError("Already connected")
# After starting the thread we wait for it to post us
# an event signifying that connection is established. This
# ensures that the caller only resumes when we are fully connected.
self.start()
wit... | def connect(self) | Connects to the lutron controller. | 8.866474 | 8.655163 | 1.024414 |
_LOGGER.debug("Sending: %s" % cmd)
try:
self._telnet.write(cmd.encode('ascii') + b'\r\n')
except BrokenPipeError:
self._disconnect_locked() | def _send_locked(self, cmd) | Sends the specified command to the lutron controller.
Assumes self._lock is held. | 4.433293 | 4.01655 | 1.103757 |
self._telnet = telnetlib.Telnet(self._host)
self._telnet.read_until(LutronConnection.USER_PROMPT)
self._telnet.write(self._user + b'\r\n')
self._telnet.read_until(LutronConnection.PW_PROMPT)
self._telnet.write(self._password + b'\r\n')
self._telnet.read_until(LutronConnection.PROMPT)
s... | def _do_login_locked(self) | Executes the login procedure (telnet) as well as setting up some
connection defaults like turning off the prompt, etc. | 2.389072 | 2.252195 | 1.060775 |
self._connected = False
self._connect_cond.notify_all()
self._telnet = None
_LOGGER.warning("Disconnected") | def _disconnect_locked(self) | Closes the current connection. Assume self._lock is held. | 8.313778 | 7.182977 | 1.157428 |
with self._lock:
if not self._connected:
_LOGGER.info("Connecting")
self._do_login_locked()
self._connected = True
self._connect_cond.notify_all()
_LOGGER.info("Connected") | def _maybe_reconnect(self) | Reconnects to the controller if we have been previously disconnected. | 5.344122 | 4.925615 | 1.084966 |
_LOGGER.info("Started")
while True:
self._maybe_reconnect()
line = ''
try:
# If someone is sending a command, we can lose our connection so grab a
# copy beforehand. We don't need the lock because if the connection is
# open, we are the only ones that will read fro... | def run(self) | Main thread function to maintain connection and receive remote status. | 7.260301 | 6.823193 | 1.064062 |
import xml.etree.ElementTree as ET
root = ET.fromstring(self._xml_db_str)
# The structure is something like this:
# <Areas>
# <Area ...>
# <DeviceGroups ...>
# <Scenes ...>
# <ShadeGroups ...>
# <Outputs ...>
# <Areas ...>
# <Area ...>
#... | def parse(self) | Main entrypoint into the parser. It interprets and creates all the
relevant Lutron objects and stuffs them into the appropriate hierarchy. | 4.886105 | 4.757271 | 1.027082 |
area = Area(self._lutron,
name=area_xml.get('Name'),
integration_id=int(area_xml.get('IntegrationID')),
occupancy_group_id=area_xml.get('OccupancyGroupAssignedToID'))
for output_xml in area_xml.find('Outputs'):
output = self._parse_output(output_xml)
... | def _parse_area(self, area_xml) | Parses an Area tag, which is effectively a room, depending on how the
Lutron controller programming was done. | 3.349988 | 3.203175 | 1.045834 |
output = Output(self._lutron,
name=output_xml.get('Name'),
watts=int(output_xml.get('Wattage')),
output_type=output_xml.get('OutputType'),
integration_id=int(output_xml.get('IntegrationID')))
return output | def _parse_output(self, output_xml) | Parses an output, which is generally a switch controlling a set of
lights/outlets, etc. | 4.889591 | 4.354074 | 1.122992 |
keypad = Keypad(self._lutron,
name=keypad_xml.get('Name'),
integration_id=int(keypad_xml.get('IntegrationID')))
components = keypad_xml.find('Components')
if not components:
return keypad
for comp in components:
if comp.tag != 'Component':
... | def _parse_keypad(self, keypad_xml) | Parses a keypad device (the Visor receiver is technically a keypad too). | 2.301383 | 2.237399 | 1.028598 |
button_xml = component_xml.find('Button')
name = button_xml.get('Engraving')
button_type = button_xml.get('ButtonType')
direction = button_xml.get('Direction')
# Hybrid keypads have dimmer buttons which have no engravings.
if button_type == 'SingleSceneRaiseLower':
name = 'Dimmer ' + ... | def _parse_button(self, keypad, component_xml) | Parses a button device that part of a keypad. | 5.065372 | 4.748192 | 1.0668 |
component_num = int(component_xml.get('ComponentNumber'))
led_num = component_num - 80
led = Led(self._lutron, keypad,
name=('LED %d' % led_num),
led_num=led_num,
component_num=component_num)
return led | def _parse_led(self, keypad, component_xml) | Parses an LED device that part of a keypad. | 4.646671 | 4.364254 | 1.064712 |
return MotionSensor(self._lutron,
name=sensor_xml.get('Name'),
integration_id=int(sensor_xml.get('IntegrationID'))) | def _parse_motion_sensor(self, sensor_xml) | Parses a motion sensor object.
TODO: We don't actually do anything with these yet. There's a lot of info
that needs to be managed to do this right. We'd have to manage the occupancy
groups, what's assigned to them, and when they go (un)occupied. We'll handle
this later. | 8.320045 | 7.985301 | 1.04192 |
if not isinstance(obj, LutronEntity):
raise InvalidSubscription("Subscription target not a LutronEntity")
_LOGGER.warning("DEPRECATED: Subscribing via Lutron.subscribe is obsolete. "
"Please use LutronEntity.subscribe")
if obj not in self._legacy_subscribers:
self._legac... | def subscribe(self, obj, handler) | Subscribes to status updates of the requested object.
DEPRECATED
The handler will be invoked when the controller sends a notification
regarding changed state. The user can then further query the object for the
state itself. | 6.22123 | 6.07162 | 1.024641 |
ids = self._ids.setdefault(cmd_type, {})
if obj.id in ids:
raise IntegrationIdExistsError
self._ids[cmd_type][obj.id] = obj | def register_id(self, cmd_type, obj) | Registers an object (through its integration id) to receive update
notifications. This is the core mechanism how Output and Keypad objects get
notified when the controller sends status updates. | 4.68467 | 3.938765 | 1.189376 |
if obj in self._legacy_subscribers:
self._legacy_subscribers[obj](obj) | def _dispatch_legacy_subscriber(self, obj, *args, **kwargs) | This dispatches the registered callback for 'obj'. This is only used
for legacy subscribers since new users should register with the target
object directly. | 6.033593 | 4.840557 | 1.246467 |
if line == '':
return
# Only handle query response messages, which are also sent on remote status
# updates (e.g. user manually pressed a keypad button)
if line[0] != Lutron.OP_RESPONSE:
_LOGGER.debug("ignoring %s" % line)
return
parts = line[1:].split(',')
cmd_type = part... | def _recv(self, line) | Invoked by the connection manager to process incoming data. | 4.4438 | 4.38795 | 1.012728 |
out_cmd = ",".join(
(cmd, str(integration_id)) + tuple((str(x) for x in args)))
self._conn.send(op + out_cmd) | def send(self, op, cmd, integration_id, *args) | Formats and sends the requested command to the Lutron controller. | 6.035439 | 5.822347 | 1.036599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.