Search is not available for this dataset
text
stringlengths
75
104k
def file_observer(population, num_generations, num_evaluations, args): """Print the output of the evolutionary computation to a file. This function saves the results of the evolutionary computation to two files. The first file, which by default is named 'inspyred-statistics-file-<timestamp>.csv', ...
def archive_observer(population, num_generations, num_evaluations, args): """Print the current archive to the screen. This function displays the current archive of the evolutionary computation to the screen. .. Arguments: population -- the population of Individuals num_generati...
def plot_observer(population, num_generations, num_evaluations, args): """Plot the output of the evolutionary computation as a graph. This function plots the performance of the EC as a line graph using matplotlib and numpy. The graph consists of a blue line representing the best fitness, a gr...
def diversity_termination(population, num_generations, num_evaluations, args): """Return True if population diversity is less than a minimum diversity. This function calculates the Euclidean distance between every pair of individuals in the population. It then compares the maximum of those distance...
def average_fitness_termination(population, num_generations, num_evaluations, args): """Return True if the population's average fitness is near its best fitness. This function calculates the average fitness of the population, as well as the best fitness. If the difference between those values is less ...
def evaluation_termination(population, num_generations, num_evaluations, args): """Return True if the number of function evaluations meets or exceeds a maximum. This function compares the number of function evaluations that have been generated with a specified maximum. It returns True if the maximum i...
def generation_termination(population, num_generations, num_evaluations, args): """Return True if the number of generations meets or exceeds a maximum. This function compares the number of generations with a specified maximum. It returns True if the maximum is met or exceeded. .. Arguments: ...
def time_termination(population, num_generations, num_evaluations, args): """Return True if the elapsed time meets or exceeds a duration of time. This function compares the elapsed time with a specified maximum. It returns True if the maximum is met or exceeded. If the `start_time` keyword argumen...
def user_termination(population, num_generations, num_evaluations, args): """Return True if user presses the ESC key when prompted. This function prompts the user to press the ESC key to terminate the evolution. The prompt persists for a specified number of seconds before evolution continues. Addi...
def no_improvement_termination(population, num_generations, num_evaluations, args): """Return True if the best fitness does not change for a number of generations. This function keeps track of the current best fitness and compares it to the best fitness in previous generations. Whenever those values ar...
def global_optimum(self): """Return a globally optimal solution to this problem. This function returns a globally optimal solution (i.e., a solution that lives on the Pareto front). Since there are many solutions that are Pareto-optimal, this function randomly chooses ...
def generator(self, random, args): """Return a candidate solution for an evolutionary computation.""" locations = [i for i in range(len(self.weights))] random.shuffle(locations) return locations
def constructor(self, random, args): """Return a candidate solution for an ant colony optimization.""" self._use_ants = True candidate = [] while len(candidate) < len(self.weights) - 1: # Find feasible components feasible_components = [] if len(candida...
def evaluator(self, candidates, args): """Return the fitness values for the given candidates.""" fitness = [] if self._use_ants: for candidate in candidates: total = 0 for c in candidate: total += self.weights[c.element[0]][c.elemen...
def generator(self, random, args): """Return a candidate solution for an evolutionary computation.""" if self.duplicates: max_count = [self.capacity // item[0] for item in self.items] return [random.randint(0, m) for m in max_count] else: return [random.choice...
def constructor(self, random, args): """Return a candidate solution for an ant colony optimization.""" self._use_ants = True candidate = [] while len(candidate) < len(self.components): # Find feasible components feasible_components = [] if len(candidat...
def evaluator(self, candidates, args): """Return the fitness values for the given candidates.""" fitness = [] if self._use_ants: for candidate in candidates: total = 0 for c in candidate: total += c.value fitness.app...
def crossover(cross): """Return an inspyred crossover function based on the given function. This function generator takes a function that operates on only two parent candidates to produce an iterable sequence of offspring (typically two). The generator handles the pairing of selected parents and co...
def n_point_crossover(random, mom, dad, args): """Return the offspring of n-point crossover on the candidates. This function performs n-point crossover (NPX). It selects *n* random points without replacement at which to 'cut' the candidate solutions and recombine them. .. Arguments: rando...
def uniform_crossover(random, mom, dad, args): """Return the offspring of uniform crossover on the candidates. This function performs uniform crossover (UX). For each element of the parents, a biased coin is flipped to determine whether the first offspring gets the 'mom' or the 'dad' element. An ...
def partially_matched_crossover(random, mom, dad, args): """Return the offspring of partially matched crossover on the candidates. This function performs partially matched crossover (PMX). This type of crossover assumes that candidates are composed of discrete values that are permutations of a given se...
def arithmetic_crossover(random, mom, dad, args): """Return the offspring of arithmetic crossover on the candidates. This function performs arithmetic crossover (AX), which is similar to a generalized weighted averaging of the candidate elements. The allele of each parent is weighted by the *ax_alpha*...
def blend_crossover(random, mom, dad, args): """Return the offspring of blend crossover on the candidates. This function performs blend crossover (BLX), which is similar to arithmetic crossover with a bit of mutation. It creates offspring whose values are chosen randomly from a range bounded by the ...
def heuristic_crossover(random, candidates, args): """Return the offspring of heuristic crossover on the candidates. It performs heuristic crossover (HX), which is similar to the update rule used in particle swarm optimization. This function also makes use of the bounder function as specified in the ...
def simulated_binary_crossover(random, mom, dad, args): """Return the offspring of simulated binary crossover on the candidates. This function performs simulated binary crossover (SBX), following the implementation in NSGA-II `(Deb et al., ICANNGA 1999) <http://vision.ucsd.edu/~sagarwal/icannga.p...
def laplace_crossover(random, mom, dad, args): """Return the offspring of Laplace crossover on the candidates. This function performs Laplace crosssover (LX), following the implementation specified in (Deep and Thakur, "A new crossover operator for real coded genetic algorithms," Applied Mathemat...
def fitness_statistics(population): """Return the basic statistics of the population's fitness values. This function returns a dictionary containing the "best", "worst", "mean", "median", and "std" fitness values in the population. ("std" is the standard deviation.) A typical usage would be similar...
def generation_plot(file, errorbars=True): """Plot the results of the algorithm using generation statistics. This function creates a plot of the generation fitness statistics (best, worst, median, and average). This function requires the matplotlib library. .. note:: This fun...
def allele_plot(file, normalize=False, alleles=None, generations=None): """Plot the alleles from each generation from the individuals file. This function creates a plot of the individual allele values as they change through the generations. It creates three subplots, one for each of the best, media...
def hypervolume(pareto_set, reference_point=None): """Calculates the hypervolume by slicing objectives (HSO). This function calculates the hypervolume (or S-measure) of a nondominated set using the Hypervolume by Slicing Objectives (HSO) procedure of `While, et al. (IEEE CEC 2005) <http://www.lani...
def gravitational_force(position_a, mass_a, position_b, mass_b): """Returns the gravitational force between the two bodies a and b.""" distance = distance_between(position_a, position_b) # Calculate the direction and magnitude of the force. angle = math.atan2(position_a[1] - position_b[1], position_a[0...
def force_on_satellite(position, mass): """Returns the total gravitational force acting on the body from the Earth and Moon.""" earth_grav_force = gravitational_force(position, mass, earth_position, earth_mass) moon_grav_force = gravitational_force(position, mass, moon_position, moon_mass) F_x = earth_g...
def acceleration_of_satellite(position, mass): """Returns the acceleration based on all forces acting upon the body.""" F_x, F_y = force_on_satellite(position, mass) return F_x / mass, F_y / mass
def truncation_replacement(random, population, parents, offspring, args): """Replaces population with the best of the population and offspring. This function performs truncation replacement, which means that the entire existing population is replaced by the best from among the current population an...
def steady_state_replacement(random, population, parents, offspring, args): """Performs steady-state replacement for the offspring. This function performs steady-state replacement, which means that the offspring replace the least fit individuals in the existing population, even if those offspring a...
def generational_replacement(random, population, parents, offspring, args): """Performs generational replacement with optional weak elitism. This function performs generational replacement, which means that the entire existing population is replaced by the offspring, truncating to the population si...
def random_replacement(random, population, parents, offspring, args): """Performs random replacement with optional weak elitism. This function performs random replacement, which means that the offspring replace random members of the population, keeping the population size constant. Weak elitism may...
def plus_replacement(random, population, parents, offspring, args): """Performs "plus" replacement. This function performs "plus" replacement, which means that the entire existing population is replaced by the best population-many elements from the combined set of parents and offspring. ...
def comma_replacement(random, population, parents, offspring, args): """Performs "comma" replacement. This function performs "comma" replacement, which means that the entire existing population is replaced by the best population-many elements from the offspring. This function makes the assumpti...
def crowding_replacement(random, population, parents, offspring, args): """Performs crowding replacement as a form of niching. This function performs crowding replacement, which means that the members of the population are replaced one-at-a-time with each of the offspring. A random sample of `crowd...
def simulated_annealing_replacement(random, population, parents, offspring, args): """Replaces population using the simulated annealing schedule. This function performs simulated annealing replacement based on a temperature and a cooling rate. These can be specified by the keyword arguments `temper...
def nsga_replacement(random, population, parents, offspring, args): """Replaces population using the non-dominated sorting technique from NSGA-II. .. Arguments: random -- the random number generator object population -- the population of individuals parents -- the list of parent indivi...
def paes_replacement(random, population, parents, offspring, args): """Replaces population using the Pareto Archived Evolution Strategy method. .. Arguments: random -- the random number generator object population -- the population of individuals parents -- the list of parent individua...
def evaluator(evaluate): """Return an inspyred evaluator function based on the given function. This function generator takes a function that evaluates only one candidate. The generator handles the iteration over each candidate to be evaluated. The given function ``evaluate`` must have the fol...
def parallel_evaluation_pp(candidates, args): """Evaluate the candidates in parallel using Parallel Python. This function allows parallel evaluation of candidate solutions. It uses the `Parallel Python <http://www.parallelpython.com>`_ (pp) library to accomplish the parallelization. This library must ...
def parallel_evaluation_mp(candidates, args): """Evaluate the candidates in parallel using ``multiprocessing``. This function allows parallel evaluation of candidate solutions. It uses the standard multiprocessing library to accomplish the parallelization. The function assigns the evaluation of each ...
def strategize(generator): """Add strategy parameters to candidates created by a generator. This function decorator is used to provide a means of adding strategy parameters to candidates created by a generator. The generator function is modifed to extend the candidate with ``len(candidate)`` stra...
def memoize(func=None, maxlen=None): """Cache a function's return value each time it is called. This function serves as a function decorator to provide a caching of evaluated fitness values. If called later with the same arguments, the cached value is returned instead of being re-evaluated. ...
def allow_ajax(request): """ Default function to determine whether to show the toolbar on a given page. """ if request.META.get('REMOTE_ADDR', None) not in settings.INTERNAL_IPS: return False if toolbar_version < LooseVersion('1.8') \ and request.get_full_path().startswith(DEBUG_...
def content(self): """ Content of the panel when it's displayed in full screen. """ toolbars = OrderedDict() for id, toolbar in DebugToolbar._store.items(): content = {} for panel in toolbar.panels: panel_id = None nav_title = '' ...
def execute_command(self): """ The web command runs the Scrapple web interface through a simple \ `Flask <http://flask.pocoo.org>`_ app. When the execute_command() method is called from the \ :ref:`runCLI() <implementation-cli>` function, it starts of two simultaneous \ ...
def execute_command(self): """ The generate command uses `Jinja2 <http://jinja.pocoo.org/>`_ templates \ to create Python scripts, according to the specification in the configuration \ file. The predefined templates use the extract_content() method of the \ :ref:`selector classes...
def extract_content(self, selector='', attr='', default='', connector='', *args, **kwargs): """ Method for performing the content extraction for the particular selector type. \ If the selector is "url", the URL of the current web page is returned. Otherwise, the selector expression is used to extract content. ...
def extract_links(self, selector='', *args, **kwargs): """ Method for performing the link extraction for the crawler. \ The selector passed as the argument is a selector to point to the anchor tags \ that the crawler should pass through. A list of links is obtained, and the links \ are iterated through. The ...
def extract_tabular(self, header='', prefix='', suffix='', table_type='', *args, **kwargs): """ Method for performing the tabular data extraction. \ :param result: A dictionary containing the extracted data so far :param table_type: Can be "rows" or "columns". This determines the type of table to be extracted....
def extract_rows(self, result={}, selector='', table_headers=[], attr='', connector='', default='', verbosity=0, *args, **kwargs): """ Row data extraction for extract_tabular """ result_list = [] try: values = self.get_tree_tag(selector) if len(table_headers) >= len(values): from itertools import i...
def extract_columns(self, result={}, selector='', table_headers=[], attr='', connector='', default='', verbosity=0, *args, **kwargs): """ Column data extraction for extract_tabular """ result_list = [] try: if type(selector) in [str, unicode]: selectors = [selector] elif type(selector) == list: ...
def runCLI(): """ The starting point for the execution of the Scrapple command line tool. runCLI uses the docstring as the usage description for the scrapple command. \ The class for the required command is selected by a dynamic dispatch, and the \ command is executed through the execute_command() ...
def check_arguments(args): """ Validates the arguments passed through the CLI commands. :param args: The arguments passed in the CLI, parsed by the docopt module :return: None """ projectname_re = re.compile(r'[^a-zA-Z0-9_]') if args['genconfig']: if args['--type'] not in ['scraper', 'crawler']: raise Inv...
def get_command_class(command): """ Called from runCLI() to select the command class for the selected command. :param command: The command to be implemented :return: The command class corresponding to the selected command """ from scrapple.commands import genconfig, generate, run, web comma...
def form_to_json(form): """ Takes the form from the POST request in the web interface, and generates the JSON config\ file :param form: The form from the POST request :return: None """ config = dict() if form['project_name'] == "": raise Exception('Project name cannot be empty.') if form['selector_type'] ...
def execute_command(self): """ The run command implements the web content extractor corresponding to the given \ configuration file. The execute_command() validates the input project name and opens the JSON \ configuration file. The run() method handles the execution of the ext...
def traverse_next(page, nextx, results, tabular_data_headers=[], verbosity=0): """ Recursive generator to traverse through the next attribute and \ crawl through the links to be followed. :param page: The current page being parsed :param next: The next attribute of the current scraping dict :pa...
def validate_config(config): """ Validates the extractor configuration file. Ensures that there are no duplicate field names, etc. :param config: The configuration file that contains the specification of the extractor :return: True if config is valid, else raises a exception that specifies the correcti...
def get_fields(config): """ Recursive generator that yields the field names in the config file :param config: The configuration file that contains the specification of the extractor :return: The field names in the config file, through a generator """ for data in config['scraping']['data']: ...
def extract_fieldnames(config): """ Function to return a list of unique field names from the config file :param config: The configuration file that contains the specification of the extractor :return: A list of field names from the config file """ fields = [] for x in get_fields(config): ...
def execute_command(self): """ The genconfig command depends on predefined `Jinja2 <http://jinja.pocoo.org/>`_ \ templates for the skeleton configuration files. Taking the --type argument from the \ CLI input, the corresponding template file is used. Settings for the configurat...
def _jordan_wigner_mode(n): """ Jordan_Wigner mode. Args: n (int): number of modes """ a = [] for i in range(n): xv = np.asarray([1] * i + [0] + [0] * (n - i - 1)) xw = np.asarray([0] * i + [1] + [0] * (n - i - 1)) yv = np.a...
def _one_body_mapping(a_i, a_j, threshold=0.000001): """ Subroutine for one body mapping. Args: a_i (Pauli): pauli at index i a_j (Pauli): pauli at index j threshold: (float): threshold to remove a pauli Returns: Operator: Operator for thos...
def get_grid_qubits(arc: SquareGrid, nodes: Iterator[int]) -> List[cirq.GridQubit]: """Gets a list of :py:class:GridQubit` s corresponding to the qubit nodes provided on the given Architecture. :param arc: The grid Architecture :param nodes: An iterator of node index values :return: The list ...
def cirq_to_tk(circuit: cirq.Circuit) -> Circuit: """Converts a Cirq :py:class:`Circuit` to a :math:`\\mathrm{t|ket}\\rangle` :py:class:`Circuit` object. :param circuit: The input Cirq :py:class:`Circuit` :raises NotImplementedError: If the input contains a Cirq :py:class:`Circuit` operation whi...
def tk_to_cirq(tkcirc: Circuit, indexed_qubits: List[QubitId]) -> cirq.Circuit: """Converts a :math:`\\mathrm{t|ket}\\rangle` :py:class:`Circuit` object to a Cirq :py:class:`Circuit`. :param tkcirc: The input :math:`\\mathrm{t|ket}\\rangle` :py:class:`Circuit` :param indexed_qubits: Map from :math:`\\m...
def dagcircuit_to_tk(dag:DAGCircuit, _BOX_UNKNOWN:bool=BOX_UNKNOWN, _DROP_CONDS:bool=DROP_CONDS) -> Circuit : """Converts a :py:class:`qiskit.DAGCircuit` into a :math:`\\mathrm{t|ket}\\rangle` :py:class:`Circuit`. Note that not all Qiskit operations are currently supported by pytket. Classical registers are sup...
def tk_to_dagcircuit(circ:Circuit,_qreg_name:str="q") -> DAGCircuit : """ Convert a :math:`\\mathrm{t|ket}\\rangle` :py:class:`Circuit` to a :py:class:`qiskit.DAGCircuit` . Requires that the circuit only conatins :py:class:`OpType` s from the qelib set. :param circ: A circuit to be converted ...
def coupling_to_arc(coupling_map:List[List[int]]) -> Architecture: """ Produces a :math:`\\mathrm{t|ket}\\rangle` :py:class:`Architecture` corresponding to a (directed) coupling map, stating the pairs of qubits between which two-qubit interactions (e.g. CXs) can be applied. :param coupling...
def run(self, dag:DAGCircuit) -> DAGCircuit: """ Run one pass of optimisation on the circuit and route for the given backend. :param dag: The circuit to optimise and route :return: The modified circuit """ circ = dagcircuit_to_tk(dag, _DROP_CONDS=self.DROP_CONDS,_BO...
def _sort_row_col(qubits: Iterator[GridQubit]) -> List[GridQubit]: """Sort grid qubits first by row then by column""" return sorted(qubits, key=lambda x: (x.row, x.col))
def xmon_to_arc(xmon: XmonDevice) -> Architecture: """Generates a :math:`\\mathrm{t|ket}\\rangle` :py:class:`Architecture` object for a Cirq :py:class:`XmonDevice` . :param xmon: The device to convert :return: The corresponding :math:`\\mathrm{t|ket}\\rangle` :py:class:`Architecture` """ node...
def pyquil_to_tk(prog: Program) -> Circuit: """ Convert a :py:class:`pyquil.Program` to a :math:`\\mathrm{t|ket}\\rangle` :py:class:`Circuit` . Note that not all pyQuil operations are currently supported by pytket. :param prog: A circuit to be converted :return: The converted circuit """ ...
def tk_to_pyquil(circ: Circuit) -> Program: """ Convert a :math:`\\mathrm{t|ket}\\rangle` :py:class:`Circuit` to a :py:class:`pyquil.Program` . :param circ: A circuit to be converted :return: The converted circuit """ p = Program() ro = p.declare('ro', 'BIT', circ.n_qubits()) gr...
def print_setting(self) -> str: """ Presents the QSE settings as a string. :return: The formatted settings of the QSE instance """ ret = "\n" ret += "==================== Setting of {} ============================\n".format(self.configuration['name']) ret += "{}"...
def _energy_evaluation(self, operator): """ Evaluate the energy of the current input circuit with respect to the given operator. :param operator: Hamiltonian of the system :return: Energy of the Hamiltonian """ if self._quantum_state is not None: input_circu...
def _run(self) -> dict: """ Runs the QSE algorithm to compute the eigenvalues of the Hamiltonian. :return: Dictionary of results """ if not self._quantum_instance.is_statevector: raise AquaError("Can only calculate state for QSE with statevector backends") re...
def whooshee_search(self, search_string, group=whoosh.qparser.OrGroup, whoosheer=None, match_substrings=True, limit=None, order_by_relevance=10): """Do a fulltext search on the query. Returns a query filtered with results of the fulltext search. :param search_string: The...
def search(cls, search_string, values_of='', group=whoosh.qparser.OrGroup, match_substrings=True, limit=None): """Searches the fields for given search_string. Returns the found records if 'values_of' is left empty, else the values of the given columns. :param search_string: The string t...
def prep_search_string(cls, search_string, match_substrings): """Prepares search string as a proper whoosh search string. :param search_string: The search string which should be prepared. :param match_substrings: ``True`` if you want to match substrings, ``False...
def init_app(self, app): """Initialize the extension. It will create the `index_path_root` directory upon initalization but it will **not** create the index. Please use :meth:`reindex` for this. :param app: The application instance for which the extension should be i...
def register_whoosheer(self, wh): """This will register the given whoosher on `whoosheers`, create the neccessary SQLAlchemy event listeners, replace the `query_class` with our own query class which will provide the search functionality and store the app on the whoosheer, so that we can ...
def register_model(self, *index_fields, **kw): """Registers a single model for fulltext search. This basically creates a simple Whoosheer for the model and calls :func:`register_whoosheer` on it. """ # construct subclass of AbstractWhoosheer for a model class ModelWhooshe...
def create_index(cls, app, wh): """Creates and opens an index for the given whoosheer and app. If the index already exists, it just opens it, otherwise it creates it first. :param app: The application instance. :param wh: The whoosheer instance for which a index should be create...
def camel_to_snake(self, s): """Constructs nice dir name from class name, e.g. FooBar => foo_bar. :param s: The string which should be converted to snake_case. """ return self._underscore_re2.sub(r'\1_\2', self._underscore_re1.sub(r'\1_\2', s)).lower()
def get_or_create_index(cls, app, wh): """Gets a previously cached index or creates a new one for the given app and whoosheer. :param app: The application instance. :param wh: The whoosheer instance for which the index should be retrieved or created. """ ...
def on_commit(self, changes): """Method that gets called when a model is changed. This serves to do the actual index writing. """ if _get_config(self)['enable_indexing'] is False: return None for wh in self.whoosheers: if not wh.auto_update: ...
def reindex(self): """Reindex all data This method retrieves all the data from the registered models and calls the ``update_<model>()`` function for every instance of such model. """ for wh in self.whoosheers: index = type(self).get_or_create_index(_get_app(s...
def create_domain(self, domain, ipaddr, params=None): ''' /v1/dns/create_domain POST - account Create a domain name in DNS Link: https://www.vultr.com/api/#dns_create_domain ''' params = update_params(params, { 'domain': domain, 'ip': ipaddr ...
def create_record(self, domain, name, _type, data, params=None): ''' /v1/dns/create_domain POST - account Add a DNS record Link: https://www.vultr.com/api/#dns_create_record ''' params = update_params(params, { 'domain': domain, 'name': name, ...
def delete_domain(self, domain, params=None): ''' /v1/dns/delete_domain POST - account Delete a domain name (and all associated records) Link: https://www.vultr.com/api/#dns_delete_domain ''' params = update_params(params, {'domain': domain}) return self.request(...
def delete_record(self, domain, recordid, params=None): ''' /v1/dns/delete_record POST - account Deletes an individual DNS record Link: https://www.vultr.com/api/#dns_delete_record ''' params = update_params(params, { 'domain': domain, 'RECORDID':...
def records(self, domain, params=None): ''' /v1/dns/records GET - account List all the records associated with a particular domain Link: https://www.vultr.com/api/#dns_records ''' params = update_params(params, {'domain': domain}) return self.request('/v1/dns/rec...
def update_record(self, domain, recordid, params=None): ''' /v1/dns/update_record POST - account Update a DNS record Link: https://www.vultr.com/api/#dns_update_record ''' params = update_params(params, { 'domain': domain, 'RECORDID': recordid ...