_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q6800 | SeqRepo._get_unique_seqid | train | def _get_unique_seqid(self, alias, namespace):
"""given alias and namespace, return seq_id if exactly one distinct
sequence id is found, raise KeyError if there's no match, or
raise ValueError if there's more than one match.
"""
recs = self.aliases.find_aliases(alias=alias, nam... | python | {
"resource": ""
} |
q6801 | SeqAliasDB.find_aliases | train | def find_aliases(self, seq_id=None, namespace=None, alias=None, current_only=True, translate_ncbi_namespace=None):
"""returns iterator over alias annotation records that match criteria
The arguments, all optional, restrict the records that are
returned. Without arguments, all aliases a... | python | {
"resource": ""
} |
q6802 | SeqAliasDB.store_alias | train | def store_alias(self, seq_id, namespace, alias):
"""associate a namespaced alias with a sequence
Alias association with sequences is idempotent: duplicate
associations are discarded silently.
"""
if not self._writeable:
raise RuntimeError("Cannot write -- opened re... | python | {
"resource": ""
} |
q6803 | add_assembly_names | train | def add_assembly_names(opts):
"""add assembly names as aliases to existing sequences
Specifically, associate aliases like GRCh37.p9:1 with existing
refseq accessions
```
[{'aliases': ['chr19'],
'assembly_unit': 'Primary Assembly',
'genbank_ac': 'CM000681.2',
'length': 58617616,
... | python | {
"resource": ""
} |
q6804 | snapshot | train | def snapshot(opts):
"""snapshot a seqrepo data directory by hardlinking sequence files,
copying sqlite databases, and remove write permissions from directories
"""
seqrepo_dir = os.path.join(opts.root_directory, opts.instance_name)
dst_dir = opts.destination_name
if not dst_dir.startswith("/")... | python | {
"resource": ""
} |
q6805 | StorageBackend.set_sqlite_pragmas | train | def set_sqlite_pragmas(self):
"""
Sets the connection PRAGMAs for the sqlalchemy engine stored in self.engine.
It currently sets:
- journal_mode to WAL
:return: None
"""
def _pragmas_on_connect(dbapi_con, con_record):
dbapi_con.execute("PRAGMA journ... | python | {
"resource": ""
} |
q6806 | StorageBackend.schedule_job | train | def schedule_job(self, j):
"""
Add the job given by j to the job queue.
Note: Does not actually run the job.
"""
job_id = uuid.uuid4().hex
j.job_id = job_id
session = self.sessionmaker()
orm_job = ORMJob(
id=job_id,
state=j.state,... | python | {
"resource": ""
} |
q6807 | StorageBackend.mark_job_as_canceling | train | def mark_job_as_canceling(self, job_id):
"""
Mark the job as requested for canceling. Does not actually try to cancel a running job.
:param job_id: the job to be marked as canceling.
:return: the job object
"""
job, _ = self._update_job_state(job_id, State.CANCELING)
... | python | {
"resource": ""
} |
q6808 | BaseWorkerBackend.handle_incoming_message | train | def handle_incoming_message(self, msg):
"""
Start or cancel a job, based on the msg.
If msg.type == MessageType.START_JOB, then start the job given by msg.job.
If msg.type == MessageType.CANCEL_JOB, then try to cancel the job given by msg.job.job_id.
Args:
msg (bar... | python | {
"resource": ""
} |
q6809 | WorkerBackend.schedule_job | train | def schedule_job(self, job):
"""
schedule a job to the type of workers spawned by self.start_workers.
:param job: the job to schedule for running.
:return:
"""
l = _reraise_with_traceback(job.get_lambda_to_execute())
future = self.workers.submit(l, update_progr... | python | {
"resource": ""
} |
q6810 | WorkerBackend._check_for_cancel | train | def _check_for_cancel(self, job_id, current_stage=""):
"""
Check if a job has been requested to be cancelled. When called, the calling function can
optionally give the stage it is currently in, so the user has information on where the job
was before it was cancelled.
:param job_... | python | {
"resource": ""
} |
q6811 | Scheduler.request_job_cancel | train | def request_job_cancel(self, job_id):
"""
Send a message to the workers to cancel the job with job_id. We then mark the job in the storage
as being canceled.
:param job_id: the job to cancel
:return: None
"""
msg = CancelMessage(job_id)
self.messaging_bac... | python | {
"resource": ""
} |
q6812 | Scheduler.handle_worker_messages | train | def handle_worker_messages(self, timeout):
"""
Read messages that are placed in self.incoming_mailbox,
and then update the job states corresponding to each message.
Args:
timeout: How long to wait for an incoming message, if the mailbox is empty right now.
Returns: ... | python | {
"resource": ""
} |
q6813 | Job.get_lambda_to_execute | train | def get_lambda_to_execute(self):
"""
return a function that executes the function assigned to this job.
If job.track_progress is None (the default), the returned function accepts no argument
and simply needs to be called. If job.track_progress is True, an update_progress function
... | python | {
"resource": ""
} |
q6814 | Job.percentage_progress | train | def percentage_progress(self):
"""
Returns a float between 0 and 1, representing the current job's progress in its task.
If total_progress is not given or 0, just return self.progress.
:return: float corresponding to the total percentage progress of the job.
"""
if self... | python | {
"resource": ""
} |
q6815 | Client.schedule | train | def schedule(self, func, *args, **kwargs):
"""
Schedules a function func for execution.
One special parameter is track_progress. If passed in and not None, the func will be passed in a
keyword parameter called update_progress:
def update_progress(progress, total_progress, stage... | python | {
"resource": ""
} |
q6816 | Client.wait | train | def wait(self, job_id, timeout=None):
"""
Wait until the job given by job_id has a new update.
:param job_id: the id of the job to wait for.
:param timeout: how long to wait for a job state change before timing out.
:return: Job object corresponding to job_id
"""
... | python | {
"resource": ""
} |
q6817 | Client.wait_for_completion | train | def wait_for_completion(self, job_id, timeout=None):
"""
Wait for the job given by job_id to change to COMPLETED or CANCELED. Raises a
iceqube.exceptions.TimeoutError if timeout is exceeded before each job change.
:param job_id: the id of the job to wait for.
:param timeout: how... | python | {
"resource": ""
} |
q6818 | invalidate_cache_after_error | train | def invalidate_cache_after_error(f):
"""
catch any exception and invalidate internal cache with list of nodes
"""
@wraps(f)
def wrapper(self, *args, **kwds):
try:
return f(self, *args, **kwds)
except Exception:
self.clear_cluster_nodes_cache()
rais... | python | {
"resource": ""
} |
q6819 | ElastiCache.update_params | train | def update_params(self, params):
"""
update connection params to maximize performance
"""
if not params.get('BINARY', True):
raise Warning('To increase performance please use ElastiCache'
' in binary mode')
else:
params['BINARY'] ... | python | {
"resource": ""
} |
q6820 | ElastiCache.get_cluster_nodes | train | def get_cluster_nodes(self):
"""
return list with all nodes in cluster
"""
if not hasattr(self, '_cluster_nodes_cache'):
server, port = self._servers[0].split(':')
try:
self._cluster_nodes_cache = (
get_cluster_info(server, port... | python | {
"resource": ""
} |
q6821 | restore_placeholders | train | def restore_placeholders(msgid, translation):
"""Restore placeholders in the translated message."""
placehoders = re.findall(r'(\s*)(%(?:\(\w+\))?[sd])(\s*)', msgid)
return re.sub(
r'(\s*)(__[\w]+?__)(\s*)',
lambda matches: '{0}{1}{2}'.format(placehoders[0][0], placehoders[0][1], placehoders... | python | {
"resource": ""
} |
q6822 | Command.translate_file | train | def translate_file(self, root, file_name, target_language):
"""
convenience method for translating a pot file
:param root: the absolute path of folder where the file is present
:param file_name: name of the file to be translated (it should be a pot file)
:param ... | python | {
"resource": ""
} |
q6823 | Command.get_strings_to_translate | train | def get_strings_to_translate(self, po):
"""Return list of string to translate from po file.
:param po: POFile object to translate
:type po: polib.POFile
:return: list of string to translate
:rtype: collections.Iterable[six.text_type]
"""
strings = []
for ... | python | {
"resource": ""
} |
q6824 | Command.update_translations | train | def update_translations(self, entries, translated_strings):
"""Update translations in entries.
The order and number of translations should match to get_strings_to_translate() result.
:param entries: list of entries to translate
:type entries: collections.Iterable[polib.POEntry] | polib... | python | {
"resource": ""
} |
q6825 | load_ply | train | def load_ply(fileobj):
"""Same as load_ply, but takes a file-like object"""
def nextline():
"""Read next line, skip comments"""
while True:
line = fileobj.readline()
assert line != '' # eof
if not line.startswith('comment'):
return line.strip(... | python | {
"resource": ""
} |
q6826 | read_ssh_config | train | def read_ssh_config(path):
"""
Read ssh config file and return parsed SshConfig
"""
with open(path, "r") as fh_:
lines = fh_.read().splitlines()
return SshConfig(lines) | python | {
"resource": ""
} |
q6827 | _remap_key | train | def _remap_key(key):
""" Change key into correct casing if we know the parameter """
if key in KNOWN_PARAMS:
return key
if key.lower() in known_params:
return KNOWN_PARAMS[known_params.index(key.lower())]
return key | python | {
"resource": ""
} |
q6828 | SshConfig.parse | train | def parse(self, lines):
"""Parse lines from ssh config file"""
cur_entry = None
for line in lines:
kv_ = _key_value(line)
if len(kv_) > 1:
key, value = kv_
if key.lower() == "host":
cur_entry = value
... | python | {
"resource": ""
} |
q6829 | SshConfig.host | train | def host(self, host):
"""
Return the configuration of a specific host as a dictionary.
Dictionary always contains lowercase versions of the attribute names.
Parameters
----------
host : the host to return values for.
Returns
-------
dict of key ... | python | {
"resource": ""
} |
q6830 | SshConfig.set | train | def set(self, host, **kwargs):
"""
Set configuration values for an existing host.
Overwrites values for existing settings, or adds new settings.
Parameters
----------
host : the Host to modify.
**kwargs : The new configuration parameters
"""
self.... | python | {
"resource": ""
} |
q6831 | SshConfig.unset | train | def unset(self, host, *args):
"""
Removes settings for a host.
Parameters
----------
host : the host to remove settings from.
*args : list of settings to removes.
"""
self.__check_host_args(host, args)
remove_idx = [idx for idx, x in enumerate(sel... | python | {
"resource": ""
} |
q6832 | SshConfig.rename | train | def rename(self, old_host, new_host):
"""
Renames a host configuration.
Parameters
----------
old_host : the host to rename.
new_host : the new host value
"""
if new_host in self.hosts_:
raise ValueError("Host %s: already exists." % new_host)
... | python | {
"resource": ""
} |
q6833 | SshConfig.add | train | def add(self, host, **kwargs):
"""
Add another host to the SSH configuration.
Parameters
----------
host: The Host entry to add.
**kwargs: The parameters for the host (without "Host" parameter itself)
"""
if host in self.hosts_:
raise ValueErr... | python | {
"resource": ""
} |
q6834 | SshConfig.remove | train | def remove(self, host):
"""
Removes a host from the SSH configuration.
Parameters
----------
host : The host to remove
"""
if host not in self.hosts_:
raise ValueError("Host %s: not found." % host)
self.hosts_.remove(host)
# remove lin... | python | {
"resource": ""
} |
q6835 | SshConfig.write | train | def write(self, path):
"""
Writes ssh config file
Parameters
----------
path : The file to write to
"""
with open(path, "w") as fh_:
fh_.write(self.config()) | python | {
"resource": ""
} |
q6836 | orthogonal_vector | train | def orthogonal_vector(v):
"""Return an arbitrary vector that is orthogonal to v"""
if v[1] != 0 or v[2] != 0:
c = (1, 0, 0)
else:
c = (0, 1, 0)
return np.cross(v, c) | python | {
"resource": ""
} |
q6837 | show_plane | train | def show_plane(orig, n, scale=1.0, **kwargs):
"""
Show the plane with the given origin and normal. scale give its size
"""
b1 = orthogonal_vector(n)
b1 /= la.norm(b1)
b2 = np.cross(b1, n)
b2 /= la.norm(b2)
verts = [orig + scale*(-b1 - b2),
orig + scale*(b1 - b2),
... | python | {
"resource": ""
} |
q6838 | triangle_intersects_plane | train | def triangle_intersects_plane(mesh, tid, plane):
"""
Returns true if the given triangle is cut by the plane. This will return
false if a single vertex of the triangle lies on the plane
"""
dists = [point_to_plane_dist(mesh.verts[vid], plane)
for vid in mesh.tris[tid]]
side = np.sign... | python | {
"resource": ""
} |
q6839 | compute_triangle_plane_intersections | train | def compute_triangle_plane_intersections(mesh, tid, plane, dist_tol=1e-8):
"""
Compute the intersection between a triangle and a plane
Returns a list of intersections in the form
(INTERSECT_EDGE, <intersection point>, <edge>) for edges intersection
(INTERSECT_VERTEX, <intersection point>, <... | python | {
"resource": ""
} |
q6840 | _walk_polyline | train | def _walk_polyline(tid, intersect, T, mesh, plane, dist_tol):
"""
Given an intersection, walk through the mesh triangles, computing
intersection with the cut plane for each visited triangle and adding
those intersection to a polyline.
"""
T = set(T)
p = []
# Loop until we have explored a... | python | {
"resource": ""
} |
q6841 | cross_section | train | def cross_section(verts, tris, plane_orig, plane_normal, **kwargs):
"""
Compute the planar cross section of a mesh. This returns a set of
polylines.
Args:
verts: Nx3 array of the vertices position
faces: Nx3 array of the faces, containing vertex indices
plane_orig: 3-vector indi... | python | {
"resource": ""
} |
q6842 | merge_close_vertices | train | def merge_close_vertices(verts, faces, close_epsilon=1e-5):
"""
Will merge vertices that are closer than close_epsilon.
Warning, this has a O(n^2) memory usage because we compute the full
vert-to-vert distance matrix. If you have a large mesh, might want
to use some kind of spatial search structure... | python | {
"resource": ""
} |
q6843 | signed_to_float | train | def signed_to_float(hex: str) -> float:
"""Convert signed hexadecimal to floating value."""
if int(hex, 16) & 0x8000:
return -(int(hex, 16) & 0x7FFF) / 10
else:
return int(hex, 16) / 10 | python | {
"resource": ""
} |
q6844 | encode_packet | train | def encode_packet(packet: dict) -> str:
"""Construct packet string from packet dictionary.
>>> encode_packet({
... 'protocol': 'newkaku',
... 'id': '000001',
... 'switch': '01',
... 'command': 'on',
... })
'10;newkaku;000001;01;on;'
"""
if packet['protocol'] == '... | python | {
"resource": ""
} |
q6845 | serialize_packet_id | train | def serialize_packet_id(packet: dict) -> str:
"""Serialize packet identifiers into one reversable string.
>>> serialize_packet_id({
... 'protocol': 'newkaku',
... 'id': '000001',
... 'switch': '01',
... 'command': 'on',
... })
'newkaku_000001_01'
>>> serialize_packet... | python | {
"resource": ""
} |
q6846 | packet_events | train | def packet_events(packet: dict) -> Generator:
"""Return list of all events in the packet.
>>> x = list(packet_events({
... 'protocol': 'alecto v1',
... 'id': 'ec02',
... 'temperature': 1.0,
... 'temperature_unit': '°C',
... 'humidity': 10,
... 'humidity_unit': '%... | python | {
"resource": ""
} |
q6847 | RFLinkProxy.forward_packet | train | def forward_packet(self, writer, packet, raw_packet):
"""Forward packet from client to RFLink."""
peer = writer.get_extra_info('peername')
log.debug(' %s:%s: forwarding data: %s', peer[0], peer[1], packet)
if 'command' in packet:
packet_id = serialize_packet_id(packet)
... | python | {
"resource": ""
} |
q6848 | RFLinkProxy.client_connected_callback | train | def client_connected_callback(self, reader, writer):
"""Handle connected client."""
peer = writer.get_extra_info('peername')
clients.append((reader, writer, peer))
log.info("Incoming connection from: %s:%s", peer[0], peer[1])
try:
while True:
data = yi... | python | {
"resource": ""
} |
q6849 | RFLinkProxy.raw_callback | train | def raw_callback(self, raw_packet):
"""Send data to all connected clients."""
if not ';PONG;' in raw_packet:
log.info('forwarding packet %s to clients', raw_packet)
else:
log.debug('forwarding packet %s to clients', raw_packet)
writers = [i[1] for i in list(client... | python | {
"resource": ""
} |
q6850 | RFLinkProxy.reconnect | train | def reconnect(self, exc=None):
"""Schedule reconnect after connection has been unexpectedly lost."""
# Reset protocol binding before starting reconnect
self.protocol = None
if not self.closing:
log.warning('disconnected from Rflink, reconnecting')
self.loop.creat... | python | {
"resource": ""
} |
q6851 | create_rflink_connection | train | def create_rflink_connection(port=None, host=None, baud=57600, protocol=RflinkProtocol,
packet_callback=None, event_callback=None,
disconnect_callback=None, ignore=None, loop=None):
"""Create Rflink manager class, returns transport coroutine."""
# use de... | python | {
"resource": ""
} |
q6852 | ProtocolBase.data_received | train | def data_received(self, data):
"""Add incoming data to buffer."""
data = data.decode()
log.debug('received data: %s', data.strip())
self.buffer += data
self.handle_lines() | python | {
"resource": ""
} |
q6853 | ProtocolBase.send_raw_packet | train | def send_raw_packet(self, packet: str):
"""Encode and put packet string onto write buffer."""
data = packet + '\r\n'
log.debug('writing data: %s', repr(data))
self.transport.write(data.encode()) | python | {
"resource": ""
} |
q6854 | ProtocolBase.log_all | train | def log_all(self, file):
"""Log all data received from RFLink to file."""
global rflink_log
if file == None:
rflink_log = None
else:
log.debug('logging to: %s', file)
rflink_log = open(file, 'a') | python | {
"resource": ""
} |
q6855 | PacketHandling.handle_packet | train | def handle_packet(self, packet):
"""Process incoming packet dict and optionally call callback."""
if self.packet_callback:
# forward to callback
self.packet_callback(packet)
else:
print('packet', packet) | python | {
"resource": ""
} |
q6856 | PacketHandling.send_command | train | def send_command(self, device_id, action):
"""Send device command to rflink gateway."""
command = deserialize_packet_id(device_id)
command['command'] = action
log.debug('sending command: %s', command)
self.send_packet(command) | python | {
"resource": ""
} |
q6857 | CommandSerialization.send_command_ack | train | def send_command_ack(self, device_id, action):
"""Send command, wait for gateway to repond with acknowledgment."""
# serialize commands
yield from self._ready_to_send.acquire()
acknowledgement = None
try:
self._command_ack.clear()
self.send_command(device_... | python | {
"resource": ""
} |
q6858 | EventHandling._handle_packet | train | def _handle_packet(self, packet):
"""Event specific packet handling logic.
Break packet into events and fires configured event callback or
nicely prints events for console.
"""
events = packet_events(packet)
for event in events:
if self.ignore_event(event['i... | python | {
"resource": ""
} |
q6859 | EventHandling.ignore_event | train | def ignore_event(self, event_id):
"""Verify event id against list of events to ignore.
>>> e = EventHandling(ignore=[
... 'test1_00',
... 'test2_*',
... ])
>>> e.ignore_event('test1_00')
True
>>> e.ignore_event('test2_00')
True
>>> e.i... | python | {
"resource": ""
} |
q6860 | _initial_population_gsa | train | 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... | python | {
"resource": ""
} |
q6861 | _new_population_gsa | train | 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
"""
# Update th... | python | {
"resource": ""
} |
q6862 | _next_grav_gsa | train | 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
"""
return grav_initial * math.exp(
-grav_reduction_rate * iteration / float(max_iterations)) | python | {
"resource": ""
} |
q6863 | _get_masses | train | def _get_masses(fitnesses):
"""Convert fitnesses into masses, as given by GSA algorithm."""
# 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 i... | python | {
"resource": ""
} |
q6864 | _gsa_force | train | 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... | python | {
"resource": ""
} |
q6865 | _gsa_total_force | train | 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.
"""
if len(force_vectors) == 0:
return [0.0] * vector... | python | {
"resource": ""
} |
q6866 | _gsa_update_velocity | train | def _gsa_update_velocity(velocity, acceleration):
"""Stochastically update velocity given acceleration.
In GSA paper, velocity is v_i, acceleration is a_i
"""
# The GSA algorithm specifies that the new velocity for each dimension
# is a sum of a random fraction of its current velocity in that dime... | python | {
"resource": ""
} |
q6867 | _new_population_genalg | train | def _new_population_genalg(population,
fitnesses,
mutation_chance=0.02,
crossover_chance=0.7,
selection_function=gaoperators.tournament_selection,
crossover_function=gaoperators.one_poi... | python | {
"resource": ""
} |
q6868 | _crossover | train | def _crossover(population, crossover_chance, crossover_operator):
"""Perform crossover on a population, return the new crossed-over population."""
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 i... | python | {
"resource": ""
} |
q6869 | random_real_solution | train | def random_real_solution(solution_size, lower_bounds, upper_bounds):
"""Make a list of random real numbers between lower and upper bounds."""
return [
random.uniform(lower_bounds[i], upper_bounds[i])
for i in range(solution_size)
] | python | {
"resource": ""
} |
q6870 | make_population | train | def make_population(population_size, solution_generator, *args, **kwargs):
"""Make a population with the supplied generator."""
return [
solution_generator(*args, **kwargs) for _ in range(population_size)
] | python | {
"resource": ""
} |
q6871 | tournament_selection | train | 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 ... | python | {
"resource": ""
} |
q6872 | stochastic_selection | train | def stochastic_selection(population, fitnesses):
"""Create a list of parents with stochastic universal sampling."""
pop_size = len(population)
probabilities = _fitnesses_to_probabilities(fitnesses)
# Create selection list (for stochastic universal sampling)
selection_list = []
selection_spacing... | python | {
"resource": ""
} |
q6873 | roulette_selection | train | def roulette_selection(population, fitnesses):
"""Create a list of parents with roulette selection."""
probabilities = _fitnesses_to_probabilities(fitnesses)
intermediate_population = []
for _ in range(len(population)):
# Choose a random individual
selection = random.uniform(0.0, 1.0)
... | python | {
"resource": ""
} |
q6874 | _diversity_metric | train | 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].
"""
# Edge case for empty population
# If there are no other solutions, the giv... | python | {
"resource": ""
} |
q6875 | _manhattan_distance | train | def _manhattan_distance(vec_a, vec_b):
"""Return manhattan distance between two lists of numbers."""
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)) | python | {
"resource": ""
} |
q6876 | _fitnesses_to_probabilities | train | def _fitnesses_to_probabilities(fitnesses):
"""Return a list of probabilities proportional to fitnesses."""
# 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)
... | python | {
"resource": ""
} |
q6877 | one_point_crossover | train | 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
"""
# The po... | python | {
"resource": ""
} |
q6878 | uniform_crossover | train | 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
"""
chromosome_length = len(parents[0])
children = [[], []]
for i in range(chromosome_length):
select... | python | {
"resource": ""
} |
q6879 | random_flip_mutate | train | 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).
"""
for chromosome in population: # For every chromosome in the population
for i in range(len(chromosome)): # For ever... | python | {
"resource": ""
} |
q6880 | _duplicates | train | def _duplicates(list_):
"""Return dict mapping item -> indices."""
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 | python | {
"resource": ""
} |
q6881 | _parse_parameter_locks | train | 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.
"""
# WARNING: meta_parameters is modified ... | python | {
"resource": ""
} |
q6882 | _get_hyperparameter_solution_size | train | def _get_hyperparameter_solution_size(meta_parameters):
"""Determine size of binary encoding of parameters.
Also adds binary size information for each parameter.
"""
# WARNING: meta_parameters is modified inline
solution_size = 0
for _, parameters in meta_parameters.iteritems():
if par... | python | {
"resource": ""
} |
q6883 | _make_hyperparameter_decode_func | train | def _make_hyperparameter_decode_func(locked_values, meta_parameters):
"""Create a function that converts the binary solution to parameters."""
# Locked parameters are also returned by decode function, but are not
# based on solution
def decode(solution):
"""Convert solution into dict of hyperp... | python | {
"resource": ""
} |
q6884 | _meta_fitness_func | train | 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 ... | python | {
"resource": ""
} |
q6885 | Problem.copy | train | 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 thos... | python | {
"resource": ""
} |
q6886 | Problem.get_fitness | train | def get_fitness(self, solution):
"""Return fitness for the given solution."""
return self._fitness_function(solution, *self._fitness_args,
**self._fitness_kwargs) | python | {
"resource": ""
} |
q6887 | Problem.decode_solution | train | def decode_solution(self, encoded_solution):
"""Return solution from an encoded representation."""
return self._decode_function(encoded_solution, *self._decode_args,
**self._decode_kwargs) | python | {
"resource": ""
} |
q6888 | Optimizer.optimize | train | 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:
... | python | {
"resource": ""
} |
q6889 | Optimizer._reset_bookkeeping | train | def _reset_bookkeeping(self):
"""Reset bookkeeping parameters to initial values.
Call before beginning optimization.
"""
self.iteration = 0
self.fitness_runs = 0
self.best_solution = None
self.best_fitness = None
self.solution_found = False | python | {
"resource": ""
} |
q6890 | Optimizer._get_fitnesses | train | def _get_fitnesses(self,
problem,
population,
cache_encoded=True,
cache_solution=False,
pool=None):
"""Get the fitness for every solution in a population.
Args:
problem: Proble... | python | {
"resource": ""
} |
q6891 | Optimizer._pmap | train | 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... | python | {
"resource": ""
} |
q6892 | Optimizer._set_hyperparameters | train | def _set_hyperparameters(self, parameters):
"""Set internal optimization parameters."""
for name, value in parameters.iteritems():
try:
getattr(self, name)
except AttributeError:
raise ValueError(
'Each parameter in parameters m... | python | {
"resource": ""
} |
q6893 | Optimizer._get_hyperparameters | train | def _get_hyperparameters(self):
"""Get internal optimization parameters."""
hyperparameters = {}
for key in self._hyperparameters:
hyperparameters[key] = getattr(self, key)
return hyperparameters | python | {
"resource": ""
} |
q6894 | Optimizer.optimize_hyperparameters | train | def optimize_hyperparameters(self,
problems,
parameter_locks=None,
smoothing=20,
max_iterations=100,
_meta_optimizer=None,
... | python | {
"resource": ""
} |
q6895 | compare | train | 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 ... | python | {
"resource": ""
} |
q6896 | benchmark | train | 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.
Retu... | python | {
"resource": ""
} |
q6897 | aggregate | train | 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.
"""
aggregate_stats = {'means': [], 'standard_deviations': []}
for op... | python | {
"resource": ""
} |
q6898 | _mean_of_runs | train | 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
"""
num_runs = len(stats[key])
first = stats[key][0]
mean = {}
for stat_key i... | python | {
"resource": ""
} |
q6899 | _sd_of_runs | train | 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
"""
num_runs = len(stats... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.