Search is not available for this dataset
text
stringlengths
75
104k
def _declare_consumer(self, consumer, nowait=False): """Declare consumer so messages can be received from it using :meth:`iterconsume`.""" if consumer.queue not in self._open_consumers: # Use the ConsumerSet's consumer by default, but if the # child consumer has a callbac...
def consume(self): """Declare consumers.""" head = self.consumers[:-1] tail = self.consumers[-1] [self._declare_consumer(consumer, nowait=True) for consumer in head] self._declare_consumer(tail, nowait=False)
def iterconsume(self, limit=None): """Cycle between all consumers in consume mode. See :meth:`Consumer.iterconsume`. """ self.consume() return self.backend.consume(limit=limit)
def cancel(self): """Cancel a running :meth:`iterconsume` session.""" for consumer_tag in self._open_consumers.values(): try: self.backend.cancel(consumer_tag) except KeyError: pass self._open_consumers.clear()
def convert_md_to_rst(source, destination=None, backup_dir=None): """Try to convert the source, an .md (markdown) file, to an .rst (reStructuredText) file at the destination. If the destination isn't provided, it defaults to be the same as the source path except for the filename extension. If the destin...
def build_readme(base_path=None): """Call the conversion routine on README.md to generate README.rst. Why do all this? Because pypi requires reStructuredText, but markdown is friendlier to work with and is nicer for GitHub.""" if base_path: path = os.path.join(base_path, 'README.md') else: ...
def sense(self): """Return a situation, encoded as a bit string, which represents the observable state of the environment. Usage: situation = scenario.sense() assert isinstance(situation, BitString) Arguments: None Return: The current situati...
def execute(self, action): """Execute the indicated action within the environment and return the resulting immediate reward dictated by the reward program. Usage: immediate_reward = scenario.execute(selected_action) Arguments: action: The action to be ex...
def reset(self): """Reset the scenario, starting it over for a new run. Usage: if not scenario.more(): scenario.reset() Arguments: None Return: None """ self.remaining_cycles = self.initial_training_cycles self.needle_index = random.r...
def sense(self): """Return a situation, encoded as a bit string, which represents the observable state of the environment. Usage: situation = scenario.sense() assert isinstance(situation, BitString) Arguments: None Return: The current situati...
def execute(self, action): """Execute the indicated action within the environment and return the resulting immediate reward dictated by the reward program. Usage: immediate_reward = scenario.execute(selected_action) Arguments: action: The action to be ex...
def get_possible_actions(self): """Return a sequence containing the possible actions that can be executed within the environment. Usage: possible_actions = scenario.get_possible_actions() Arguments: None Return: A sequence containing the possible actions...
def sense(self): """Return a situation, encoded as a bit string, which represents the observable state of the environment. Usage: situation = scenario.sense() assert isinstance(situation, BitString) Arguments: None Return: The current situati...
def execute(self, action): """Execute the indicated action within the environment and return the resulting immediate reward dictated by the reward program. Usage: immediate_reward = scenario.execute(selected_action) Arguments: action: The action to be ex...
def more(self): """Return a Boolean indicating whether additional actions may be executed, per the reward program. Usage: while scenario.more(): situation = scenario.sense() selected_action = choice(possible_actions) reward = scenario....
def execute(self, action): """Execute the indicated action within the environment and return the resulting immediate reward dictated by the reward program. Usage: immediate_reward = scenario.execute(selected_action) Arguments: action: The action to be ex...
def get_classifications(self): """Return the classifications made by the algorithm for this scenario. Usage: model.run(scenario, learn=False) classifications = scenario.get_classifications() Arguments: None Return: An indexable sequence conta...
def new_model(self, scenario): """Create and return a new classifier set initialized for handling the given scenario. Usage: scenario = MUXProblem() model = algorithm.new_model(scenario) model.run(scenario, learn=True) Arguments: scenario...
def run(self, scenario): """Run the algorithm, utilizing a classifier set to choose the most appropriate action for each situation produced by the scenario. Improve the situation/action mapping on each reward cycle to maximize reward. Return the classifier set that was created. ...
def _compute_prediction(self): """Compute the combined prediction and prediction weight for this action set. The combined prediction is the weighted average of the individual predictions of the classifiers. The combined prediction weight is the sum of the individual prediction weights of...
def best_prediction(self): """The highest value from among the predictions made by the action sets in this match set.""" if self._best_prediction is None and self._action_sets: self._best_prediction = max( action_set.prediction for action_set in self._...
def best_actions(self): """A tuple containing the actions whose action sets have the best prediction.""" if self._best_actions is None: best_prediction = self.best_prediction self._best_actions = tuple( action for action, action_set in self...
def select_action(self): """Select an action according to the action selection strategy of the associated algorithm. If an action has already been selected, raise a ValueError instead. Usage: if match_set.selected_action is None: match_set.select_action() ...
def _set_selected_action(self, action): """Setter method for the selected_action property.""" assert action in self._action_sets if self._selected_action is not None: raise ValueError("The action has already been selected.") self._selected_action = action
def _set_payoff(self, payoff): """Setter method for the payoff property.""" if self._selected_action is None: raise ValueError("The action has not been selected yet.") if self._closed: raise ValueError("The payoff for this match set has already" ...
def pay(self, predecessor): """If the predecessor is not None, gives the appropriate amount of payoff to the predecessor in payment for its contribution to this match set's expected future payoff. The predecessor argument should be either None or a MatchSet instance whose selected action...
def apply_payoff(self): """Apply the payoff that has been accumulated from immediate reward and/or payments from successor match sets. Attempting to call this method before an action has been selected or after it has already been called for the same match set will result in a Val...
def match(self, situation): """Accept a situation (input) and return a MatchSet containing the classifier rules whose conditions match the situation. If appropriate per the algorithm managing this classifier set, create new rules to ensure sufficient coverage of the possible actions. ...
def add(self, rule): """Add a new classifier rule to the classifier set. Return a list containing zero or more rules that were deleted from the classifier by the algorithm in order to make room for the new rule. The rule argument should be a ClassifierRule instance. The behavior of this ...
def discard(self, rule, count=1): """Remove one or more instances of a rule from the classifier set. Return a Boolean indicating whether the rule's numerosity dropped to zero. (If the rule's numerosity was already zero, do nothing and return False.) Usage: if rule in...
def get(self, rule, default=None): """Return the existing version of the given rule. If the rule is not present in the classifier set, return the default. If no default was given, use None. This is useful for eliminating duplicate copies of rules. Usage: unique_rule ...
def run(self, scenario, learn=True): """Run the algorithm, utilizing the classifier set to choose the most appropriate action for each situation produced by the scenario. If learn is True, improve the situation/action mapping to maximize reward. Otherwise, ignore any reward received. ...
def ls(system, user, local, include_missing): """List configuration files detected (and/or examined paths).""" # default action is to list *all* auto-detected files if not (system or user or local): system = user = local = True for path in get_configfile_paths(system=system, user=user, local=l...
def inspect(config_file, profile): """Inspect existing configuration/profile.""" try: section = load_profile_from_files( [config_file] if config_file else None, profile) click.echo("Configuration file: {}".format(config_file if config_file else "auto-detected")) click.echo(...
def create(config_file, profile): """Create and/or update cloud client configuration file.""" # determine the config file path if config_file: click.echo("Using configuration file: {}".format(config_file)) else: # path not given, try to detect; or use default, but allow user to override...
def _ping(config_file, profile, solver_def, request_timeout, polling_timeout, output): """Helper method for the ping command that uses `output()` for info output and raises `CLIError()` on handled errors. This function is invariant to output format and/or error signaling mechanism. """ config = di...
def ping(config_file, profile, solver_def, json_output, request_timeout, polling_timeout): """Ping the QPU by submitting a single-qubit problem.""" now = utcnow() info = dict(datetime=now.isoformat(), timestamp=datetime_to_timestamp(now), code=0) def output(fmt, **kwargs): info.update(kwargs) ...
def solvers(config_file, profile, solver_def, list_solvers): """Get solver details. Unless solver name/id specified, fetch and display details for all online solvers available on the configured endpoint. """ with Client.from_config( config_file=config_file, profile=profile, solver=solv...
def sample(config_file, profile, solver_def, biases, couplings, random_problem, num_reads, verbose): """Submit Ising-formulated problem and return samples.""" # TODO: de-dup wrt ping def echo(s, maxlen=100): click.echo(s if verbose else strtrunc(s, maxlen)) try: client = Cl...
def get_input_callback(samplerate, params, num_samples=256): """Return a function that produces samples of a sine. Parameters ---------- samplerate : float The sample rate. params : dict Parameters for FM generation. num_samples : int, optional Number of samples to be ge...
def get_playback_callback(resampler, samplerate, params): """Return a sound playback callback. Parameters ---------- resampler The resampler from which samples are read. samplerate : float The sample rate. params : dict Parameters for FM generation. """ def call...
def main(source_samplerate, target_samplerate, params, converter_type): """Setup the resampling and audio output callbacks and start playback.""" from time import sleep ratio = target_samplerate / source_samplerate with sr.CallbackResampler(get_input_callback(source_samplerate, params), ...
def max_num_reads(self, **params): """Returns the maximum number of reads for the given solver parameters. Args: **params: Parameters for the sampling method. Relevant to num_reads: - annealing_time - readout_thermalization - ...
def sample_ising(self, linear, quadratic, **params): """Sample from the specified Ising model. Args: linear (list/dict): Linear terms of the model (h). quadratic (dict of (int, int):float): Quadratic terms of the model (J). **params: Parameters for the sampling metho...
def sample_qubo(self, qubo, **params): """Sample from the specified QUBO. Args: qubo (dict of (int, int):float): Coefficients of a quadratic unconstrained binary optimization (QUBO) model. **params: Parameters for the sampling method, specified per solver. ...
def _sample(self, type_, linear, quadratic, params): """Internal method for both sample_ising and sample_qubo. Args: linear (list/dict): Linear terms of the model. quadratic (dict of (int, int):float): Quadratic terms of the model. **params: Parameters for the sampli...
def _format_params(self, type_, params): """Reformat some of the parameters for sapi.""" if 'initial_state' in params: # NB: at this moment the error raised when initial_state does not match lin/quad (in # active qubits) is not very informative, but there is also no clean way to ...
def check_problem(self, linear, quadratic): """Test if an Ising model matches the graph provided by the solver. Args: linear (list/dict): Linear terms of the model (h). quadratic (dict of (int, int):float): Quadratic terms of the model (J). Returns: boolean ...
def _retrieve_problem(self, id_): """Resume polling for a problem previously submitted. Args: id_: Identification of the query. Returns: :obj: `Future` """ future = Future(self, id_, self.return_matrix, None) self.client._poll(future) ret...
def _get_converter_type(identifier): """Return the converter type for `identifier`.""" if isinstance(identifier, str): return ConverterType[identifier] if isinstance(identifier, ConverterType): return identifier return ConverterType(identifier)
def resample(input_data, ratio, converter_type='sinc_best', verbose=False): """Resample the signal in `input_data` at once. Parameters ---------- input_data : ndarray Input data. A single channel is provided as a 1D array of `num_frames` length. Input data with several channels is repre...
def set_ratio(self, new_ratio): """Set a new conversion ratio immediately.""" from samplerate.lowlevel import src_set_ratio return src_set_ratio(self._state, new_ratio)
def process(self, input_data, ratio, end_of_input=False, verbose=False): """Resample the signal in `input_data`. Parameters ---------- input_data : ndarray Input data. A single channel is provided as a 1D array of `num_frames` length. Input data with several chan...
def _create(self): """Create new callback resampler.""" from samplerate.lowlevel import ffi, src_callback_new, src_delete from samplerate.exceptions import ResamplingError state, handle, error = src_callback_new( self._callback, self._converter_type.value, self._channels) ...
def set_starting_ratio(self, ratio): """ Set the starting conversion ratio for the next `read` call. """ from samplerate.lowlevel import src_set_ratio if self._state is None: self._create() src_set_ratio(self._state, ratio) self.ratio = ratio
def reset(self): """Reset state.""" from samplerate.lowlevel import src_reset if self._state is None: self._create() src_reset(self._state)
def read(self, num_frames): """Read a number of frames from the resampler. Parameters ---------- num_frames : int Number of frames to read. Returns ------- output_data : ndarray Resampled frames as a (`num_output_frames`, `num_channels`) ...
def get_variance(seq): """ Batch variance calculation. """ m = get_mean(seq) return sum((v-m)**2 for v in seq)/float(len(seq))
def mean_absolute_error(seq, correct): """ Batch mean absolute error calculation. """ assert len(seq) == len(correct) diffs = [abs(a-b) for a, b in zip(seq, correct)] return sum(diffs)/float(len(diffs))
def normalize(seq): """ Scales each number in the sequence so that the sum of all numbers equals 1. """ s = float(sum(seq)) return [v/s for v in seq]
def normcdf(x, mu, sigma): """ Describes the probability that a real-valued random variable X with a given probability distribution will be found at a value less than or equal to X in a normal distribution. http://en.wikipedia.org/wiki/Cumulative_distribution_function """ t = x-mu y...
def normpdf(x, mu, sigma): """ Describes the relative likelihood that a real-valued random variable X will take on a given value. http://en.wikipedia.org/wiki/Probability_density_function """ u = (x-mu)/abs(sigma) y = (1/(math.sqrt(2*pi)*abs(sigma)))*math.exp(-u*u/2) return y
def entropy(data, class_attr=None, method=DEFAULT_DISCRETE_METRIC): """ Calculates the entropy of the attribute attr in given data set data. Parameters: data<dict|list> := if dict, treated as value counts of the given attribute name if list, treated as a raw list from which the valu...
def entropy_variance(data, class_attr=None, method=DEFAULT_CONTINUOUS_METRIC): """ Calculates the variance fo a continuous class attribute, to be used as an entropy metric. """ assert method in CONTINUOUS_METRICS, "Unknown entropy variance metric: %s" % (method,) assert (class_attr is None a...
def get_gain(data, attr, class_attr, method=DEFAULT_DISCRETE_METRIC, only_sub=0, prefer_fewer_values=False, entropy_func=None): """ Calculates the information gain (reduction in entropy) that would result by splitting the data on the chosen attribute (attr). Parameters: prefer_fewe...
def majority_value(data, class_attr): """ Creates a list of all values in the target attribute for each record in the data list object, and returns the value that appears in this list the most frequently. """ if is_continuous(data[0][class_attr]): return CDist(seq=[record[class_attr] for...
def most_frequent(lst): """ Returns the item that appears most frequently in the given list. """ lst = lst[:] highest_freq = 0 most_freq = None for val in unique(lst): if lst.count(val) > highest_freq: most_freq = val highest_freq = lst.count(val) ...
def unique(lst): """ Returns a list made up of the unique values found in lst. i.e., it removes the redundant values in lst. """ lst = lst[:] unique_lst = [] # Cycle through the list and add each value to the unique list only once. for item in lst: if unique_lst.count(item) <= ...
def choose_attribute(data, attributes, class_attr, fitness, method): """ Cycles through all the attributes and returns the attribute with the highest information gain (or lowest entropy). """ best = (-1e999999, None) for attr in attributes: if attr == class_attr: continue ...
def create_decision_tree(data, attributes, class_attr, fitness_func, wrapper, **kwargs): """ Returns a new decision tree based on the examples given. """ split_attr = kwargs.get('split_attr', None) split_val = kwargs.get('split_val', None) assert class_attr not in attributes node =...
def add(self, k, count=1): """ Increments the count for the given element. """ self.counts[k] += count self.total += count
def best(self): """ Returns the element with the highest probability. """ b = (-1e999999, None) for k, c in iteritems(self.counts): b = max(b, (c, k)) return b[1]
def probs(self): """ Returns a list of probabilities for all elements in the form [(value1,prob1),(value2,prob2),...]. """ return [ (k, self.counts[k]/float(self.total)) for k in iterkeys(self.counts) ]
def update(self, dist): """ Adds the given distribution's counts to the current distribution. """ assert isinstance(dist, DDist) for k, c in iteritems(dist.counts): self.counts[k] += c self.total += dist.total
def probability_lt(self, x): """ Returns the probability of a random variable being less than the given value. """ if self.mean is None: return return normdist(x=x, mu=self.mean, sigma=self.standard_deviation)
def probability_in(self, a, b): """ Returns the probability of a random variable falling between the given values. """ if self.mean is None: return p1 = normdist(x=a, mu=self.mean, sigma=self.standard_deviation) p2 = normdist(x=b, mu=self.mean, sigma=s...
def probability_gt(self, x): """ Returns the probability of a random variable being greater than the given value. """ if self.mean is None: return p = normdist(x=x, mu=self.mean, sigma=self.standard_deviation) return 1-p
def copy_no_data(self): """ Returns a copy of the object without any data. """ return type(self)( [], order=list(self.header_modes), types=self.header_types.copy(), modes=self.header_modes.copy())
def is_valid(self, name, value): """ Returns true if the given value matches the type for the given name according to the schema. Returns false otherwise. """ if name not in self.header_types: return False t = self.header_types[name] if t == AT...
def _read_header(self): """ When a CSV file is given, extracts header information the file. Otherwise, this header data must be explicitly given when the object is instantiated. """ if not self.filename or self.header_types: return rows = csv.reader(op...
def validate_row(self, row): """ Ensure each element in the row matches the schema. """ clean_row = {} if isinstance(row, (tuple, list)): assert self.header_order, "No attribute order specified." assert len(row) == len(self.header_order), \ ...
def split(self, ratio=0.5, leave_one_out=False): """ Returns two Data instances, containing the data randomly split between the two according to the given ratio. The first instance will contain the ratio of data specified. The second instance will contain the remaining r...
def _get_attribute_value_for_node(self, record): """ Gets the closest value for the current node's attribute matching the given record. """ # Abort if this node has not get split on an attribute. if self.attr_name is None: return # O...
def get_values(self, attr_name): """ Retrieves the unique set of values seen for the given attribute at this node. """ ret = list(self._attr_value_cdist[attr_name].keys()) \ + list(self._attr_value_counts[attr_name].keys()) \ + list(self._branches.keys()) ...
def get_best_splitting_attr(self): """ Returns the name of the attribute with the highest gain. """ best = (-1e999999, None) for attr in self.attributes: best = max(best, (self.get_gain(attr), attr)) best_gain, best_attr = best return best_attr
def get_entropy(self, attr_name=None, attr_value=None): """ Calculates the entropy of a specific attribute/value combination. """ is_con = self.tree.data.is_continuous_class if is_con: if attr_name is None: # Calculate variance of class attribute. ...
def get_gain(self, attr_name): """ Calculates the information gain from splitting on the given attribute. """ subset_entropy = 0.0 for value in iterkeys(self._attr_value_counts[attr_name]): value_prob = self.get_value_prob(attr_name, value) e = self.get_en...
def get_value_ddist(self, attr_name, attr_value): """ Returns the class value probability distribution of the given attribute value. """ assert not self.tree.data.is_continuous_class, \ "Discrete distributions are only maintained for " + \ "discrete class ...
def get_value_prob(self, attr_name, value): """ Returns the value probability of the given attribute at this node. """ if attr_name not in self._attr_value_count_totals: return n = self._attr_value_counts[attr_name][value] d = self._attr_value_count_totals[att...
def predict(self, record, depth=0): """ Returns the estimated value of the class attribute for the given record. """ # Check if we're ready to predict. if not self.ready_to_predict: raise NodeNotReadyToPredict # Lookup attribute value...
def ready_to_split(self): """ Returns true if this node is ready to branch off additional nodes. Returns false otherwise. """ # Never split if we're a leaf that predicts adequately. threshold = self._tree.leaf_threshold if self._tree.data.is_continuous_class: ...
def set_leaf_dist(self, attr_value, dist): """ Sets the probability distribution at a leaf node. """ assert self.attr_name assert self.tree.data.is_valid(self.attr_name, attr_value), \ "Value %s is invalid for attribute %s." \ % (attr_value, self.attr_...
def train(self, record): """ Incrementally update the statistics at this node. """ self.n += 1 class_attr = self.tree.data.class_attribute_name class_value = record[class_attr] # Update class statistics. is_con = self.tree.data.is_continuous_class...
def build(cls, data, *args, **kwargs): """ Constructs a classification or regression tree in a single batch by analyzing the given data. """ assert isinstance(data, Data) if data.is_continuous_class: fitness_func = gain_variance else: fitne...
def out_of_bag_mae(self): """ Returns the mean absolute error for predictions on the out-of-bag samples. """ if not self._out_of_bag_mae_clean: try: self._out_of_bag_mae = self.test(self.out_of_bag_samples) self._out_of_bag_mae_clean = ...
def out_of_bag_samples(self): """ Returns the out-of-bag samples list, inside a wrapper to keep track of modifications. """ #TODO:replace with more a generic pass-through wrapper? class O(object): def __init__(self, tree): self.tree = tree ...
def set_missing_value_policy(self, policy, target_attr_name=None): """ Sets the behavior for one or all attributes to use when traversing the tree using a query vector and it encounters a branch that does not exist. """ assert policy in MISSING_VALUE_POLICIES, \ ...
def train(self, record): """ Incrementally updates the tree with the given sample record. """ assert self.data.class_attribute_name in record, \ "The class attribute must be present in the record." record = record.copy() self.sample_count += 1 self.tre...
def _fell_trees(self): """ Removes trees from the forest according to the specified fell method. """ if callable(self.fell_method): for tree in self.fell_method(list(self.trees)): self.trees.remove(tree)
def _get_best_prediction(self, record, train=True): """ Gets the prediction from the tree with the lowest mean absolute error. """ if not self.trees: return best = (+1e999999, None) for tree in self.trees: best = min(best, (tree.mae.mean, tree)) ...