repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
hosford42/xcs
xcs/framework.py
MatchSet.select_action
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() Arguments: None Return: The action that was selected by the action selection strategy. """ if self._selected_action is not None: raise ValueError("The action has already been selected.") strategy = self._algorithm.action_selection_strategy self._selected_action = strategy(self) return self._selected_action
python
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() Arguments: None Return: The action that was selected by the action selection strategy. """ if self._selected_action is not None: raise ValueError("The action has already been selected.") strategy = self._algorithm.action_selection_strategy self._selected_action = strategy(self) return self._selected_action
[ "def", "select_action", "(", "self", ")", ":", "if", "self", ".", "_selected_action", "is", "not", "None", ":", "raise", "ValueError", "(", "\"The action has already been selected.\"", ")", "strategy", "=", "self", ".", "_algorithm", ".", "action_selection_strategy", "self", ".", "_selected_action", "=", "strategy", "(", "self", ")", "return", "self", ".", "_selected_action" ]
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() Arguments: None Return: The action that was selected by the action selection strategy.
[ "Select", "an", "action", "according", "to", "the", "action", "selection", "strategy", "of", "the", "associated", "algorithm", ".", "If", "an", "action", "has", "already", "been", "selected", "raise", "a", "ValueError", "instead", "." ]
183bdd0dd339e19ded3be202f86e1b38bdb9f1e5
https://github.com/hosford42/xcs/blob/183bdd0dd339e19ded3be202f86e1b38bdb9f1e5/xcs/framework.py#L637-L654
train
hosford42/xcs
xcs/framework.py
MatchSet._set_selected_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
python
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_selected_action", "(", "self", ",", "action", ")", ":", "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" ]
Setter method for the selected_action property.
[ "Setter", "method", "for", "the", "selected_action", "property", "." ]
183bdd0dd339e19ded3be202f86e1b38bdb9f1e5
https://github.com/hosford42/xcs/blob/183bdd0dd339e19ded3be202f86e1b38bdb9f1e5/xcs/framework.py#L660-L666
train
hosford42/xcs
xcs/framework.py
MatchSet._set_payoff
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" "been applied.") self._payoff = float(payoff)
python
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" "been applied.") self._payoff = float(payoff)
[ "def", "_set_payoff", "(", "self", ",", "payoff", ")", ":", "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\"", "\"been applied.\"", ")", "self", ".", "_payoff", "=", "float", "(", "payoff", ")" ]
Setter method for the payoff property.
[ "Setter", "method", "for", "the", "payoff", "property", "." ]
183bdd0dd339e19ded3be202f86e1b38bdb9f1e5
https://github.com/hosford42/xcs/blob/183bdd0dd339e19ded3be202f86e1b38bdb9f1e5/xcs/framework.py#L692-L699
train
hosford42/xcs
xcs/framework.py
MatchSet.pay
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 led directly to this match set's situation. Usage: match_set = model.match(situation) match_set.pay(previous_match_set) Arguments: predecessor: The MatchSet instance which was produced by the same classifier set in response to the immediately preceding situation, or None if this is the first situation in the scenario. Return: None """ assert predecessor is None or isinstance(predecessor, MatchSet) if predecessor is not None: expectation = self._algorithm.get_future_expectation(self) predecessor.payoff += expectation
python
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 led directly to this match set's situation. Usage: match_set = model.match(situation) match_set.pay(previous_match_set) Arguments: predecessor: The MatchSet instance which was produced by the same classifier set in response to the immediately preceding situation, or None if this is the first situation in the scenario. Return: None """ assert predecessor is None or isinstance(predecessor, MatchSet) if predecessor is not None: expectation = self._algorithm.get_future_expectation(self) predecessor.payoff += expectation
[ "def", "pay", "(", "self", ",", "predecessor", ")", ":", "assert", "predecessor", "is", "None", "or", "isinstance", "(", "predecessor", ",", "MatchSet", ")", "if", "predecessor", "is", "not", "None", ":", "expectation", "=", "self", ".", "_algorithm", ".", "get_future_expectation", "(", "self", ")", "predecessor", ".", "payoff", "+=", "expectation" ]
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 led directly to this match set's situation. Usage: match_set = model.match(situation) match_set.pay(previous_match_set) Arguments: predecessor: The MatchSet instance which was produced by the same classifier set in response to the immediately preceding situation, or None if this is the first situation in the scenario. Return: None
[ "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", "led", "directly", "to", "this", "match", "set", "s", "situation", "." ]
183bdd0dd339e19ded3be202f86e1b38bdb9f1e5
https://github.com/hosford42/xcs/blob/183bdd0dd339e19ded3be202f86e1b38bdb9f1e5/xcs/framework.py#L713-L735
train
hosford42/xcs
xcs/framework.py
MatchSet.apply_payoff
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 ValueError. Usage: match_set.select_action() match_set.payoff = reward match_set.apply_payoff() Arguments: None Return: None """ 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" "been applied.") self._algorithm.distribute_payoff(self) self._payoff = 0 self._algorithm.update(self) self._closed = True
python
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 ValueError. Usage: match_set.select_action() match_set.payoff = reward match_set.apply_payoff() Arguments: None Return: None """ 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" "been applied.") self._algorithm.distribute_payoff(self) self._payoff = 0 self._algorithm.update(self) self._closed = True
[ "def", "apply_payoff", "(", "self", ")", ":", "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\"", "\"been applied.\"", ")", "self", ".", "_algorithm", ".", "distribute_payoff", "(", "self", ")", "self", ".", "_payoff", "=", "0", "self", ".", "_algorithm", ".", "update", "(", "self", ")", "self", ".", "_closed", "=", "True" ]
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 ValueError. Usage: match_set.select_action() match_set.payoff = reward match_set.apply_payoff() Arguments: None Return: None
[ "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", "ValueError", "." ]
183bdd0dd339e19ded3be202f86e1b38bdb9f1e5
https://github.com/hosford42/xcs/blob/183bdd0dd339e19ded3be202f86e1b38bdb9f1e5/xcs/framework.py#L737-L760
train
hosford42/xcs
xcs/framework.py
ClassifierSet.match
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. Usage: match_set = model.match(situation) Arguments: situation: The situation for which a match set is desired. Return: A MatchSet instance for the given situation, drawn from the classifier rules in this classifier set. """ # Find the conditions that match against the current situation, and # group them according to which action(s) they recommend. by_action = {} for condition, actions in self._population.items(): if not condition(situation): continue for action, rule in actions.items(): if action in by_action: by_action[action][condition] = rule else: by_action[action] = {condition: rule} # Construct the match set. match_set = MatchSet(self, situation, by_action) # If an insufficient number of actions are recommended, create some # new rules (condition/action pairs) until there are enough actions # being recommended. if self._algorithm.covering_is_required(match_set): # Ask the algorithm to provide a new classifier rule to add to # the population. rule = self._algorithm.cover(match_set) # Ensure that the condition provided by the algorithm does # indeed match the situation. If not, there is a bug in the # algorithm. assert rule.condition(situation) # Add the new classifier, getting back a list of the rule(s) # which had to be removed to make room for it. replaced = self.add(rule) # Remove the rules that were removed the population from the # action set, as well. Note that they may not appear in the # action set, in which case nothing is done. for replaced_rule in replaced: action = replaced_rule.action condition = replaced_rule.condition if action in by_action and condition in by_action[action]: del by_action[action][condition] if not by_action[action]: del by_action[action] # Add the new classifier to the action set. This is done after # the replaced rules are removed, just in case the algorithm # provided us with a rule that was already present and was # displaced. if rule.action not in by_action: by_action[rule.action] = {} by_action[rule.action][rule.condition] = rule # Reconstruct the match set with the modifications we just # made. match_set = MatchSet(self, situation, by_action) # Return the newly created match set. return match_set
python
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. Usage: match_set = model.match(situation) Arguments: situation: The situation for which a match set is desired. Return: A MatchSet instance for the given situation, drawn from the classifier rules in this classifier set. """ # Find the conditions that match against the current situation, and # group them according to which action(s) they recommend. by_action = {} for condition, actions in self._population.items(): if not condition(situation): continue for action, rule in actions.items(): if action in by_action: by_action[action][condition] = rule else: by_action[action] = {condition: rule} # Construct the match set. match_set = MatchSet(self, situation, by_action) # If an insufficient number of actions are recommended, create some # new rules (condition/action pairs) until there are enough actions # being recommended. if self._algorithm.covering_is_required(match_set): # Ask the algorithm to provide a new classifier rule to add to # the population. rule = self._algorithm.cover(match_set) # Ensure that the condition provided by the algorithm does # indeed match the situation. If not, there is a bug in the # algorithm. assert rule.condition(situation) # Add the new classifier, getting back a list of the rule(s) # which had to be removed to make room for it. replaced = self.add(rule) # Remove the rules that were removed the population from the # action set, as well. Note that they may not appear in the # action set, in which case nothing is done. for replaced_rule in replaced: action = replaced_rule.action condition = replaced_rule.condition if action in by_action and condition in by_action[action]: del by_action[action][condition] if not by_action[action]: del by_action[action] # Add the new classifier to the action set. This is done after # the replaced rules are removed, just in case the algorithm # provided us with a rule that was already present and was # displaced. if rule.action not in by_action: by_action[rule.action] = {} by_action[rule.action][rule.condition] = rule # Reconstruct the match set with the modifications we just # made. match_set = MatchSet(self, situation, by_action) # Return the newly created match set. return match_set
[ "def", "match", "(", "self", ",", "situation", ")", ":", "# Find the conditions that match against the current situation, and", "# group them according to which action(s) they recommend.", "by_action", "=", "{", "}", "for", "condition", ",", "actions", "in", "self", ".", "_population", ".", "items", "(", ")", ":", "if", "not", "condition", "(", "situation", ")", ":", "continue", "for", "action", ",", "rule", "in", "actions", ".", "items", "(", ")", ":", "if", "action", "in", "by_action", ":", "by_action", "[", "action", "]", "[", "condition", "]", "=", "rule", "else", ":", "by_action", "[", "action", "]", "=", "{", "condition", ":", "rule", "}", "# Construct the match set.", "match_set", "=", "MatchSet", "(", "self", ",", "situation", ",", "by_action", ")", "# If an insufficient number of actions are recommended, create some", "# new rules (condition/action pairs) until there are enough actions", "# being recommended.", "if", "self", ".", "_algorithm", ".", "covering_is_required", "(", "match_set", ")", ":", "# Ask the algorithm to provide a new classifier rule to add to", "# the population.", "rule", "=", "self", ".", "_algorithm", ".", "cover", "(", "match_set", ")", "# Ensure that the condition provided by the algorithm does", "# indeed match the situation. If not, there is a bug in the", "# algorithm.", "assert", "rule", ".", "condition", "(", "situation", ")", "# Add the new classifier, getting back a list of the rule(s)", "# which had to be removed to make room for it.", "replaced", "=", "self", ".", "add", "(", "rule", ")", "# Remove the rules that were removed the population from the", "# action set, as well. Note that they may not appear in the", "# action set, in which case nothing is done.", "for", "replaced_rule", "in", "replaced", ":", "action", "=", "replaced_rule", ".", "action", "condition", "=", "replaced_rule", ".", "condition", "if", "action", "in", "by_action", "and", "condition", "in", "by_action", "[", "action", "]", ":", "del", "by_action", "[", "action", "]", "[", "condition", "]", "if", "not", "by_action", "[", "action", "]", ":", "del", "by_action", "[", "action", "]", "# Add the new classifier to the action set. This is done after", "# the replaced rules are removed, just in case the algorithm", "# provided us with a rule that was already present and was", "# displaced.", "if", "rule", ".", "action", "not", "in", "by_action", ":", "by_action", "[", "rule", ".", "action", "]", "=", "{", "}", "by_action", "[", "rule", ".", "action", "]", "[", "rule", ".", "condition", "]", "=", "rule", "# Reconstruct the match set with the modifications we just", "# made.", "match_set", "=", "MatchSet", "(", "self", ",", "situation", ",", "by_action", ")", "# Return the newly created match set.", "return", "match_set" ]
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. Usage: match_set = model.match(situation) Arguments: situation: The situation for which a match set is desired. Return: A MatchSet instance for the given situation, drawn from the classifier rules in this classifier set.
[ "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", "." ]
183bdd0dd339e19ded3be202f86e1b38bdb9f1e5
https://github.com/hosford42/xcs/blob/183bdd0dd339e19ded3be202f86e1b38bdb9f1e5/xcs/framework.py#L865-L938
train
hosford42/xcs
xcs/framework.py
ClassifierSet.add
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 method depends on whether the rule already exists in the classifier set. When a rule is already present, the rule's numerosity is added to that of the version of the rule already present in the population. Otherwise, the new rule is captured. Note that this means that for rules already present in the classifier set, the metadata of the existing rule is not overwritten by that of the one passed in as an argument. Usage: displaced_rules = model.add(rule) Arguments: rule: A ClassifierRule instance which is to be added to this classifier set. Return: A possibly empty list of ClassifierRule instances which were removed altogether from the classifier set (as opposed to simply having their numerosities decremented) in order to make room for the newly added rule. """ assert isinstance(rule, ClassifierRule) condition = rule.condition action = rule.action # If the rule already exists in the population, then we virtually # add the rule by incrementing the existing rule's numerosity. This # prevents redundancy in the rule set. Otherwise we capture the # new rule. if condition not in self._population: self._population[condition] = {} if action in self._population[condition]: existing_rule = self._population[condition][action] existing_rule.numerosity += rule.numerosity else: self._population[condition][action] = rule # Any time we add a rule, we need to call this to keep the # population size under control. return self._algorithm.prune(self)
python
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 method depends on whether the rule already exists in the classifier set. When a rule is already present, the rule's numerosity is added to that of the version of the rule already present in the population. Otherwise, the new rule is captured. Note that this means that for rules already present in the classifier set, the metadata of the existing rule is not overwritten by that of the one passed in as an argument. Usage: displaced_rules = model.add(rule) Arguments: rule: A ClassifierRule instance which is to be added to this classifier set. Return: A possibly empty list of ClassifierRule instances which were removed altogether from the classifier set (as opposed to simply having their numerosities decremented) in order to make room for the newly added rule. """ assert isinstance(rule, ClassifierRule) condition = rule.condition action = rule.action # If the rule already exists in the population, then we virtually # add the rule by incrementing the existing rule's numerosity. This # prevents redundancy in the rule set. Otherwise we capture the # new rule. if condition not in self._population: self._population[condition] = {} if action in self._population[condition]: existing_rule = self._population[condition][action] existing_rule.numerosity += rule.numerosity else: self._population[condition][action] = rule # Any time we add a rule, we need to call this to keep the # population size under control. return self._algorithm.prune(self)
[ "def", "add", "(", "self", ",", "rule", ")", ":", "assert", "isinstance", "(", "rule", ",", "ClassifierRule", ")", "condition", "=", "rule", ".", "condition", "action", "=", "rule", ".", "action", "# If the rule already exists in the population, then we virtually", "# add the rule by incrementing the existing rule's numerosity. This", "# prevents redundancy in the rule set. Otherwise we capture the", "# new rule.", "if", "condition", "not", "in", "self", ".", "_population", ":", "self", ".", "_population", "[", "condition", "]", "=", "{", "}", "if", "action", "in", "self", ".", "_population", "[", "condition", "]", ":", "existing_rule", "=", "self", ".", "_population", "[", "condition", "]", "[", "action", "]", "existing_rule", ".", "numerosity", "+=", "rule", ".", "numerosity", "else", ":", "self", ".", "_population", "[", "condition", "]", "[", "action", "]", "=", "rule", "# Any time we add a rule, we need to call this to keep the", "# population size under control.", "return", "self", ".", "_algorithm", ".", "prune", "(", "self", ")" ]
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 method depends on whether the rule already exists in the classifier set. When a rule is already present, the rule's numerosity is added to that of the version of the rule already present in the population. Otherwise, the new rule is captured. Note that this means that for rules already present in the classifier set, the metadata of the existing rule is not overwritten by that of the one passed in as an argument. Usage: displaced_rules = model.add(rule) Arguments: rule: A ClassifierRule instance which is to be added to this classifier set. Return: A possibly empty list of ClassifierRule instances which were removed altogether from the classifier set (as opposed to simply having their numerosities decremented) in order to make room for the newly added 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", "method", "depends", "on", "whether", "the", "rule", "already", "exists", "in", "the", "classifier", "set", ".", "When", "a", "rule", "is", "already", "present", "the", "rule", "s", "numerosity", "is", "added", "to", "that", "of", "the", "version", "of", "the", "rule", "already", "present", "in", "the", "population", ".", "Otherwise", "the", "new", "rule", "is", "captured", ".", "Note", "that", "this", "means", "that", "for", "rules", "already", "present", "in", "the", "classifier", "set", "the", "metadata", "of", "the", "existing", "rule", "is", "not", "overwritten", "by", "that", "of", "the", "one", "passed", "in", "as", "an", "argument", "." ]
183bdd0dd339e19ded3be202f86e1b38bdb9f1e5
https://github.com/hosford42/xcs/blob/183bdd0dd339e19ded3be202f86e1b38bdb9f1e5/xcs/framework.py#L940-L986
train
hosford42/xcs
xcs/framework.py
ClassifierSet.discard
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 model and model.discard(rule, count=3): print("Rule numerosity dropped to zero.") Arguments: rule: A ClassifierRule instance whose numerosity is to be decremented. count: An int, the size of the decrement to the rule's numerosity; default is 1. Return: A bool indicating whether the rule was removed altogether from the classifier set, as opposed to simply having its numerosity decremented. """ assert isinstance(rule, ClassifierRule) assert isinstance(count, int) and count >= 0 rule = self.get(rule) if rule is None: return False # Only actually remove the rule if its numerosity drops below 1. rule.numerosity -= count if rule.numerosity <= 0: # Ensure that if there is still a reference to this rule # elsewhere, its numerosity is still well-defined. rule.numerosity = 0 del self._population[rule.condition][rule.action] if not self._population[rule.condition]: del self._population[rule.condition] return True return False
python
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 model and model.discard(rule, count=3): print("Rule numerosity dropped to zero.") Arguments: rule: A ClassifierRule instance whose numerosity is to be decremented. count: An int, the size of the decrement to the rule's numerosity; default is 1. Return: A bool indicating whether the rule was removed altogether from the classifier set, as opposed to simply having its numerosity decremented. """ assert isinstance(rule, ClassifierRule) assert isinstance(count, int) and count >= 0 rule = self.get(rule) if rule is None: return False # Only actually remove the rule if its numerosity drops below 1. rule.numerosity -= count if rule.numerosity <= 0: # Ensure that if there is still a reference to this rule # elsewhere, its numerosity is still well-defined. rule.numerosity = 0 del self._population[rule.condition][rule.action] if not self._population[rule.condition]: del self._population[rule.condition] return True return False
[ "def", "discard", "(", "self", ",", "rule", ",", "count", "=", "1", ")", ":", "assert", "isinstance", "(", "rule", ",", "ClassifierRule", ")", "assert", "isinstance", "(", "count", ",", "int", ")", "and", "count", ">=", "0", "rule", "=", "self", ".", "get", "(", "rule", ")", "if", "rule", "is", "None", ":", "return", "False", "# Only actually remove the rule if its numerosity drops below 1.", "rule", ".", "numerosity", "-=", "count", "if", "rule", ".", "numerosity", "<=", "0", ":", "# Ensure that if there is still a reference to this rule", "# elsewhere, its numerosity is still well-defined.", "rule", ".", "numerosity", "=", "0", "del", "self", ".", "_population", "[", "rule", ".", "condition", "]", "[", "rule", ".", "action", "]", "if", "not", "self", ".", "_population", "[", "rule", ".", "condition", "]", ":", "del", "self", ".", "_population", "[", "rule", ".", "condition", "]", "return", "True", "return", "False" ]
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 model and model.discard(rule, count=3): print("Rule numerosity dropped to zero.") Arguments: rule: A ClassifierRule instance whose numerosity is to be decremented. count: An int, the size of the decrement to the rule's numerosity; default is 1. Return: A bool indicating whether the rule was removed altogether from the classifier set, as opposed to simply having its numerosity decremented.
[ "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", ".", ")" ]
183bdd0dd339e19ded3be202f86e1b38bdb9f1e5
https://github.com/hosford42/xcs/blob/183bdd0dd339e19ded3be202f86e1b38bdb9f1e5/xcs/framework.py#L988-L1027
train
hosford42/xcs
xcs/framework.py
ClassifierSet.get
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 = model.get(possible_duplicate, possible_duplicate) Arguments: rule: The ClassifierRule instance which may be a duplicate of another already contained in the classifier set. default: The value returned if the rule is not a duplicate of another already contained in the classifier set. Return: If the rule is a duplicate of another already contained in the classifier set, the existing one is returned. Otherwise, the value of default is returned. """ assert isinstance(rule, ClassifierRule) if (rule.condition not in self._population or rule.action not in self._population[rule.condition]): return default return self._population[rule.condition][rule.action]
python
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 = model.get(possible_duplicate, possible_duplicate) Arguments: rule: The ClassifierRule instance which may be a duplicate of another already contained in the classifier set. default: The value returned if the rule is not a duplicate of another already contained in the classifier set. Return: If the rule is a duplicate of another already contained in the classifier set, the existing one is returned. Otherwise, the value of default is returned. """ assert isinstance(rule, ClassifierRule) if (rule.condition not in self._population or rule.action not in self._population[rule.condition]): return default return self._population[rule.condition][rule.action]
[ "def", "get", "(", "self", ",", "rule", ",", "default", "=", "None", ")", ":", "assert", "isinstance", "(", "rule", ",", "ClassifierRule", ")", "if", "(", "rule", ".", "condition", "not", "in", "self", ".", "_population", "or", "rule", ".", "action", "not", "in", "self", ".", "_population", "[", "rule", ".", "condition", "]", ")", ":", "return", "default", "return", "self", ".", "_population", "[", "rule", ".", "condition", "]", "[", "rule", ".", "action", "]" ]
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 = model.get(possible_duplicate, possible_duplicate) Arguments: rule: The ClassifierRule instance which may be a duplicate of another already contained in the classifier set. default: The value returned if the rule is not a duplicate of another already contained in the classifier set. Return: If the rule is a duplicate of another already contained in the classifier set, the existing one is returned. Otherwise, the value of default is returned.
[ "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", "." ]
183bdd0dd339e19ded3be202f86e1b38bdb9f1e5
https://github.com/hosford42/xcs/blob/183bdd0dd339e19ded3be202f86e1b38bdb9f1e5/xcs/framework.py#L1029-L1053
train
hosford42/xcs
xcs/framework.py
ClassifierSet.run
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. Usage: model.run(scenario, learn=True) Arguments: scenario: A Scenario instance which this classifier set is to interact with. learn: A bool indicating whether the classifier set should attempt to optimize its performance based on reward received for each action, as opposed to simply using what it has already learned from previous runs and ignoring reward received; default is True. Return: None """ assert isinstance(scenario, scenarios.Scenario) previous_match_set = None # Repeat until the scenario has run its course. while scenario.more(): # Gather information about the current state of the # environment. situation = scenario.sense() # Determine which rules match the current situation. match_set = self.match(situation) # Select the best action for the current situation (or a random # one, if we are on an exploration step). match_set.select_action() # Perform the selected action # and find out what the received reward was. reward = scenario.execute(match_set.selected_action) # If the scenario is dynamic, don't immediately apply the # reward; instead, wait until the next iteration and factor in # not only the reward that was received on the previous step, # but the (discounted) reward that is expected going forward # given the resulting situation observed after the action was # taken. This is a classic feature of temporal difference (TD) # algorithms, which acts to stitch together a general picture # of the future expected reward without actually waiting the # full duration to find out what it will be. if learn: # Ensure we are not trying to learn in a non-learning # scenario. assert reward is not None if scenario.is_dynamic: if previous_match_set is not None: match_set.pay(previous_match_set) previous_match_set.apply_payoff() match_set.payoff = reward # Remember the current reward and match set for the # next iteration. previous_match_set = match_set else: match_set.payoff = reward match_set.apply_payoff() # This serves to tie off the final stitch. The last action taken # gets only the immediate reward; there is no future reward # expected. if learn and previous_match_set is not None: previous_match_set.apply_payoff()
python
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. Usage: model.run(scenario, learn=True) Arguments: scenario: A Scenario instance which this classifier set is to interact with. learn: A bool indicating whether the classifier set should attempt to optimize its performance based on reward received for each action, as opposed to simply using what it has already learned from previous runs and ignoring reward received; default is True. Return: None """ assert isinstance(scenario, scenarios.Scenario) previous_match_set = None # Repeat until the scenario has run its course. while scenario.more(): # Gather information about the current state of the # environment. situation = scenario.sense() # Determine which rules match the current situation. match_set = self.match(situation) # Select the best action for the current situation (or a random # one, if we are on an exploration step). match_set.select_action() # Perform the selected action # and find out what the received reward was. reward = scenario.execute(match_set.selected_action) # If the scenario is dynamic, don't immediately apply the # reward; instead, wait until the next iteration and factor in # not only the reward that was received on the previous step, # but the (discounted) reward that is expected going forward # given the resulting situation observed after the action was # taken. This is a classic feature of temporal difference (TD) # algorithms, which acts to stitch together a general picture # of the future expected reward without actually waiting the # full duration to find out what it will be. if learn: # Ensure we are not trying to learn in a non-learning # scenario. assert reward is not None if scenario.is_dynamic: if previous_match_set is not None: match_set.pay(previous_match_set) previous_match_set.apply_payoff() match_set.payoff = reward # Remember the current reward and match set for the # next iteration. previous_match_set = match_set else: match_set.payoff = reward match_set.apply_payoff() # This serves to tie off the final stitch. The last action taken # gets only the immediate reward; there is no future reward # expected. if learn and previous_match_set is not None: previous_match_set.apply_payoff()
[ "def", "run", "(", "self", ",", "scenario", ",", "learn", "=", "True", ")", ":", "assert", "isinstance", "(", "scenario", ",", "scenarios", ".", "Scenario", ")", "previous_match_set", "=", "None", "# Repeat until the scenario has run its course.", "while", "scenario", ".", "more", "(", ")", ":", "# Gather information about the current state of the", "# environment.", "situation", "=", "scenario", ".", "sense", "(", ")", "# Determine which rules match the current situation.", "match_set", "=", "self", ".", "match", "(", "situation", ")", "# Select the best action for the current situation (or a random", "# one, if we are on an exploration step).", "match_set", ".", "select_action", "(", ")", "# Perform the selected action", "# and find out what the received reward was.", "reward", "=", "scenario", ".", "execute", "(", "match_set", ".", "selected_action", ")", "# If the scenario is dynamic, don't immediately apply the", "# reward; instead, wait until the next iteration and factor in", "# not only the reward that was received on the previous step,", "# but the (discounted) reward that is expected going forward", "# given the resulting situation observed after the action was", "# taken. This is a classic feature of temporal difference (TD)", "# algorithms, which acts to stitch together a general picture", "# of the future expected reward without actually waiting the", "# full duration to find out what it will be.", "if", "learn", ":", "# Ensure we are not trying to learn in a non-learning", "# scenario.", "assert", "reward", "is", "not", "None", "if", "scenario", ".", "is_dynamic", ":", "if", "previous_match_set", "is", "not", "None", ":", "match_set", ".", "pay", "(", "previous_match_set", ")", "previous_match_set", ".", "apply_payoff", "(", ")", "match_set", ".", "payoff", "=", "reward", "# Remember the current reward and match set for the", "# next iteration.", "previous_match_set", "=", "match_set", "else", ":", "match_set", ".", "payoff", "=", "reward", "match_set", ".", "apply_payoff", "(", ")", "# This serves to tie off the final stitch. The last action taken", "# gets only the immediate reward; there is no future reward", "# expected.", "if", "learn", "and", "previous_match_set", "is", "not", "None", ":", "previous_match_set", ".", "apply_payoff", "(", ")" ]
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. Usage: model.run(scenario, learn=True) Arguments: scenario: A Scenario instance which this classifier set is to interact with. learn: A bool indicating whether the classifier set should attempt to optimize its performance based on reward received for each action, as opposed to simply using what it has already learned from previous runs and ignoring reward received; default is True. Return: None
[ "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", "." ]
183bdd0dd339e19ded3be202f86e1b38bdb9f1e5
https://github.com/hosford42/xcs/blob/183bdd0dd339e19ded3be202f86e1b38bdb9f1e5/xcs/framework.py#L1068-L1140
train
dwavesystems/dwave-cloud-client
dwave/cloud/cli.py
ls
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=local, only_existing=not include_missing): click.echo(path)
python
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=local, only_existing=not include_missing): click.echo(path)
[ "def", "ls", "(", "system", ",", "user", ",", "local", ",", "include_missing", ")", ":", "# 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", "=", "local", ",", "only_existing", "=", "not", "include_missing", ")", ":", "click", ".", "echo", "(", "path", ")" ]
List configuration files detected (and/or examined paths).
[ "List", "configuration", "files", "detected", "(", "and", "/", "or", "examined", "paths", ")", "." ]
df3221a8385dc0c04d7b4d84f740bf3ad6706230
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/cli.py#L74-L83
train
dwavesystems/dwave-cloud-client
dwave/cloud/cli.py
inspect
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("Profile: {}".format(profile if profile else "auto-detected")) click.echo("---") for key, val in section.items(): click.echo("{} = {}".format(key, val)) except (ValueError, ConfigFileReadError, ConfigFileParseError) as e: click.echo(e)
python
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("Profile: {}".format(profile if profile else "auto-detected")) click.echo("---") for key, val in section.items(): click.echo("{} = {}".format(key, val)) except (ValueError, ConfigFileReadError, ConfigFileParseError) as e: click.echo(e)
[ "def", "inspect", "(", "config_file", ",", "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", "(", "\"Profile: {}\"", ".", "format", "(", "profile", "if", "profile", "else", "\"auto-detected\"", ")", ")", "click", ".", "echo", "(", "\"---\"", ")", "for", "key", ",", "val", "in", "section", ".", "items", "(", ")", ":", "click", ".", "echo", "(", "\"{} = {}\"", ".", "format", "(", "key", ",", "val", ")", ")", "except", "(", "ValueError", ",", "ConfigFileReadError", ",", "ConfigFileParseError", ")", "as", "e", ":", "click", ".", "echo", "(", "e", ")" ]
Inspect existing configuration/profile.
[ "Inspect", "existing", "configuration", "/", "profile", "." ]
df3221a8385dc0c04d7b4d84f740bf3ad6706230
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/cli.py#L91-L105
train
dwavesystems/dwave-cloud-client
dwave/cloud/cli.py
create
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 config_file = get_configfile_path() if config_file: click.echo("Found existing configuration file: {}".format(config_file)) else: config_file = get_default_configfile_path() click.echo("Configuration file not found; the default location is: {}".format(config_file)) config_file = default_text_input("Configuration file path", config_file) config_file = os.path.expanduser(config_file) # create config_file path config_base = os.path.dirname(config_file) if config_base and not os.path.exists(config_base): if click.confirm("Configuration file path does not exist. Create it?", abort=True): try: os.makedirs(config_base) except Exception as e: click.echo("Error creating configuration path: {}".format(e)) return 1 # try loading existing config, or use defaults try: config = load_config_from_files([config_file]) except: config = get_default_config() # determine profile if profile: click.echo("Using profile: {}".format(profile)) else: existing = config.sections() if existing: profiles = 'create new or choose from: {}'.format(', '.join(existing)) default_profile = '' else: profiles = 'create new' default_profile = 'prod' profile = default_text_input("Profile (%s)" % profiles, default_profile, optional=False) if not config.has_section(profile): config.add_section(profile) # fill out the profile variables variables = 'endpoint token client solver proxy'.split() prompts = ['API endpoint URL', 'Authentication token', 'Default client class (qpu or sw)', 'Default solver'] for var, prompt in zip(variables, prompts): default_val = config.get(profile, var, fallback=None) val = default_text_input(prompt, default_val) if val: val = os.path.expandvars(val) if val != default_val: config.set(profile, var, val) try: with open(config_file, 'w') as fp: config.write(fp) except Exception as e: click.echo("Error writing to configuration file: {}".format(e)) return 2 click.echo("Configuration saved.") return 0
python
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 config_file = get_configfile_path() if config_file: click.echo("Found existing configuration file: {}".format(config_file)) else: config_file = get_default_configfile_path() click.echo("Configuration file not found; the default location is: {}".format(config_file)) config_file = default_text_input("Configuration file path", config_file) config_file = os.path.expanduser(config_file) # create config_file path config_base = os.path.dirname(config_file) if config_base and not os.path.exists(config_base): if click.confirm("Configuration file path does not exist. Create it?", abort=True): try: os.makedirs(config_base) except Exception as e: click.echo("Error creating configuration path: {}".format(e)) return 1 # try loading existing config, or use defaults try: config = load_config_from_files([config_file]) except: config = get_default_config() # determine profile if profile: click.echo("Using profile: {}".format(profile)) else: existing = config.sections() if existing: profiles = 'create new or choose from: {}'.format(', '.join(existing)) default_profile = '' else: profiles = 'create new' default_profile = 'prod' profile = default_text_input("Profile (%s)" % profiles, default_profile, optional=False) if not config.has_section(profile): config.add_section(profile) # fill out the profile variables variables = 'endpoint token client solver proxy'.split() prompts = ['API endpoint URL', 'Authentication token', 'Default client class (qpu or sw)', 'Default solver'] for var, prompt in zip(variables, prompts): default_val = config.get(profile, var, fallback=None) val = default_text_input(prompt, default_val) if val: val = os.path.expandvars(val) if val != default_val: config.set(profile, var, val) try: with open(config_file, 'w') as fp: config.write(fp) except Exception as e: click.echo("Error writing to configuration file: {}".format(e)) return 2 click.echo("Configuration saved.") return 0
[ "def", "create", "(", "config_file", ",", "profile", ")", ":", "# 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", "config_file", "=", "get_configfile_path", "(", ")", "if", "config_file", ":", "click", ".", "echo", "(", "\"Found existing configuration file: {}\"", ".", "format", "(", "config_file", ")", ")", "else", ":", "config_file", "=", "get_default_configfile_path", "(", ")", "click", ".", "echo", "(", "\"Configuration file not found; the default location is: {}\"", ".", "format", "(", "config_file", ")", ")", "config_file", "=", "default_text_input", "(", "\"Configuration file path\"", ",", "config_file", ")", "config_file", "=", "os", ".", "path", ".", "expanduser", "(", "config_file", ")", "# create config_file path", "config_base", "=", "os", ".", "path", ".", "dirname", "(", "config_file", ")", "if", "config_base", "and", "not", "os", ".", "path", ".", "exists", "(", "config_base", ")", ":", "if", "click", ".", "confirm", "(", "\"Configuration file path does not exist. Create it?\"", ",", "abort", "=", "True", ")", ":", "try", ":", "os", ".", "makedirs", "(", "config_base", ")", "except", "Exception", "as", "e", ":", "click", ".", "echo", "(", "\"Error creating configuration path: {}\"", ".", "format", "(", "e", ")", ")", "return", "1", "# try loading existing config, or use defaults", "try", ":", "config", "=", "load_config_from_files", "(", "[", "config_file", "]", ")", "except", ":", "config", "=", "get_default_config", "(", ")", "# determine profile", "if", "profile", ":", "click", ".", "echo", "(", "\"Using profile: {}\"", ".", "format", "(", "profile", ")", ")", "else", ":", "existing", "=", "config", ".", "sections", "(", ")", "if", "existing", ":", "profiles", "=", "'create new or choose from: {}'", ".", "format", "(", "', '", ".", "join", "(", "existing", ")", ")", "default_profile", "=", "''", "else", ":", "profiles", "=", "'create new'", "default_profile", "=", "'prod'", "profile", "=", "default_text_input", "(", "\"Profile (%s)\"", "%", "profiles", ",", "default_profile", ",", "optional", "=", "False", ")", "if", "not", "config", ".", "has_section", "(", "profile", ")", ":", "config", ".", "add_section", "(", "profile", ")", "# fill out the profile variables", "variables", "=", "'endpoint token client solver proxy'", ".", "split", "(", ")", "prompts", "=", "[", "'API endpoint URL'", ",", "'Authentication token'", ",", "'Default client class (qpu or sw)'", ",", "'Default solver'", "]", "for", "var", ",", "prompt", "in", "zip", "(", "variables", ",", "prompts", ")", ":", "default_val", "=", "config", ".", "get", "(", "profile", ",", "var", ",", "fallback", "=", "None", ")", "val", "=", "default_text_input", "(", "prompt", ",", "default_val", ")", "if", "val", ":", "val", "=", "os", ".", "path", ".", "expandvars", "(", "val", ")", "if", "val", "!=", "default_val", ":", "config", ".", "set", "(", "profile", ",", "var", ",", "val", ")", "try", ":", "with", "open", "(", "config_file", ",", "'w'", ")", "as", "fp", ":", "config", ".", "write", "(", "fp", ")", "except", "Exception", "as", "e", ":", "click", ".", "echo", "(", "\"Error writing to configuration file: {}\"", ".", "format", "(", "e", ")", ")", "return", "2", "click", ".", "echo", "(", "\"Configuration saved.\"", ")", "return", "0" ]
Create and/or update cloud client configuration file.
[ "Create", "and", "/", "or", "update", "cloud", "client", "configuration", "file", "." ]
df3221a8385dc0c04d7b4d84f740bf3ad6706230
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/cli.py#L113-L184
train
dwavesystems/dwave-cloud-client
dwave/cloud/cli.py
_ping
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 = dict(config_file=config_file, profile=profile, solver=solver_def) if request_timeout is not None: config.update(request_timeout=request_timeout) if polling_timeout is not None: config.update(polling_timeout=polling_timeout) try: client = Client.from_config(**config) except Exception as e: raise CLIError("Invalid configuration: {}".format(e), code=1) if config_file: output("Using configuration file: {config_file}", config_file=config_file) if profile: output("Using profile: {profile}", profile=profile) output("Using endpoint: {endpoint}", endpoint=client.endpoint) t0 = timer() try: solver = client.get_solver() except SolverAuthenticationError: raise CLIError("Authentication error. Check credentials in your configuration file.", 2) except SolverNotFoundError: raise CLIError("Solver not available.", 6) except (InvalidAPIResponseError, UnsupportedSolverError): raise CLIError("Invalid or unexpected API response.", 3) except RequestTimeout: raise CLIError("API connection timed out.", 4) except requests.exceptions.SSLError as e: # we need to handle `ssl.SSLError` wrapped in several exceptions, # with differences between py2/3; greping the message is the easiest way if 'CERTIFICATE_VERIFY_FAILED' in str(e): raise CLIError( "Certificate verification failed. Please check that your API endpoint " "is correct. If you are connecting to a private or third-party D-Wave " "system that uses self-signed certificate(s), please see " "https://support.dwavesys.com/hc/en-us/community/posts/360018930954.", 5) raise CLIError("Unexpected SSL error while fetching solver: {!r}".format(e), 5) except Exception as e: raise CLIError("Unexpected error while fetching solver: {!r}".format(e), 5) t1 = timer() output("Using solver: {solver_id}", solver_id=solver.id) try: future = solver.sample_ising({0: 1}, {}) timing = future.timing except RequestTimeout: raise CLIError("API connection timed out.", 8) except PollingTimeout: raise CLIError("Polling timeout exceeded.", 9) except Exception as e: raise CLIError("Sampling error: {!r}".format(e), 10) finally: output("Submitted problem ID: {problem_id}", problem_id=future.id) t2 = timer() output("\nWall clock time:") output(" * Solver definition fetch: {wallclock_solver_definition:.3f} ms", wallclock_solver_definition=(t1-t0)*1000.0) output(" * Problem submit and results fetch: {wallclock_sampling:.3f} ms", wallclock_sampling=(t2-t1)*1000.0) output(" * Total: {wallclock_total:.3f} ms", wallclock_total=(t2-t0)*1000.0) if timing.items(): output("\nQPU timing:") for component, duration in timing.items(): output(" * %(name)s = {%(name)s} us" % {"name": component}, **{component: duration}) else: output("\nQPU timing data not available.")
python
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 = dict(config_file=config_file, profile=profile, solver=solver_def) if request_timeout is not None: config.update(request_timeout=request_timeout) if polling_timeout is not None: config.update(polling_timeout=polling_timeout) try: client = Client.from_config(**config) except Exception as e: raise CLIError("Invalid configuration: {}".format(e), code=1) if config_file: output("Using configuration file: {config_file}", config_file=config_file) if profile: output("Using profile: {profile}", profile=profile) output("Using endpoint: {endpoint}", endpoint=client.endpoint) t0 = timer() try: solver = client.get_solver() except SolverAuthenticationError: raise CLIError("Authentication error. Check credentials in your configuration file.", 2) except SolverNotFoundError: raise CLIError("Solver not available.", 6) except (InvalidAPIResponseError, UnsupportedSolverError): raise CLIError("Invalid or unexpected API response.", 3) except RequestTimeout: raise CLIError("API connection timed out.", 4) except requests.exceptions.SSLError as e: # we need to handle `ssl.SSLError` wrapped in several exceptions, # with differences between py2/3; greping the message is the easiest way if 'CERTIFICATE_VERIFY_FAILED' in str(e): raise CLIError( "Certificate verification failed. Please check that your API endpoint " "is correct. If you are connecting to a private or third-party D-Wave " "system that uses self-signed certificate(s), please see " "https://support.dwavesys.com/hc/en-us/community/posts/360018930954.", 5) raise CLIError("Unexpected SSL error while fetching solver: {!r}".format(e), 5) except Exception as e: raise CLIError("Unexpected error while fetching solver: {!r}".format(e), 5) t1 = timer() output("Using solver: {solver_id}", solver_id=solver.id) try: future = solver.sample_ising({0: 1}, {}) timing = future.timing except RequestTimeout: raise CLIError("API connection timed out.", 8) except PollingTimeout: raise CLIError("Polling timeout exceeded.", 9) except Exception as e: raise CLIError("Sampling error: {!r}".format(e), 10) finally: output("Submitted problem ID: {problem_id}", problem_id=future.id) t2 = timer() output("\nWall clock time:") output(" * Solver definition fetch: {wallclock_solver_definition:.3f} ms", wallclock_solver_definition=(t1-t0)*1000.0) output(" * Problem submit and results fetch: {wallclock_sampling:.3f} ms", wallclock_sampling=(t2-t1)*1000.0) output(" * Total: {wallclock_total:.3f} ms", wallclock_total=(t2-t0)*1000.0) if timing.items(): output("\nQPU timing:") for component, duration in timing.items(): output(" * %(name)s = {%(name)s} us" % {"name": component}, **{component: duration}) else: output("\nQPU timing data not available.")
[ "def", "_ping", "(", "config_file", ",", "profile", ",", "solver_def", ",", "request_timeout", ",", "polling_timeout", ",", "output", ")", ":", "config", "=", "dict", "(", "config_file", "=", "config_file", ",", "profile", "=", "profile", ",", "solver", "=", "solver_def", ")", "if", "request_timeout", "is", "not", "None", ":", "config", ".", "update", "(", "request_timeout", "=", "request_timeout", ")", "if", "polling_timeout", "is", "not", "None", ":", "config", ".", "update", "(", "polling_timeout", "=", "polling_timeout", ")", "try", ":", "client", "=", "Client", ".", "from_config", "(", "*", "*", "config", ")", "except", "Exception", "as", "e", ":", "raise", "CLIError", "(", "\"Invalid configuration: {}\"", ".", "format", "(", "e", ")", ",", "code", "=", "1", ")", "if", "config_file", ":", "output", "(", "\"Using configuration file: {config_file}\"", ",", "config_file", "=", "config_file", ")", "if", "profile", ":", "output", "(", "\"Using profile: {profile}\"", ",", "profile", "=", "profile", ")", "output", "(", "\"Using endpoint: {endpoint}\"", ",", "endpoint", "=", "client", ".", "endpoint", ")", "t0", "=", "timer", "(", ")", "try", ":", "solver", "=", "client", ".", "get_solver", "(", ")", "except", "SolverAuthenticationError", ":", "raise", "CLIError", "(", "\"Authentication error. Check credentials in your configuration file.\"", ",", "2", ")", "except", "SolverNotFoundError", ":", "raise", "CLIError", "(", "\"Solver not available.\"", ",", "6", ")", "except", "(", "InvalidAPIResponseError", ",", "UnsupportedSolverError", ")", ":", "raise", "CLIError", "(", "\"Invalid or unexpected API response.\"", ",", "3", ")", "except", "RequestTimeout", ":", "raise", "CLIError", "(", "\"API connection timed out.\"", ",", "4", ")", "except", "requests", ".", "exceptions", ".", "SSLError", "as", "e", ":", "# we need to handle `ssl.SSLError` wrapped in several exceptions,", "# with differences between py2/3; greping the message is the easiest way", "if", "'CERTIFICATE_VERIFY_FAILED'", "in", "str", "(", "e", ")", ":", "raise", "CLIError", "(", "\"Certificate verification failed. Please check that your API endpoint \"", "\"is correct. If you are connecting to a private or third-party D-Wave \"", "\"system that uses self-signed certificate(s), please see \"", "\"https://support.dwavesys.com/hc/en-us/community/posts/360018930954.\"", ",", "5", ")", "raise", "CLIError", "(", "\"Unexpected SSL error while fetching solver: {!r}\"", ".", "format", "(", "e", ")", ",", "5", ")", "except", "Exception", "as", "e", ":", "raise", "CLIError", "(", "\"Unexpected error while fetching solver: {!r}\"", ".", "format", "(", "e", ")", ",", "5", ")", "t1", "=", "timer", "(", ")", "output", "(", "\"Using solver: {solver_id}\"", ",", "solver_id", "=", "solver", ".", "id", ")", "try", ":", "future", "=", "solver", ".", "sample_ising", "(", "{", "0", ":", "1", "}", ",", "{", "}", ")", "timing", "=", "future", ".", "timing", "except", "RequestTimeout", ":", "raise", "CLIError", "(", "\"API connection timed out.\"", ",", "8", ")", "except", "PollingTimeout", ":", "raise", "CLIError", "(", "\"Polling timeout exceeded.\"", ",", "9", ")", "except", "Exception", "as", "e", ":", "raise", "CLIError", "(", "\"Sampling error: {!r}\"", ".", "format", "(", "e", ")", ",", "10", ")", "finally", ":", "output", "(", "\"Submitted problem ID: {problem_id}\"", ",", "problem_id", "=", "future", ".", "id", ")", "t2", "=", "timer", "(", ")", "output", "(", "\"\\nWall clock time:\"", ")", "output", "(", "\" * Solver definition fetch: {wallclock_solver_definition:.3f} ms\"", ",", "wallclock_solver_definition", "=", "(", "t1", "-", "t0", ")", "*", "1000.0", ")", "output", "(", "\" * Problem submit and results fetch: {wallclock_sampling:.3f} ms\"", ",", "wallclock_sampling", "=", "(", "t2", "-", "t1", ")", "*", "1000.0", ")", "output", "(", "\" * Total: {wallclock_total:.3f} ms\"", ",", "wallclock_total", "=", "(", "t2", "-", "t0", ")", "*", "1000.0", ")", "if", "timing", ".", "items", "(", ")", ":", "output", "(", "\"\\nQPU timing:\"", ")", "for", "component", ",", "duration", "in", "timing", ".", "items", "(", ")", ":", "output", "(", "\" * %(name)s = {%(name)s} us\"", "%", "{", "\"name\"", ":", "component", "}", ",", "*", "*", "{", "component", ":", "duration", "}", ")", "else", ":", "output", "(", "\"\\nQPU timing data not available.\"", ")" ]
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.
[ "Helper", "method", "for", "the", "ping", "command", "that", "uses", "output", "()", "for", "info", "output", "and", "raises", "CLIError", "()", "on", "handled", "errors", "." ]
df3221a8385dc0c04d7b4d84f740bf3ad6706230
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/cli.py#L187-L259
train
dwavesystems/dwave-cloud-client
dwave/cloud/cli.py
ping
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) if not json_output: click.echo(fmt.format(**kwargs)) def flush(): if json_output: click.echo(json.dumps(info)) try: _ping(config_file, profile, solver_def, request_timeout, polling_timeout, output) except CLIError as error: output("Error: {error} (code: {code})", error=str(error), code=error.code) sys.exit(error.code) except Exception as error: output("Unhandled error: {error}", error=str(error)) sys.exit(127) finally: flush()
python
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) if not json_output: click.echo(fmt.format(**kwargs)) def flush(): if json_output: click.echo(json.dumps(info)) try: _ping(config_file, profile, solver_def, request_timeout, polling_timeout, output) except CLIError as error: output("Error: {error} (code: {code})", error=str(error), code=error.code) sys.exit(error.code) except Exception as error: output("Unhandled error: {error}", error=str(error)) sys.exit(127) finally: flush()
[ "def", "ping", "(", "config_file", ",", "profile", ",", "solver_def", ",", "json_output", ",", "request_timeout", ",", "polling_timeout", ")", ":", "now", "=", "utcnow", "(", ")", "info", "=", "dict", "(", "datetime", "=", "now", ".", "isoformat", "(", ")", ",", "timestamp", "=", "datetime_to_timestamp", "(", "now", ")", ",", "code", "=", "0", ")", "def", "output", "(", "fmt", ",", "*", "*", "kwargs", ")", ":", "info", ".", "update", "(", "kwargs", ")", "if", "not", "json_output", ":", "click", ".", "echo", "(", "fmt", ".", "format", "(", "*", "*", "kwargs", ")", ")", "def", "flush", "(", ")", ":", "if", "json_output", ":", "click", ".", "echo", "(", "json", ".", "dumps", "(", "info", ")", ")", "try", ":", "_ping", "(", "config_file", ",", "profile", ",", "solver_def", ",", "request_timeout", ",", "polling_timeout", ",", "output", ")", "except", "CLIError", "as", "error", ":", "output", "(", "\"Error: {error} (code: {code})\"", ",", "error", "=", "str", "(", "error", ")", ",", "code", "=", "error", ".", "code", ")", "sys", ".", "exit", "(", "error", ".", "code", ")", "except", "Exception", "as", "error", ":", "output", "(", "\"Unhandled error: {error}\"", ",", "error", "=", "str", "(", "error", ")", ")", "sys", ".", "exit", "(", "127", ")", "finally", ":", "flush", "(", ")" ]
Ping the QPU by submitting a single-qubit problem.
[ "Ping", "the", "QPU", "by", "submitting", "a", "single", "-", "qubit", "problem", "." ]
df3221a8385dc0c04d7b4d84f740bf3ad6706230
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/cli.py#L274-L298
train
dwavesystems/dwave-cloud-client
dwave/cloud/cli.py
solvers
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=solver_def) as client: try: solvers = client.get_solvers(**client.default_solver) except SolverNotFoundError: click.echo("Solver(s) {} not found.".format(solver_def)) return 1 if list_solvers: for solver in solvers: click.echo(solver.id) return # ~YAML output for solver in solvers: click.echo("Solver: {}".format(solver.id)) click.echo(" Parameters:") for name, val in sorted(solver.parameters.items()): click.echo(" {}: {}".format(name, strtrunc(val) if val else '?')) solver.properties.pop('parameters', None) click.echo(" Properties:") for name, val in sorted(solver.properties.items()): click.echo(" {}: {}".format(name, strtrunc(val))) click.echo(" Derived properties:") for name in sorted(solver.derived_properties): click.echo(" {}: {}".format(name, strtrunc(getattr(solver, name)))) click.echo()
python
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=solver_def) as client: try: solvers = client.get_solvers(**client.default_solver) except SolverNotFoundError: click.echo("Solver(s) {} not found.".format(solver_def)) return 1 if list_solvers: for solver in solvers: click.echo(solver.id) return # ~YAML output for solver in solvers: click.echo("Solver: {}".format(solver.id)) click.echo(" Parameters:") for name, val in sorted(solver.parameters.items()): click.echo(" {}: {}".format(name, strtrunc(val) if val else '?')) solver.properties.pop('parameters', None) click.echo(" Properties:") for name, val in sorted(solver.properties.items()): click.echo(" {}: {}".format(name, strtrunc(val))) click.echo(" Derived properties:") for name in sorted(solver.derived_properties): click.echo(" {}: {}".format(name, strtrunc(getattr(solver, name)))) click.echo()
[ "def", "solvers", "(", "config_file", ",", "profile", ",", "solver_def", ",", "list_solvers", ")", ":", "with", "Client", ".", "from_config", "(", "config_file", "=", "config_file", ",", "profile", "=", "profile", ",", "solver", "=", "solver_def", ")", "as", "client", ":", "try", ":", "solvers", "=", "client", ".", "get_solvers", "(", "*", "*", "client", ".", "default_solver", ")", "except", "SolverNotFoundError", ":", "click", ".", "echo", "(", "\"Solver(s) {} not found.\"", ".", "format", "(", "solver_def", ")", ")", "return", "1", "if", "list_solvers", ":", "for", "solver", "in", "solvers", ":", "click", ".", "echo", "(", "solver", ".", "id", ")", "return", "# ~YAML output", "for", "solver", "in", "solvers", ":", "click", ".", "echo", "(", "\"Solver: {}\"", ".", "format", "(", "solver", ".", "id", ")", ")", "click", ".", "echo", "(", "\" Parameters:\"", ")", "for", "name", ",", "val", "in", "sorted", "(", "solver", ".", "parameters", ".", "items", "(", ")", ")", ":", "click", ".", "echo", "(", "\" {}: {}\"", ".", "format", "(", "name", ",", "strtrunc", "(", "val", ")", "if", "val", "else", "'?'", ")", ")", "solver", ".", "properties", ".", "pop", "(", "'parameters'", ",", "None", ")", "click", ".", "echo", "(", "\" Properties:\"", ")", "for", "name", ",", "val", "in", "sorted", "(", "solver", ".", "properties", ".", "items", "(", ")", ")", ":", "click", ".", "echo", "(", "\" {}: {}\"", ".", "format", "(", "name", ",", "strtrunc", "(", "val", ")", ")", ")", "click", ".", "echo", "(", "\" Derived properties:\"", ")", "for", "name", "in", "sorted", "(", "solver", ".", "derived_properties", ")", ":", "click", ".", "echo", "(", "\" {}: {}\"", ".", "format", "(", "name", ",", "strtrunc", "(", "getattr", "(", "solver", ",", "name", ")", ")", ")", ")", "click", ".", "echo", "(", ")" ]
Get solver details. Unless solver name/id specified, fetch and display details for all online solvers available on the configured endpoint.
[ "Get", "solver", "details", "." ]
df3221a8385dc0c04d7b4d84f740bf3ad6706230
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/cli.py#L308-L342
train
dwavesystems/dwave-cloud-client
dwave/cloud/cli.py
sample
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 = Client.from_config( config_file=config_file, profile=profile, solver=solver_def) except Exception as e: click.echo("Invalid configuration: {}".format(e)) return 1 if config_file: echo("Using configuration file: {}".format(config_file)) if profile: echo("Using profile: {}".format(profile)) echo("Using endpoint: {}".format(client.endpoint)) try: solver = client.get_solver() except SolverAuthenticationError: click.echo("Authentication error. Check credentials in your configuration file.") return 1 except (InvalidAPIResponseError, UnsupportedSolverError): click.echo("Invalid or unexpected API response.") return 2 except SolverNotFoundError: click.echo("Solver with the specified features does not exist.") return 3 echo("Using solver: {}".format(solver.id)) if random_problem: linear, quadratic = generate_random_ising_problem(solver) else: try: linear = ast.literal_eval(biases) if biases else [] except Exception as e: click.echo("Invalid biases: {}".format(e)) try: quadratic = ast.literal_eval(couplings) if couplings else {} except Exception as e: click.echo("Invalid couplings: {}".format(e)) echo("Using qubit biases: {!r}".format(linear)) echo("Using qubit couplings: {!r}".format(quadratic)) echo("Number of samples: {}".format(num_reads)) try: result = solver.sample_ising(linear, quadratic, num_reads=num_reads).result() except Exception as e: click.echo(e) return 4 if verbose: click.echo("Result: {!r}".format(result)) echo("Samples: {!r}".format(result['samples'])) echo("Occurrences: {!r}".format(result['occurrences'])) echo("Energies: {!r}".format(result['energies']))
python
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 = Client.from_config( config_file=config_file, profile=profile, solver=solver_def) except Exception as e: click.echo("Invalid configuration: {}".format(e)) return 1 if config_file: echo("Using configuration file: {}".format(config_file)) if profile: echo("Using profile: {}".format(profile)) echo("Using endpoint: {}".format(client.endpoint)) try: solver = client.get_solver() except SolverAuthenticationError: click.echo("Authentication error. Check credentials in your configuration file.") return 1 except (InvalidAPIResponseError, UnsupportedSolverError): click.echo("Invalid or unexpected API response.") return 2 except SolverNotFoundError: click.echo("Solver with the specified features does not exist.") return 3 echo("Using solver: {}".format(solver.id)) if random_problem: linear, quadratic = generate_random_ising_problem(solver) else: try: linear = ast.literal_eval(biases) if biases else [] except Exception as e: click.echo("Invalid biases: {}".format(e)) try: quadratic = ast.literal_eval(couplings) if couplings else {} except Exception as e: click.echo("Invalid couplings: {}".format(e)) echo("Using qubit biases: {!r}".format(linear)) echo("Using qubit couplings: {!r}".format(quadratic)) echo("Number of samples: {}".format(num_reads)) try: result = solver.sample_ising(linear, quadratic, num_reads=num_reads).result() except Exception as e: click.echo(e) return 4 if verbose: click.echo("Result: {!r}".format(result)) echo("Samples: {!r}".format(result['samples'])) echo("Occurrences: {!r}".format(result['occurrences'])) echo("Energies: {!r}".format(result['energies']))
[ "def", "sample", "(", "config_file", ",", "profile", ",", "solver_def", ",", "biases", ",", "couplings", ",", "random_problem", ",", "num_reads", ",", "verbose", ")", ":", "# TODO: de-dup wrt ping", "def", "echo", "(", "s", ",", "maxlen", "=", "100", ")", ":", "click", ".", "echo", "(", "s", "if", "verbose", "else", "strtrunc", "(", "s", ",", "maxlen", ")", ")", "try", ":", "client", "=", "Client", ".", "from_config", "(", "config_file", "=", "config_file", ",", "profile", "=", "profile", ",", "solver", "=", "solver_def", ")", "except", "Exception", "as", "e", ":", "click", ".", "echo", "(", "\"Invalid configuration: {}\"", ".", "format", "(", "e", ")", ")", "return", "1", "if", "config_file", ":", "echo", "(", "\"Using configuration file: {}\"", ".", "format", "(", "config_file", ")", ")", "if", "profile", ":", "echo", "(", "\"Using profile: {}\"", ".", "format", "(", "profile", ")", ")", "echo", "(", "\"Using endpoint: {}\"", ".", "format", "(", "client", ".", "endpoint", ")", ")", "try", ":", "solver", "=", "client", ".", "get_solver", "(", ")", "except", "SolverAuthenticationError", ":", "click", ".", "echo", "(", "\"Authentication error. Check credentials in your configuration file.\"", ")", "return", "1", "except", "(", "InvalidAPIResponseError", ",", "UnsupportedSolverError", ")", ":", "click", ".", "echo", "(", "\"Invalid or unexpected API response.\"", ")", "return", "2", "except", "SolverNotFoundError", ":", "click", ".", "echo", "(", "\"Solver with the specified features does not exist.\"", ")", "return", "3", "echo", "(", "\"Using solver: {}\"", ".", "format", "(", "solver", ".", "id", ")", ")", "if", "random_problem", ":", "linear", ",", "quadratic", "=", "generate_random_ising_problem", "(", "solver", ")", "else", ":", "try", ":", "linear", "=", "ast", ".", "literal_eval", "(", "biases", ")", "if", "biases", "else", "[", "]", "except", "Exception", "as", "e", ":", "click", ".", "echo", "(", "\"Invalid biases: {}\"", ".", "format", "(", "e", ")", ")", "try", ":", "quadratic", "=", "ast", ".", "literal_eval", "(", "couplings", ")", "if", "couplings", "else", "{", "}", "except", "Exception", "as", "e", ":", "click", ".", "echo", "(", "\"Invalid couplings: {}\"", ".", "format", "(", "e", ")", ")", "echo", "(", "\"Using qubit biases: {!r}\"", ".", "format", "(", "linear", ")", ")", "echo", "(", "\"Using qubit couplings: {!r}\"", ".", "format", "(", "quadratic", ")", ")", "echo", "(", "\"Number of samples: {}\"", ".", "format", "(", "num_reads", ")", ")", "try", ":", "result", "=", "solver", ".", "sample_ising", "(", "linear", ",", "quadratic", ",", "num_reads", "=", "num_reads", ")", ".", "result", "(", ")", "except", "Exception", "as", "e", ":", "click", ".", "echo", "(", "e", ")", "return", "4", "if", "verbose", ":", "click", ".", "echo", "(", "\"Result: {!r}\"", ".", "format", "(", "result", ")", ")", "echo", "(", "\"Samples: {!r}\"", ".", "format", "(", "result", "[", "'samples'", "]", ")", ")", "echo", "(", "\"Occurrences: {!r}\"", ".", "format", "(", "result", "[", "'occurrences'", "]", ")", ")", "echo", "(", "\"Energies: {!r}\"", ".", "format", "(", "result", "[", "'energies'", "]", ")", ")" ]
Submit Ising-formulated problem and return samples.
[ "Submit", "Ising", "-", "formulated", "problem", "and", "return", "samples", "." ]
df3221a8385dc0c04d7b4d84f740bf3ad6706230
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/cli.py#L362-L424
train
tuxu/python-samplerate
examples/play_modulation.py
get_input_callback
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 generated on each call. """ amplitude = params['mod_amplitude'] frequency = params['mod_frequency'] def producer(): """Generate samples. Yields ------ samples : ndarray A number of samples (`num_samples`) of the sine. """ start_time = 0 while True: time = start_time + np.arange(num_samples) / samplerate start_time += num_samples / samplerate output = amplitude * np.cos(2 * np.pi * frequency * time) yield output return lambda p=producer(): next(p)
python
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 generated on each call. """ amplitude = params['mod_amplitude'] frequency = params['mod_frequency'] def producer(): """Generate samples. Yields ------ samples : ndarray A number of samples (`num_samples`) of the sine. """ start_time = 0 while True: time = start_time + np.arange(num_samples) / samplerate start_time += num_samples / samplerate output = amplitude * np.cos(2 * np.pi * frequency * time) yield output return lambda p=producer(): next(p)
[ "def", "get_input_callback", "(", "samplerate", ",", "params", ",", "num_samples", "=", "256", ")", ":", "amplitude", "=", "params", "[", "'mod_amplitude'", "]", "frequency", "=", "params", "[", "'mod_frequency'", "]", "def", "producer", "(", ")", ":", "\"\"\"Generate samples.\n\n Yields\n ------\n samples : ndarray\n A number of samples (`num_samples`) of the sine.\n \"\"\"", "start_time", "=", "0", "while", "True", ":", "time", "=", "start_time", "+", "np", ".", "arange", "(", "num_samples", ")", "/", "samplerate", "start_time", "+=", "num_samples", "/", "samplerate", "output", "=", "amplitude", "*", "np", ".", "cos", "(", "2", "*", "np", ".", "pi", "*", "frequency", "*", "time", ")", "yield", "output", "return", "lambda", "p", "=", "producer", "(", ")", ":", "next", "(", "p", ")" ]
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 generated on each call.
[ "Return", "a", "function", "that", "produces", "samples", "of", "a", "sine", "." ]
ed73d7a39e61bfb34b03dade14ffab59aa27922a
https://github.com/tuxu/python-samplerate/blob/ed73d7a39e61bfb34b03dade14ffab59aa27922a/examples/play_modulation.py#L27-L57
train
tuxu/python-samplerate
examples/play_modulation.py
get_playback_callback
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 callback(outdata, frames, time, _): """Playback callback. Read samples from the resampler and modulate them onto a carrier frequency. """ last_fmphase = getattr(callback, 'last_fmphase', 0) df = params['fm_gain'] * resampler.read(frames) df = np.pad(df, (0, frames - len(df)), mode='constant') t = time.outputBufferDacTime + np.arange(frames) / samplerate phase = 2 * np.pi * params['carrier_frequency'] * t fmphase = last_fmphase + 2 * np.pi * np.cumsum(df) / samplerate outdata[:, 0] = params['output_volume'] * np.cos(phase + fmphase) callback.last_fmphase = fmphase[-1] return callback
python
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 callback(outdata, frames, time, _): """Playback callback. Read samples from the resampler and modulate them onto a carrier frequency. """ last_fmphase = getattr(callback, 'last_fmphase', 0) df = params['fm_gain'] * resampler.read(frames) df = np.pad(df, (0, frames - len(df)), mode='constant') t = time.outputBufferDacTime + np.arange(frames) / samplerate phase = 2 * np.pi * params['carrier_frequency'] * t fmphase = last_fmphase + 2 * np.pi * np.cumsum(df) / samplerate outdata[:, 0] = params['output_volume'] * np.cos(phase + fmphase) callback.last_fmphase = fmphase[-1] return callback
[ "def", "get_playback_callback", "(", "resampler", ",", "samplerate", ",", "params", ")", ":", "def", "callback", "(", "outdata", ",", "frames", ",", "time", ",", "_", ")", ":", "\"\"\"Playback callback.\n\n Read samples from the resampler and modulate them onto a carrier\n frequency.\n \"\"\"", "last_fmphase", "=", "getattr", "(", "callback", ",", "'last_fmphase'", ",", "0", ")", "df", "=", "params", "[", "'fm_gain'", "]", "*", "resampler", ".", "read", "(", "frames", ")", "df", "=", "np", ".", "pad", "(", "df", ",", "(", "0", ",", "frames", "-", "len", "(", "df", ")", ")", ",", "mode", "=", "'constant'", ")", "t", "=", "time", ".", "outputBufferDacTime", "+", "np", ".", "arange", "(", "frames", ")", "/", "samplerate", "phase", "=", "2", "*", "np", ".", "pi", "*", "params", "[", "'carrier_frequency'", "]", "*", "t", "fmphase", "=", "last_fmphase", "+", "2", "*", "np", ".", "pi", "*", "np", ".", "cumsum", "(", "df", ")", "/", "samplerate", "outdata", "[", ":", ",", "0", "]", "=", "params", "[", "'output_volume'", "]", "*", "np", ".", "cos", "(", "phase", "+", "fmphase", ")", "callback", ".", "last_fmphase", "=", "fmphase", "[", "-", "1", "]", "return", "callback" ]
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.
[ "Return", "a", "sound", "playback", "callback", "." ]
ed73d7a39e61bfb34b03dade14ffab59aa27922a
https://github.com/tuxu/python-samplerate/blob/ed73d7a39e61bfb34b03dade14ffab59aa27922a/examples/play_modulation.py#L60-L88
train
tuxu/python-samplerate
examples/play_modulation.py
main
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), ratio, converter_type) as resampler, \ sd.OutputStream(channels=1, samplerate=target_samplerate, callback=get_playback_callback( resampler, target_samplerate, params)): print("Playing back... Ctrl+C to stop.") try: while True: sleep(1) except KeyboardInterrupt: print("Aborting.")
python
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), ratio, converter_type) as resampler, \ sd.OutputStream(channels=1, samplerate=target_samplerate, callback=get_playback_callback( resampler, target_samplerate, params)): print("Playing back... Ctrl+C to stop.") try: while True: sleep(1) except KeyboardInterrupt: print("Aborting.")
[ "def", "main", "(", "source_samplerate", ",", "target_samplerate", ",", "params", ",", "converter_type", ")", ":", "from", "time", "import", "sleep", "ratio", "=", "target_samplerate", "/", "source_samplerate", "with", "sr", ".", "CallbackResampler", "(", "get_input_callback", "(", "source_samplerate", ",", "params", ")", ",", "ratio", ",", "converter_type", ")", "as", "resampler", ",", "sd", ".", "OutputStream", "(", "channels", "=", "1", ",", "samplerate", "=", "target_samplerate", ",", "callback", "=", "get_playback_callback", "(", "resampler", ",", "target_samplerate", ",", "params", ")", ")", ":", "print", "(", "\"Playing back... Ctrl+C to stop.\"", ")", "try", ":", "while", "True", ":", "sleep", "(", "1", ")", "except", "KeyboardInterrupt", ":", "print", "(", "\"Aborting.\"", ")" ]
Setup the resampling and audio output callbacks and start playback.
[ "Setup", "the", "resampling", "and", "audio", "output", "callbacks", "and", "start", "playback", "." ]
ed73d7a39e61bfb34b03dade14ffab59aa27922a
https://github.com/tuxu/python-samplerate/blob/ed73d7a39e61bfb34b03dade14ffab59aa27922a/examples/play_modulation.py#L91-L107
train
dwavesystems/dwave-cloud-client
dwave/cloud/solver.py
Solver.max_num_reads
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 - num_reads - programming_thermalization Returns: int: The maximum number of reads. """ # dev note: in the future it would be good to have a way of doing this # server-side, as we are duplicating logic here. properties = self.properties if self.software or not params: # software solvers don't use any of the above parameters return properties['num_reads_range'][1] # qpu _, duration = properties['problem_run_duration_range'] annealing_time = params.get('annealing_time', properties['default_annealing_time']) readout_thermalization = params.get('readout_thermalization', properties['default_readout_thermalization']) programming_thermalization = params.get('programming_thermalization', properties['default_programming_thermalization']) return min(properties['num_reads_range'][1], int((duration - programming_thermalization) / (annealing_time + readout_thermalization)))
python
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 - num_reads - programming_thermalization Returns: int: The maximum number of reads. """ # dev note: in the future it would be good to have a way of doing this # server-side, as we are duplicating logic here. properties = self.properties if self.software or not params: # software solvers don't use any of the above parameters return properties['num_reads_range'][1] # qpu _, duration = properties['problem_run_duration_range'] annealing_time = params.get('annealing_time', properties['default_annealing_time']) readout_thermalization = params.get('readout_thermalization', properties['default_readout_thermalization']) programming_thermalization = params.get('programming_thermalization', properties['default_programming_thermalization']) return min(properties['num_reads_range'][1], int((duration - programming_thermalization) / (annealing_time + readout_thermalization)))
[ "def", "max_num_reads", "(", "self", ",", "*", "*", "params", ")", ":", "# dev note: in the future it would be good to have a way of doing this", "# server-side, as we are duplicating logic here.", "properties", "=", "self", ".", "properties", "if", "self", ".", "software", "or", "not", "params", ":", "# software solvers don't use any of the above parameters", "return", "properties", "[", "'num_reads_range'", "]", "[", "1", "]", "# qpu", "_", ",", "duration", "=", "properties", "[", "'problem_run_duration_range'", "]", "annealing_time", "=", "params", ".", "get", "(", "'annealing_time'", ",", "properties", "[", "'default_annealing_time'", "]", ")", "readout_thermalization", "=", "params", ".", "get", "(", "'readout_thermalization'", ",", "properties", "[", "'default_readout_thermalization'", "]", ")", "programming_thermalization", "=", "params", ".", "get", "(", "'programming_thermalization'", ",", "properties", "[", "'default_programming_thermalization'", "]", ")", "return", "min", "(", "properties", "[", "'num_reads_range'", "]", "[", "1", "]", ",", "int", "(", "(", "duration", "-", "programming_thermalization", ")", "/", "(", "annealing_time", "+", "readout_thermalization", ")", ")", ")" ]
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 - num_reads - programming_thermalization Returns: int: The maximum number of reads.
[ "Returns", "the", "maximum", "number", "of", "reads", "for", "the", "given", "solver", "parameters", "." ]
df3221a8385dc0c04d7b4d84f740bf3ad6706230
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/solver.py#L227-L267
train
dwavesystems/dwave-cloud-client
dwave/cloud/solver.py
Solver.sample_ising
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 method, specified per solver. Returns: :obj:`Future` Examples: This example creates a client using the local system's default D-Wave Cloud Client configuration file, which is configured to access a D-Wave 2000Q QPU, submits a simple :term:`Ising` problem (opposite linear biases on two coupled qubits), and samples 5 times. >>> from dwave.cloud import Client >>> with Client.from_config() as client: ... solver = client.get_solver() ... u, v = next(iter(solver.edges)) ... computation = solver.sample_ising({u: -1, v: 1},{}, num_reads=5) # doctest: +SKIP ... for i in range(5): ... print(computation.samples[i][u], computation.samples[i][v]) ... ... (1, -1) (1, -1) (1, -1) (1, -1) (1, -1) """ # Our linear and quadratic objective terms are already separated in an # ising model so we can just directly call `_sample`. return self._sample('ising', linear, quadratic, params)
python
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 method, specified per solver. Returns: :obj:`Future` Examples: This example creates a client using the local system's default D-Wave Cloud Client configuration file, which is configured to access a D-Wave 2000Q QPU, submits a simple :term:`Ising` problem (opposite linear biases on two coupled qubits), and samples 5 times. >>> from dwave.cloud import Client >>> with Client.from_config() as client: ... solver = client.get_solver() ... u, v = next(iter(solver.edges)) ... computation = solver.sample_ising({u: -1, v: 1},{}, num_reads=5) # doctest: +SKIP ... for i in range(5): ... print(computation.samples[i][u], computation.samples[i][v]) ... ... (1, -1) (1, -1) (1, -1) (1, -1) (1, -1) """ # Our linear and quadratic objective terms are already separated in an # ising model so we can just directly call `_sample`. return self._sample('ising', linear, quadratic, params)
[ "def", "sample_ising", "(", "self", ",", "linear", ",", "quadratic", ",", "*", "*", "params", ")", ":", "# Our linear and quadratic objective terms are already separated in an", "# ising model so we can just directly call `_sample`.", "return", "self", ".", "_sample", "(", "'ising'", ",", "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 method, specified per solver. Returns: :obj:`Future` Examples: This example creates a client using the local system's default D-Wave Cloud Client configuration file, which is configured to access a D-Wave 2000Q QPU, submits a simple :term:`Ising` problem (opposite linear biases on two coupled qubits), and samples 5 times. >>> from dwave.cloud import Client >>> with Client.from_config() as client: ... solver = client.get_solver() ... u, v = next(iter(solver.edges)) ... computation = solver.sample_ising({u: -1, v: 1},{}, num_reads=5) # doctest: +SKIP ... for i in range(5): ... print(computation.samples[i][u], computation.samples[i][v]) ... ... (1, -1) (1, -1) (1, -1) (1, -1) (1, -1)
[ "Sample", "from", "the", "specified", "Ising", "model", "." ]
df3221a8385dc0c04d7b4d84f740bf3ad6706230
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/solver.py#L271-L306
train
dwavesystems/dwave-cloud-client
dwave/cloud/solver.py
Solver.sample_qubo
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. Returns: :obj:`Future` Examples: This example creates a client using the local system's default D-Wave Cloud Client configuration file, which is configured to access a D-Wave 2000Q QPU, submits a :term:`QUBO` problem (a Boolean NOT gate represented by a penalty model), and samples 5 times. >>> from dwave.cloud import Client >>> with Client.from_config() as client: # doctest: +SKIP ... solver = client.get_solver() ... u, v = next(iter(solver.edges)) ... Q = {(u, u): -1, (u, v): 0, (v, u): 2, (v, v): -1} ... computation = solver.sample_qubo(Q, num_reads=5) ... for i in range(5): ... print(computation.samples[i][u], computation.samples[i][v]) ... ... (0, 1) (1, 0) (1, 0) (0, 1) (1, 0) """ # In a QUBO the linear and quadratic terms in the objective are mixed into # a matrix. For the sake of encoding, we will separate them before calling `_sample` linear = {i1: v for (i1, i2), v in uniform_iterator(qubo) if i1 == i2} quadratic = {(i1, i2): v for (i1, i2), v in uniform_iterator(qubo) if i1 != i2} return self._sample('qubo', linear, quadratic, params)
python
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. Returns: :obj:`Future` Examples: This example creates a client using the local system's default D-Wave Cloud Client configuration file, which is configured to access a D-Wave 2000Q QPU, submits a :term:`QUBO` problem (a Boolean NOT gate represented by a penalty model), and samples 5 times. >>> from dwave.cloud import Client >>> with Client.from_config() as client: # doctest: +SKIP ... solver = client.get_solver() ... u, v = next(iter(solver.edges)) ... Q = {(u, u): -1, (u, v): 0, (v, u): 2, (v, v): -1} ... computation = solver.sample_qubo(Q, num_reads=5) ... for i in range(5): ... print(computation.samples[i][u], computation.samples[i][v]) ... ... (0, 1) (1, 0) (1, 0) (0, 1) (1, 0) """ # In a QUBO the linear and quadratic terms in the objective are mixed into # a matrix. For the sake of encoding, we will separate them before calling `_sample` linear = {i1: v for (i1, i2), v in uniform_iterator(qubo) if i1 == i2} quadratic = {(i1, i2): v for (i1, i2), v in uniform_iterator(qubo) if i1 != i2} return self._sample('qubo', linear, quadratic, params)
[ "def", "sample_qubo", "(", "self", ",", "qubo", ",", "*", "*", "params", ")", ":", "# In a QUBO the linear and quadratic terms in the objective are mixed into", "# a matrix. For the sake of encoding, we will separate them before calling `_sample`", "linear", "=", "{", "i1", ":", "v", "for", "(", "i1", ",", "i2", ")", ",", "v", "in", "uniform_iterator", "(", "qubo", ")", "if", "i1", "==", "i2", "}", "quadratic", "=", "{", "(", "i1", ",", "i2", ")", ":", "v", "for", "(", "i1", ",", "i2", ")", ",", "v", "in", "uniform_iterator", "(", "qubo", ")", "if", "i1", "!=", "i2", "}", "return", "self", ".", "_sample", "(", "'qubo'", ",", "linear", ",", "quadratic", ",", "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. Returns: :obj:`Future` Examples: This example creates a client using the local system's default D-Wave Cloud Client configuration file, which is configured to access a D-Wave 2000Q QPU, submits a :term:`QUBO` problem (a Boolean NOT gate represented by a penalty model), and samples 5 times. >>> from dwave.cloud import Client >>> with Client.from_config() as client: # doctest: +SKIP ... solver = client.get_solver() ... u, v = next(iter(solver.edges)) ... Q = {(u, u): -1, (u, v): 0, (v, u): 2, (v, v): -1} ... computation = solver.sample_qubo(Q, num_reads=5) ... for i in range(5): ... print(computation.samples[i][u], computation.samples[i][v]) ... ... (0, 1) (1, 0) (1, 0) (0, 1) (1, 0)
[ "Sample", "from", "the", "specified", "QUBO", "." ]
df3221a8385dc0c04d7b4d84f740bf3ad6706230
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/solver.py#L308-L346
train
dwavesystems/dwave-cloud-client
dwave/cloud/solver.py
Solver._sample
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 sampling method, specified per solver. Returns: :obj: `Future` """ # Check the problem if not self.check_problem(linear, quadratic): raise ValueError("Problem graph incompatible with solver.") # Mix the new parameters with the default parameters combined_params = dict(self._params) combined_params.update(params) # Check the parameters before submitting for key in combined_params: if key not in self.parameters and not key.startswith('x_'): raise KeyError("{} is not a parameter of this solver.".format(key)) # transform some of the parameters in-place self._format_params(type_, combined_params) body = json.dumps({ 'solver': self.id, 'data': encode_bqm_as_qp(self, linear, quadratic), 'type': type_, 'params': combined_params }) _LOGGER.trace("Encoded sample request: %s", body) future = Future(solver=self, id_=None, return_matrix=self.return_matrix, submission_data=(type_, linear, quadratic, params)) _LOGGER.debug("Submitting new problem to: %s", self.id) self.client._submit(body, future) return future
python
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 sampling method, specified per solver. Returns: :obj: `Future` """ # Check the problem if not self.check_problem(linear, quadratic): raise ValueError("Problem graph incompatible with solver.") # Mix the new parameters with the default parameters combined_params = dict(self._params) combined_params.update(params) # Check the parameters before submitting for key in combined_params: if key not in self.parameters and not key.startswith('x_'): raise KeyError("{} is not a parameter of this solver.".format(key)) # transform some of the parameters in-place self._format_params(type_, combined_params) body = json.dumps({ 'solver': self.id, 'data': encode_bqm_as_qp(self, linear, quadratic), 'type': type_, 'params': combined_params }) _LOGGER.trace("Encoded sample request: %s", body) future = Future(solver=self, id_=None, return_matrix=self.return_matrix, submission_data=(type_, linear, quadratic, params)) _LOGGER.debug("Submitting new problem to: %s", self.id) self.client._submit(body, future) return future
[ "def", "_sample", "(", "self", ",", "type_", ",", "linear", ",", "quadratic", ",", "params", ")", ":", "# Check the problem", "if", "not", "self", ".", "check_problem", "(", "linear", ",", "quadratic", ")", ":", "raise", "ValueError", "(", "\"Problem graph incompatible with solver.\"", ")", "# Mix the new parameters with the default parameters", "combined_params", "=", "dict", "(", "self", ".", "_params", ")", "combined_params", ".", "update", "(", "params", ")", "# Check the parameters before submitting", "for", "key", "in", "combined_params", ":", "if", "key", "not", "in", "self", ".", "parameters", "and", "not", "key", ".", "startswith", "(", "'x_'", ")", ":", "raise", "KeyError", "(", "\"{} is not a parameter of this solver.\"", ".", "format", "(", "key", ")", ")", "# transform some of the parameters in-place", "self", ".", "_format_params", "(", "type_", ",", "combined_params", ")", "body", "=", "json", ".", "dumps", "(", "{", "'solver'", ":", "self", ".", "id", ",", "'data'", ":", "encode_bqm_as_qp", "(", "self", ",", "linear", ",", "quadratic", ")", ",", "'type'", ":", "type_", ",", "'params'", ":", "combined_params", "}", ")", "_LOGGER", ".", "trace", "(", "\"Encoded sample request: %s\"", ",", "body", ")", "future", "=", "Future", "(", "solver", "=", "self", ",", "id_", "=", "None", ",", "return_matrix", "=", "self", ".", "return_matrix", ",", "submission_data", "=", "(", "type_", ",", "linear", ",", "quadratic", ",", "params", ")", ")", "_LOGGER", ".", "debug", "(", "\"Submitting new problem to: %s\"", ",", "self", ".", "id", ")", "self", ".", "client", ".", "_submit", "(", "body", ",", "future", ")", "return", "future" ]
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 sampling method, specified per solver. Returns: :obj: `Future`
[ "Internal", "method", "for", "both", "sample_ising", "and", "sample_qubo", "." ]
df3221a8385dc0c04d7b4d84f740bf3ad6706230
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/solver.py#L348-L388
train
dwavesystems/dwave-cloud-client
dwave/cloud/solver.py
Solver._format_params
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 check here # that they match because lin can be either a list or a dict. In the future it would be # good to check. initial_state = params['initial_state'] if isinstance(initial_state, Mapping): initial_state_list = [3]*self.properties['num_qubits'] low = -1 if type_ == 'ising' else 0 for v, val in initial_state.items(): if val == 3: continue if val <= 0: initial_state_list[v] = low else: initial_state_list[v] = 1 params['initial_state'] = initial_state_list
python
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 check here # that they match because lin can be either a list or a dict. In the future it would be # good to check. initial_state = params['initial_state'] if isinstance(initial_state, Mapping): initial_state_list = [3]*self.properties['num_qubits'] low = -1 if type_ == 'ising' else 0 for v, val in initial_state.items(): if val == 3: continue if val <= 0: initial_state_list[v] = low else: initial_state_list[v] = 1 params['initial_state'] = initial_state_list
[ "def", "_format_params", "(", "self", ",", "type_", ",", "params", ")", ":", "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 check here", "# that they match because lin can be either a list or a dict. In the future it would be", "# good to check.", "initial_state", "=", "params", "[", "'initial_state'", "]", "if", "isinstance", "(", "initial_state", ",", "Mapping", ")", ":", "initial_state_list", "=", "[", "3", "]", "*", "self", ".", "properties", "[", "'num_qubits'", "]", "low", "=", "-", "1", "if", "type_", "==", "'ising'", "else", "0", "for", "v", ",", "val", "in", "initial_state", ".", "items", "(", ")", ":", "if", "val", "==", "3", ":", "continue", "if", "val", "<=", "0", ":", "initial_state_list", "[", "v", "]", "=", "low", "else", ":", "initial_state_list", "[", "v", "]", "=", "1", "params", "[", "'initial_state'", "]", "=", "initial_state_list" ]
Reformat some of the parameters for sapi.
[ "Reformat", "some", "of", "the", "parameters", "for", "sapi", "." ]
df3221a8385dc0c04d7b4d84f740bf3ad6706230
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/solver.py#L390-L412
train
dwavesystems/dwave-cloud-client
dwave/cloud/solver.py
Solver.check_problem
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 Examples: This example creates a client using the local system's default D-Wave Cloud Client configuration file, which is configured to access a D-Wave 2000Q QPU, and tests a simple :term:`Ising` model for two target embeddings (that is, representations of the model's graph by coupled qubits on the QPU's sparsely connected graph), where only the second is valid. >>> from dwave.cloud import Client >>> print((0, 1) in solver.edges) # doctest: +SKIP False >>> print((0, 4) in solver.edges) # doctest: +SKIP True >>> with Client.from_config() as client: # doctest: +SKIP ... solver = client.get_solver() ... print(solver.check_problem({0: -1, 1: 1},{(0, 1):0.5})) ... print(solver.check_problem({0: -1, 4: 1},{(0, 4):0.5})) ... False True """ for key, value in uniform_iterator(linear): if value != 0 and key not in self.nodes: return False for key, value in uniform_iterator(quadratic): if value != 0 and tuple(key) not in self.edges: return False return True
python
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 Examples: This example creates a client using the local system's default D-Wave Cloud Client configuration file, which is configured to access a D-Wave 2000Q QPU, and tests a simple :term:`Ising` model for two target embeddings (that is, representations of the model's graph by coupled qubits on the QPU's sparsely connected graph), where only the second is valid. >>> from dwave.cloud import Client >>> print((0, 1) in solver.edges) # doctest: +SKIP False >>> print((0, 4) in solver.edges) # doctest: +SKIP True >>> with Client.from_config() as client: # doctest: +SKIP ... solver = client.get_solver() ... print(solver.check_problem({0: -1, 1: 1},{(0, 1):0.5})) ... print(solver.check_problem({0: -1, 4: 1},{(0, 4):0.5})) ... False True """ for key, value in uniform_iterator(linear): if value != 0 and key not in self.nodes: return False for key, value in uniform_iterator(quadratic): if value != 0 and tuple(key) not in self.edges: return False return True
[ "def", "check_problem", "(", "self", ",", "linear", ",", "quadratic", ")", ":", "for", "key", ",", "value", "in", "uniform_iterator", "(", "linear", ")", ":", "if", "value", "!=", "0", "and", "key", "not", "in", "self", ".", "nodes", ":", "return", "False", "for", "key", ",", "value", "in", "uniform_iterator", "(", "quadratic", ")", ":", "if", "value", "!=", "0", "and", "tuple", "(", "key", ")", "not", "in", "self", ".", "edges", ":", "return", "False", "return", "True" ]
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 Examples: This example creates a client using the local system's default D-Wave Cloud Client configuration file, which is configured to access a D-Wave 2000Q QPU, and tests a simple :term:`Ising` model for two target embeddings (that is, representations of the model's graph by coupled qubits on the QPU's sparsely connected graph), where only the second is valid. >>> from dwave.cloud import Client >>> print((0, 1) in solver.edges) # doctest: +SKIP False >>> print((0, 4) in solver.edges) # doctest: +SKIP True >>> with Client.from_config() as client: # doctest: +SKIP ... solver = client.get_solver() ... print(solver.check_problem({0: -1, 1: 1},{(0, 1):0.5})) ... print(solver.check_problem({0: -1, 4: 1},{(0, 4):0.5})) ... False True
[ "Test", "if", "an", "Ising", "model", "matches", "the", "graph", "provided", "by", "the", "solver", "." ]
df3221a8385dc0c04d7b4d84f740bf3ad6706230
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/solver.py#L415-L451
train
dwavesystems/dwave-cloud-client
dwave/cloud/solver.py
Solver._retrieve_problem
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) return future
python
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) return future
[ "def", "_retrieve_problem", "(", "self", ",", "id_", ")", ":", "future", "=", "Future", "(", "self", ",", "id_", ",", "self", ".", "return_matrix", ",", "None", ")", "self", ".", "client", ".", "_poll", "(", "future", ")", "return", "future" ]
Resume polling for a problem previously submitted. Args: id_: Identification of the query. Returns: :obj: `Future`
[ "Resume", "polling", "for", "a", "problem", "previously", "submitted", "." ]
df3221a8385dc0c04d7b4d84f740bf3ad6706230
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/solver.py#L453-L464
train
tuxu/python-samplerate
samplerate/converters.py
_get_converter_type
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)
python
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", "_get_converter_type", "(", "identifier", ")", ":", "if", "isinstance", "(", "identifier", ",", "str", ")", ":", "return", "ConverterType", "[", "identifier", "]", "if", "isinstance", "(", "identifier", ",", "ConverterType", ")", ":", "return", "identifier", "return", "ConverterType", "(", "identifier", ")" ]
Return the converter type for `identifier`.
[ "Return", "the", "converter", "type", "for", "identifier", "." ]
ed73d7a39e61bfb34b03dade14ffab59aa27922a
https://github.com/tuxu/python-samplerate/blob/ed73d7a39e61bfb34b03dade14ffab59aa27922a/samplerate/converters.py#L22-L28
train
tuxu/python-samplerate
samplerate/converters.py
resample
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 represented as a 2D array of shape (`num_frames`, `num_channels`). For use with `libsamplerate`, `input_data` is converted to 32-bit float and C (row-major) memory order. ratio : float Conversion ratio = output sample rate / input sample rate. converter_type : ConverterType, str, or int Sample rate converter. verbose : bool If `True`, print additional information about the conversion. Returns ------- output_data : ndarray Resampled input data. Note ---- If samples are to be processed in chunks, `Resampler` and `CallbackResampler` will provide better results and allow for variable conversion ratios. """ from samplerate.lowlevel import src_simple from samplerate.exceptions import ResamplingError input_data = np.require(input_data, requirements='C', dtype=np.float32) if input_data.ndim == 2: num_frames, channels = input_data.shape output_shape = (int(num_frames * ratio), channels) elif input_data.ndim == 1: num_frames, channels = input_data.size, 1 output_shape = (int(num_frames * ratio), ) else: raise ValueError('rank > 2 not supported') output_data = np.empty(output_shape, dtype=np.float32) converter_type = _get_converter_type(converter_type) (error, input_frames_used, output_frames_gen) \ = src_simple(input_data, output_data, ratio, converter_type.value, channels) if error != 0: raise ResamplingError(error) if verbose: info = ('samplerate info:\n' '{} input frames used\n' '{} output frames generated\n' .format(input_frames_used, output_frames_gen)) print(info) return (output_data[:output_frames_gen, :] if channels > 1 else output_data[:output_frames_gen])
python
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 represented as a 2D array of shape (`num_frames`, `num_channels`). For use with `libsamplerate`, `input_data` is converted to 32-bit float and C (row-major) memory order. ratio : float Conversion ratio = output sample rate / input sample rate. converter_type : ConverterType, str, or int Sample rate converter. verbose : bool If `True`, print additional information about the conversion. Returns ------- output_data : ndarray Resampled input data. Note ---- If samples are to be processed in chunks, `Resampler` and `CallbackResampler` will provide better results and allow for variable conversion ratios. """ from samplerate.lowlevel import src_simple from samplerate.exceptions import ResamplingError input_data = np.require(input_data, requirements='C', dtype=np.float32) if input_data.ndim == 2: num_frames, channels = input_data.shape output_shape = (int(num_frames * ratio), channels) elif input_data.ndim == 1: num_frames, channels = input_data.size, 1 output_shape = (int(num_frames * ratio), ) else: raise ValueError('rank > 2 not supported') output_data = np.empty(output_shape, dtype=np.float32) converter_type = _get_converter_type(converter_type) (error, input_frames_used, output_frames_gen) \ = src_simple(input_data, output_data, ratio, converter_type.value, channels) if error != 0: raise ResamplingError(error) if verbose: info = ('samplerate info:\n' '{} input frames used\n' '{} output frames generated\n' .format(input_frames_used, output_frames_gen)) print(info) return (output_data[:output_frames_gen, :] if channels > 1 else output_data[:output_frames_gen])
[ "def", "resample", "(", "input_data", ",", "ratio", ",", "converter_type", "=", "'sinc_best'", ",", "verbose", "=", "False", ")", ":", "from", "samplerate", ".", "lowlevel", "import", "src_simple", "from", "samplerate", ".", "exceptions", "import", "ResamplingError", "input_data", "=", "np", ".", "require", "(", "input_data", ",", "requirements", "=", "'C'", ",", "dtype", "=", "np", ".", "float32", ")", "if", "input_data", ".", "ndim", "==", "2", ":", "num_frames", ",", "channels", "=", "input_data", ".", "shape", "output_shape", "=", "(", "int", "(", "num_frames", "*", "ratio", ")", ",", "channels", ")", "elif", "input_data", ".", "ndim", "==", "1", ":", "num_frames", ",", "channels", "=", "input_data", ".", "size", ",", "1", "output_shape", "=", "(", "int", "(", "num_frames", "*", "ratio", ")", ",", ")", "else", ":", "raise", "ValueError", "(", "'rank > 2 not supported'", ")", "output_data", "=", "np", ".", "empty", "(", "output_shape", ",", "dtype", "=", "np", ".", "float32", ")", "converter_type", "=", "_get_converter_type", "(", "converter_type", ")", "(", "error", ",", "input_frames_used", ",", "output_frames_gen", ")", "=", "src_simple", "(", "input_data", ",", "output_data", ",", "ratio", ",", "converter_type", ".", "value", ",", "channels", ")", "if", "error", "!=", "0", ":", "raise", "ResamplingError", "(", "error", ")", "if", "verbose", ":", "info", "=", "(", "'samplerate info:\\n'", "'{} input frames used\\n'", "'{} output frames generated\\n'", ".", "format", "(", "input_frames_used", ",", "output_frames_gen", ")", ")", "print", "(", "info", ")", "return", "(", "output_data", "[", ":", "output_frames_gen", ",", ":", "]", "if", "channels", ">", "1", "else", "output_data", "[", ":", "output_frames_gen", "]", ")" ]
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 represented as a 2D array of shape (`num_frames`, `num_channels`). For use with `libsamplerate`, `input_data` is converted to 32-bit float and C (row-major) memory order. ratio : float Conversion ratio = output sample rate / input sample rate. converter_type : ConverterType, str, or int Sample rate converter. verbose : bool If `True`, print additional information about the conversion. Returns ------- output_data : ndarray Resampled input data. Note ---- If samples are to be processed in chunks, `Resampler` and `CallbackResampler` will provide better results and allow for variable conversion ratios.
[ "Resample", "the", "signal", "in", "input_data", "at", "once", "." ]
ed73d7a39e61bfb34b03dade14ffab59aa27922a
https://github.com/tuxu/python-samplerate/blob/ed73d7a39e61bfb34b03dade14ffab59aa27922a/samplerate/converters.py#L31-L90
train
tuxu/python-samplerate
samplerate/converters.py
Resampler.set_ratio
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)
python
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", "set_ratio", "(", "self", ",", "new_ratio", ")", ":", "from", "samplerate", ".", "lowlevel", "import", "src_set_ratio", "return", "src_set_ratio", "(", "self", ".", "_state", ",", "new_ratio", ")" ]
Set a new conversion ratio immediately.
[ "Set", "a", "new", "conversion", "ratio", "immediately", "." ]
ed73d7a39e61bfb34b03dade14ffab59aa27922a
https://github.com/tuxu/python-samplerate/blob/ed73d7a39e61bfb34b03dade14ffab59aa27922a/samplerate/converters.py#L130-L133
train
tuxu/python-samplerate
samplerate/converters.py
Resampler.process
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 channels is represented as a 2D array of shape (`num_frames`, `num_channels`). For use with `libsamplerate`, `input_data` is converted to 32-bit float and C (row-major) memory order. ratio : float Conversion ratio = output sample rate / input sample rate. end_of_input : int Set to `True` if no more data is available, or to `False` otherwise. verbose : bool If `True`, print additional information about the conversion. Returns ------- output_data : ndarray Resampled input data. """ from samplerate.lowlevel import src_process from samplerate.exceptions import ResamplingError input_data = np.require(input_data, requirements='C', dtype=np.float32) if input_data.ndim == 2: num_frames, channels = input_data.shape output_shape = (int(num_frames * ratio), channels) elif input_data.ndim == 1: num_frames, channels = input_data.size, 1 output_shape = (int(num_frames * ratio), ) else: raise ValueError('rank > 2 not supported') if channels != self._channels: raise ValueError('Invalid number of channels in input data.') output_data = np.empty(output_shape, dtype=np.float32) (error, input_frames_used, output_frames_gen) = src_process( self._state, input_data, output_data, ratio, end_of_input) if error != 0: raise ResamplingError(error) if verbose: info = ('samplerate info:\n' '{} input frames used\n' '{} output frames generated\n' .format(input_frames_used, output_frames_gen)) print(info) return (output_data[:output_frames_gen, :] if channels > 1 else output_data[:output_frames_gen])
python
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 channels is represented as a 2D array of shape (`num_frames`, `num_channels`). For use with `libsamplerate`, `input_data` is converted to 32-bit float and C (row-major) memory order. ratio : float Conversion ratio = output sample rate / input sample rate. end_of_input : int Set to `True` if no more data is available, or to `False` otherwise. verbose : bool If `True`, print additional information about the conversion. Returns ------- output_data : ndarray Resampled input data. """ from samplerate.lowlevel import src_process from samplerate.exceptions import ResamplingError input_data = np.require(input_data, requirements='C', dtype=np.float32) if input_data.ndim == 2: num_frames, channels = input_data.shape output_shape = (int(num_frames * ratio), channels) elif input_data.ndim == 1: num_frames, channels = input_data.size, 1 output_shape = (int(num_frames * ratio), ) else: raise ValueError('rank > 2 not supported') if channels != self._channels: raise ValueError('Invalid number of channels in input data.') output_data = np.empty(output_shape, dtype=np.float32) (error, input_frames_used, output_frames_gen) = src_process( self._state, input_data, output_data, ratio, end_of_input) if error != 0: raise ResamplingError(error) if verbose: info = ('samplerate info:\n' '{} input frames used\n' '{} output frames generated\n' .format(input_frames_used, output_frames_gen)) print(info) return (output_data[:output_frames_gen, :] if channels > 1 else output_data[:output_frames_gen])
[ "def", "process", "(", "self", ",", "input_data", ",", "ratio", ",", "end_of_input", "=", "False", ",", "verbose", "=", "False", ")", ":", "from", "samplerate", ".", "lowlevel", "import", "src_process", "from", "samplerate", ".", "exceptions", "import", "ResamplingError", "input_data", "=", "np", ".", "require", "(", "input_data", ",", "requirements", "=", "'C'", ",", "dtype", "=", "np", ".", "float32", ")", "if", "input_data", ".", "ndim", "==", "2", ":", "num_frames", ",", "channels", "=", "input_data", ".", "shape", "output_shape", "=", "(", "int", "(", "num_frames", "*", "ratio", ")", ",", "channels", ")", "elif", "input_data", ".", "ndim", "==", "1", ":", "num_frames", ",", "channels", "=", "input_data", ".", "size", ",", "1", "output_shape", "=", "(", "int", "(", "num_frames", "*", "ratio", ")", ",", ")", "else", ":", "raise", "ValueError", "(", "'rank > 2 not supported'", ")", "if", "channels", "!=", "self", ".", "_channels", ":", "raise", "ValueError", "(", "'Invalid number of channels in input data.'", ")", "output_data", "=", "np", ".", "empty", "(", "output_shape", ",", "dtype", "=", "np", ".", "float32", ")", "(", "error", ",", "input_frames_used", ",", "output_frames_gen", ")", "=", "src_process", "(", "self", ".", "_state", ",", "input_data", ",", "output_data", ",", "ratio", ",", "end_of_input", ")", "if", "error", "!=", "0", ":", "raise", "ResamplingError", "(", "error", ")", "if", "verbose", ":", "info", "=", "(", "'samplerate info:\\n'", "'{} input frames used\\n'", "'{} output frames generated\\n'", ".", "format", "(", "input_frames_used", ",", "output_frames_gen", ")", ")", "print", "(", "info", ")", "return", "(", "output_data", "[", ":", "output_frames_gen", ",", ":", "]", "if", "channels", ">", "1", "else", "output_data", "[", ":", "output_frames_gen", "]", ")" ]
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 channels is represented as a 2D array of shape (`num_frames`, `num_channels`). For use with `libsamplerate`, `input_data` is converted to 32-bit float and C (row-major) memory order. ratio : float Conversion ratio = output sample rate / input sample rate. end_of_input : int Set to `True` if no more data is available, or to `False` otherwise. verbose : bool If `True`, print additional information about the conversion. Returns ------- output_data : ndarray Resampled input data.
[ "Resample", "the", "signal", "in", "input_data", "." ]
ed73d7a39e61bfb34b03dade14ffab59aa27922a
https://github.com/tuxu/python-samplerate/blob/ed73d7a39e61bfb34b03dade14ffab59aa27922a/samplerate/converters.py#L135-L189
train
tuxu/python-samplerate
samplerate/converters.py
CallbackResampler._create
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) if error != 0: raise ResamplingError(error) self._state = ffi.gc(state, src_delete) self._handle = handle
python
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) if error != 0: raise ResamplingError(error) self._state = ffi.gc(state, src_delete) self._handle = handle
[ "def", "_create", "(", "self", ")", ":", "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", ")", "if", "error", "!=", "0", ":", "raise", "ResamplingError", "(", "error", ")", "self", ".", "_state", "=", "ffi", ".", "gc", "(", "state", ",", "src_delete", ")", "self", ".", "_handle", "=", "handle" ]
Create new callback resampler.
[ "Create", "new", "callback", "resampler", "." ]
ed73d7a39e61bfb34b03dade14ffab59aa27922a
https://github.com/tuxu/python-samplerate/blob/ed73d7a39e61bfb34b03dade14ffab59aa27922a/samplerate/converters.py#L222-L232
train
tuxu/python-samplerate
samplerate/converters.py
CallbackResampler.set_starting_ratio
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
python
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", "set_starting_ratio", "(", "self", ",", "ratio", ")", ":", "from", "samplerate", ".", "lowlevel", "import", "src_set_ratio", "if", "self", ".", "_state", "is", "None", ":", "self", ".", "_create", "(", ")", "src_set_ratio", "(", "self", ".", "_state", ",", "ratio", ")", "self", ".", "ratio", "=", "ratio" ]
Set the starting conversion ratio for the next `read` call.
[ "Set", "the", "starting", "conversion", "ratio", "for", "the", "next", "read", "call", "." ]
ed73d7a39e61bfb34b03dade14ffab59aa27922a
https://github.com/tuxu/python-samplerate/blob/ed73d7a39e61bfb34b03dade14ffab59aa27922a/samplerate/converters.py#L246-L252
train
tuxu/python-samplerate
samplerate/converters.py
CallbackResampler.reset
def reset(self): """Reset state.""" from samplerate.lowlevel import src_reset if self._state is None: self._create() src_reset(self._state)
python
def reset(self): """Reset state.""" from samplerate.lowlevel import src_reset if self._state is None: self._create() src_reset(self._state)
[ "def", "reset", "(", "self", ")", ":", "from", "samplerate", ".", "lowlevel", "import", "src_reset", "if", "self", ".", "_state", "is", "None", ":", "self", ".", "_create", "(", ")", "src_reset", "(", "self", ".", "_state", ")" ]
Reset state.
[ "Reset", "state", "." ]
ed73d7a39e61bfb34b03dade14ffab59aa27922a
https://github.com/tuxu/python-samplerate/blob/ed73d7a39e61bfb34b03dade14ffab59aa27922a/samplerate/converters.py#L254-L259
train
tuxu/python-samplerate
samplerate/converters.py
CallbackResampler.read
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`) or (`num_output_frames`,) array. Note that this may return fewer frames than requested, for example when no more input is available. """ from samplerate.lowlevel import src_callback_read, src_error from samplerate.exceptions import ResamplingError if self._state is None: self._create() if self._channels > 1: output_shape = (num_frames, self._channels) elif self._channels == 1: output_shape = (num_frames, ) output_data = np.empty(output_shape, dtype=np.float32) ret = src_callback_read(self._state, self._ratio, num_frames, output_data) if ret == 0: error = src_error(self._state) if error: raise ResamplingError(error) return (output_data[:ret, :] if self._channels > 1 else output_data[:ret])
python
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`) or (`num_output_frames`,) array. Note that this may return fewer frames than requested, for example when no more input is available. """ from samplerate.lowlevel import src_callback_read, src_error from samplerate.exceptions import ResamplingError if self._state is None: self._create() if self._channels > 1: output_shape = (num_frames, self._channels) elif self._channels == 1: output_shape = (num_frames, ) output_data = np.empty(output_shape, dtype=np.float32) ret = src_callback_read(self._state, self._ratio, num_frames, output_data) if ret == 0: error = src_error(self._state) if error: raise ResamplingError(error) return (output_data[:ret, :] if self._channels > 1 else output_data[:ret])
[ "def", "read", "(", "self", ",", "num_frames", ")", ":", "from", "samplerate", ".", "lowlevel", "import", "src_callback_read", ",", "src_error", "from", "samplerate", ".", "exceptions", "import", "ResamplingError", "if", "self", ".", "_state", "is", "None", ":", "self", ".", "_create", "(", ")", "if", "self", ".", "_channels", ">", "1", ":", "output_shape", "=", "(", "num_frames", ",", "self", ".", "_channels", ")", "elif", "self", ".", "_channels", "==", "1", ":", "output_shape", "=", "(", "num_frames", ",", ")", "output_data", "=", "np", ".", "empty", "(", "output_shape", ",", "dtype", "=", "np", ".", "float32", ")", "ret", "=", "src_callback_read", "(", "self", ".", "_state", ",", "self", ".", "_ratio", ",", "num_frames", ",", "output_data", ")", "if", "ret", "==", "0", ":", "error", "=", "src_error", "(", "self", ".", "_state", ")", "if", "error", ":", "raise", "ResamplingError", "(", "error", ")", "return", "(", "output_data", "[", ":", "ret", ",", ":", "]", "if", "self", ".", "_channels", ">", "1", "else", "output_data", "[", ":", "ret", "]", ")" ]
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`) or (`num_output_frames`,) array. Note that this may return fewer frames than requested, for example when no more input is available.
[ "Read", "a", "number", "of", "frames", "from", "the", "resampler", "." ]
ed73d7a39e61bfb34b03dade14ffab59aa27922a
https://github.com/tuxu/python-samplerate/blob/ed73d7a39e61bfb34b03dade14ffab59aa27922a/samplerate/converters.py#L270-L304
train
chrisspen/dtree
dtree.py
get_variance
def get_variance(seq): """ Batch variance calculation. """ m = get_mean(seq) return sum((v-m)**2 for v in seq)/float(len(seq))
python
def get_variance(seq): """ Batch variance calculation. """ m = get_mean(seq) return sum((v-m)**2 for v in seq)/float(len(seq))
[ "def", "get_variance", "(", "seq", ")", ":", "m", "=", "get_mean", "(", "seq", ")", "return", "sum", "(", "(", "v", "-", "m", ")", "**", "2", "for", "v", "in", "seq", ")", "/", "float", "(", "len", "(", "seq", ")", ")" ]
Batch variance calculation.
[ "Batch", "variance", "calculation", "." ]
9e9c9992b22ad9a7e296af7e6837666b05db43ef
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L91-L96
train
chrisspen/dtree
dtree.py
mean_absolute_error
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))
python
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", "mean_absolute_error", "(", "seq", ",", "correct", ")", ":", "assert", "len", "(", "seq", ")", "==", "len", "(", "correct", ")", "diffs", "=", "[", "abs", "(", "a", "-", "b", ")", "for", "a", ",", "b", "in", "zip", "(", "seq", ",", "correct", ")", "]", "return", "sum", "(", "diffs", ")", "/", "float", "(", "len", "(", "diffs", ")", ")" ]
Batch mean absolute error calculation.
[ "Batch", "mean", "absolute", "error", "calculation", "." ]
9e9c9992b22ad9a7e296af7e6837666b05db43ef
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L101-L107
train
chrisspen/dtree
dtree.py
normalize
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]
python
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", "normalize", "(", "seq", ")", ":", "s", "=", "float", "(", "sum", "(", "seq", ")", ")", "return", "[", "v", "/", "s", "for", "v", "in", "seq", "]" ]
Scales each number in the sequence so that the sum of all numbers equals 1.
[ "Scales", "each", "number", "in", "the", "sequence", "so", "that", "the", "sum", "of", "all", "numbers", "equals", "1", "." ]
9e9c9992b22ad9a7e296af7e6837666b05db43ef
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L109-L114
train
chrisspen/dtree
dtree.py
normcdf
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 = 0.5*erfcc(-t/(sigma*math.sqrt(2.0))) if y > 1.0: y = 1.0 return y
python
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 = 0.5*erfcc(-t/(sigma*math.sqrt(2.0))) if y > 1.0: y = 1.0 return y
[ "def", "normcdf", "(", "x", ",", "mu", ",", "sigma", ")", ":", "t", "=", "x", "-", "mu", "y", "=", "0.5", "*", "erfcc", "(", "-", "t", "/", "(", "sigma", "*", "math", ".", "sqrt", "(", "2.0", ")", ")", ")", "if", "y", ">", "1.0", ":", "y", "=", "1.0", "return", "y" ]
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
[ "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" ]
9e9c9992b22ad9a7e296af7e6837666b05db43ef
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L131-L143
train
chrisspen/dtree
dtree.py
normpdf
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
python
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", "normpdf", "(", "x", ",", "mu", ",", "sigma", ")", ":", "u", "=", "(", "x", "-", "mu", ")", "/", "abs", "(", "sigma", ")", "y", "=", "(", "1", "/", "(", "math", ".", "sqrt", "(", "2", "*", "pi", ")", "*", "abs", "(", "sigma", ")", ")", ")", "*", "math", ".", "exp", "(", "-", "u", "*", "u", "/", "2", ")", "return", "y" ]
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
[ "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" ]
9e9c9992b22ad9a7e296af7e6837666b05db43ef
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L145-L154
train
chrisspen/dtree
dtree.py
entropy
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 value counts will be generated attr<string> := the name of the class attribute """ assert (class_attr is None and isinstance(data, dict)) \ or (class_attr is not None and isinstance(data, list)) if isinstance(data, dict): counts = data else: counts = defaultdict(float) # {attr:count} for record in data: # Note: A missing attribute is treated like an attribute with a value # of None, representing the attribute is "irrelevant". counts[record.get(class_attr)] += 1.0 len_data = float(sum(cnt for _, cnt in iteritems(counts))) n = max(2, len(counts)) total = float(sum(counts.values())) assert total, "There must be at least one non-zero count." try: #return -sum((count/total)*math.log(count/total,n) for count in counts) if method == ENTROPY1: return -sum((count/len_data)*math.log(count/len_data, n) for count in itervalues(counts) if count) elif method == ENTROPY2: return -sum((count/len_data)*math.log(count/len_data, n) for count in itervalues(counts) if count) - ((len(counts)-1)/float(total)) elif method == ENTROPY3: return -sum((count/len_data)*math.log(count/len_data, n) for count in itervalues(counts) if count) - 100*((len(counts)-1)/float(total)) else: raise Exception("Unknown entropy method %s." % method) except Exception: raise
python
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 value counts will be generated attr<string> := the name of the class attribute """ assert (class_attr is None and isinstance(data, dict)) \ or (class_attr is not None and isinstance(data, list)) if isinstance(data, dict): counts = data else: counts = defaultdict(float) # {attr:count} for record in data: # Note: A missing attribute is treated like an attribute with a value # of None, representing the attribute is "irrelevant". counts[record.get(class_attr)] += 1.0 len_data = float(sum(cnt for _, cnt in iteritems(counts))) n = max(2, len(counts)) total = float(sum(counts.values())) assert total, "There must be at least one non-zero count." try: #return -sum((count/total)*math.log(count/total,n) for count in counts) if method == ENTROPY1: return -sum((count/len_data)*math.log(count/len_data, n) for count in itervalues(counts) if count) elif method == ENTROPY2: return -sum((count/len_data)*math.log(count/len_data, n) for count in itervalues(counts) if count) - ((len(counts)-1)/float(total)) elif method == ENTROPY3: return -sum((count/len_data)*math.log(count/len_data, n) for count in itervalues(counts) if count) - 100*((len(counts)-1)/float(total)) else: raise Exception("Unknown entropy method %s." % method) except Exception: raise
[ "def", "entropy", "(", "data", ",", "class_attr", "=", "None", ",", "method", "=", "DEFAULT_DISCRETE_METRIC", ")", ":", "assert", "(", "class_attr", "is", "None", "and", "isinstance", "(", "data", ",", "dict", ")", ")", "or", "(", "class_attr", "is", "not", "None", "and", "isinstance", "(", "data", ",", "list", ")", ")", "if", "isinstance", "(", "data", ",", "dict", ")", ":", "counts", "=", "data", "else", ":", "counts", "=", "defaultdict", "(", "float", ")", "# {attr:count}", "for", "record", "in", "data", ":", "# Note: A missing attribute is treated like an attribute with a value", "# of None, representing the attribute is \"irrelevant\".", "counts", "[", "record", ".", "get", "(", "class_attr", ")", "]", "+=", "1.0", "len_data", "=", "float", "(", "sum", "(", "cnt", "for", "_", ",", "cnt", "in", "iteritems", "(", "counts", ")", ")", ")", "n", "=", "max", "(", "2", ",", "len", "(", "counts", ")", ")", "total", "=", "float", "(", "sum", "(", "counts", ".", "values", "(", ")", ")", ")", "assert", "total", ",", "\"There must be at least one non-zero count.\"", "try", ":", "#return -sum((count/total)*math.log(count/total,n) for count in counts)", "if", "method", "==", "ENTROPY1", ":", "return", "-", "sum", "(", "(", "count", "/", "len_data", ")", "*", "math", ".", "log", "(", "count", "/", "len_data", ",", "n", ")", "for", "count", "in", "itervalues", "(", "counts", ")", "if", "count", ")", "elif", "method", "==", "ENTROPY2", ":", "return", "-", "sum", "(", "(", "count", "/", "len_data", ")", "*", "math", ".", "log", "(", "count", "/", "len_data", ",", "n", ")", "for", "count", "in", "itervalues", "(", "counts", ")", "if", "count", ")", "-", "(", "(", "len", "(", "counts", ")", "-", "1", ")", "/", "float", "(", "total", ")", ")", "elif", "method", "==", "ENTROPY3", ":", "return", "-", "sum", "(", "(", "count", "/", "len_data", ")", "*", "math", ".", "log", "(", "count", "/", "len_data", ",", "n", ")", "for", "count", "in", "itervalues", "(", "counts", ")", "if", "count", ")", "-", "100", "*", "(", "(", "len", "(", "counts", ")", "-", "1", ")", "/", "float", "(", "total", ")", ")", "else", ":", "raise", "Exception", "(", "\"Unknown entropy method %s.\"", "%", "method", ")", "except", "Exception", ":", "raise" ]
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 value counts will be generated attr<string> := the name of the class attribute
[ "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", "value", "counts", "will", "be", "generated", "attr<string", ">", ":", "=", "the", "name", "of", "the", "class", "attribute" ]
9e9c9992b22ad9a7e296af7e6837666b05db43ef
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L374-L412
train
chrisspen/dtree
dtree.py
entropy_variance
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 and isinstance(data, dict)) \ or (class_attr is not None and isinstance(data, list)) if isinstance(data, dict): lst = data else: lst = [record.get(class_attr) for record in data] return get_variance(lst)
python
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 and isinstance(data, dict)) \ or (class_attr is not None and isinstance(data, list)) if isinstance(data, dict): lst = data else: lst = [record.get(class_attr) for record in data] return get_variance(lst)
[ "def", "entropy_variance", "(", "data", ",", "class_attr", "=", "None", ",", "method", "=", "DEFAULT_CONTINUOUS_METRIC", ")", ":", "assert", "method", "in", "CONTINUOUS_METRICS", ",", "\"Unknown entropy variance metric: %s\"", "%", "(", "method", ",", ")", "assert", "(", "class_attr", "is", "None", "and", "isinstance", "(", "data", ",", "dict", ")", ")", "or", "(", "class_attr", "is", "not", "None", "and", "isinstance", "(", "data", ",", "list", ")", ")", "if", "isinstance", "(", "data", ",", "dict", ")", ":", "lst", "=", "data", "else", ":", "lst", "=", "[", "record", ".", "get", "(", "class_attr", ")", "for", "record", "in", "data", "]", "return", "get_variance", "(", "lst", ")" ]
Calculates the variance fo a continuous class attribute, to be used as an entropy metric.
[ "Calculates", "the", "variance", "fo", "a", "continuous", "class", "attribute", "to", "be", "used", "as", "an", "entropy", "metric", "." ]
9e9c9992b22ad9a7e296af7e6837666b05db43ef
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L414-L427
train
chrisspen/dtree
dtree.py
get_gain
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_fewer_values := Weights the gain by the count of the attribute's unique values. If multiple attributes have the same gain, but one has slightly fewer attributes, this will cause the one with fewer attributes to be preferred. """ entropy_func = entropy_func or entropy val_freq = defaultdict(float) subset_entropy = 0.0 # Calculate the frequency of each of the values in the target attribute for record in data: val_freq[record.get(attr)] += 1.0 # Calculate the sum of the entropy for each subset of records weighted # by their probability of occuring in the training set. for val in val_freq.keys(): val_prob = val_freq[val] / sum(val_freq.values()) data_subset = [record for record in data if record.get(attr) == val] e = entropy_func(data_subset, class_attr, method=method) subset_entropy += val_prob * e if only_sub: return subset_entropy # Subtract the entropy of the chosen attribute from the entropy of the # whole data set with respect to the target attribute (and return it) main_entropy = entropy_func(data, class_attr, method=method) # Prefer gains on attributes with fewer values. if prefer_fewer_values: # n = len(val_freq) # w = (n+1)/float(n)/2 #return (main_entropy - subset_entropy)*w return ((main_entropy - subset_entropy), 1./len(val_freq)) else: return (main_entropy - subset_entropy)
python
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_fewer_values := Weights the gain by the count of the attribute's unique values. If multiple attributes have the same gain, but one has slightly fewer attributes, this will cause the one with fewer attributes to be preferred. """ entropy_func = entropy_func or entropy val_freq = defaultdict(float) subset_entropy = 0.0 # Calculate the frequency of each of the values in the target attribute for record in data: val_freq[record.get(attr)] += 1.0 # Calculate the sum of the entropy for each subset of records weighted # by their probability of occuring in the training set. for val in val_freq.keys(): val_prob = val_freq[val] / sum(val_freq.values()) data_subset = [record for record in data if record.get(attr) == val] e = entropy_func(data_subset, class_attr, method=method) subset_entropy += val_prob * e if only_sub: return subset_entropy # Subtract the entropy of the chosen attribute from the entropy of the # whole data set with respect to the target attribute (and return it) main_entropy = entropy_func(data, class_attr, method=method) # Prefer gains on attributes with fewer values. if prefer_fewer_values: # n = len(val_freq) # w = (n+1)/float(n)/2 #return (main_entropy - subset_entropy)*w return ((main_entropy - subset_entropy), 1./len(val_freq)) else: return (main_entropy - subset_entropy)
[ "def", "get_gain", "(", "data", ",", "attr", ",", "class_attr", ",", "method", "=", "DEFAULT_DISCRETE_METRIC", ",", "only_sub", "=", "0", ",", "prefer_fewer_values", "=", "False", ",", "entropy_func", "=", "None", ")", ":", "entropy_func", "=", "entropy_func", "or", "entropy", "val_freq", "=", "defaultdict", "(", "float", ")", "subset_entropy", "=", "0.0", "# Calculate the frequency of each of the values in the target attribute", "for", "record", "in", "data", ":", "val_freq", "[", "record", ".", "get", "(", "attr", ")", "]", "+=", "1.0", "# Calculate the sum of the entropy for each subset of records weighted", "# by their probability of occuring in the training set.", "for", "val", "in", "val_freq", ".", "keys", "(", ")", ":", "val_prob", "=", "val_freq", "[", "val", "]", "/", "sum", "(", "val_freq", ".", "values", "(", ")", ")", "data_subset", "=", "[", "record", "for", "record", "in", "data", "if", "record", ".", "get", "(", "attr", ")", "==", "val", "]", "e", "=", "entropy_func", "(", "data_subset", ",", "class_attr", ",", "method", "=", "method", ")", "subset_entropy", "+=", "val_prob", "*", "e", "if", "only_sub", ":", "return", "subset_entropy", "# Subtract the entropy of the chosen attribute from the entropy of the", "# whole data set with respect to the target attribute (and return it)", "main_entropy", "=", "entropy_func", "(", "data", ",", "class_attr", ",", "method", "=", "method", ")", "# Prefer gains on attributes with fewer values.", "if", "prefer_fewer_values", ":", "# n = len(val_freq)", "# w = (n+1)/float(n)/2", "#return (main_entropy - subset_entropy)*w", "return", "(", "(", "main_entropy", "-", "subset_entropy", ")", ",", "1.", "/", "len", "(", "val_freq", ")", ")", "else", ":", "return", "(", "main_entropy", "-", "subset_entropy", ")" ]
Calculates the information gain (reduction in entropy) that would result by splitting the data on the chosen attribute (attr). Parameters: prefer_fewer_values := Weights the gain by the count of the attribute's unique values. If multiple attributes have the same gain, but one has slightly fewer attributes, this will cause the one with fewer attributes to be preferred.
[ "Calculates", "the", "information", "gain", "(", "reduction", "in", "entropy", ")", "that", "would", "result", "by", "splitting", "the", "data", "on", "the", "chosen", "attribute", "(", "attr", ")", ".", "Parameters", ":", "prefer_fewer_values", ":", "=", "Weights", "the", "gain", "by", "the", "count", "of", "the", "attribute", "s", "unique", "values", ".", "If", "multiple", "attributes", "have", "the", "same", "gain", "but", "one", "has", "slightly", "fewer", "attributes", "this", "will", "cause", "the", "one", "with", "fewer", "attributes", "to", "be", "preferred", "." ]
9e9c9992b22ad9a7e296af7e6837666b05db43ef
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L429-L473
train
chrisspen/dtree
dtree.py
majority_value
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 record in data]) else: return most_frequent([record[class_attr] for record in data])
python
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 record in data]) else: return most_frequent([record[class_attr] for record in data])
[ "def", "majority_value", "(", "data", ",", "class_attr", ")", ":", "if", "is_continuous", "(", "data", "[", "0", "]", "[", "class_attr", "]", ")", ":", "return", "CDist", "(", "seq", "=", "[", "record", "[", "class_attr", "]", "for", "record", "in", "data", "]", ")", "else", ":", "return", "most_frequent", "(", "[", "record", "[", "class_attr", "]", "for", "record", "in", "data", "]", ")" ]
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.
[ "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", "." ]
9e9c9992b22ad9a7e296af7e6837666b05db43ef
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L481-L490
train
chrisspen/dtree
dtree.py
most_frequent
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) return most_freq
python
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) return most_freq
[ "def", "most_frequent", "(", "lst", ")", ":", "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", ")", "return", "most_freq" ]
Returns the item that appears most frequently in the given list.
[ "Returns", "the", "item", "that", "appears", "most", "frequently", "in", "the", "given", "list", "." ]
9e9c9992b22ad9a7e296af7e6837666b05db43ef
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L492-L505
train
chrisspen/dtree
dtree.py
unique
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) <= 0: unique_lst.append(item) # Return the list with all redundant values removed. return unique_lst
python
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) <= 0: unique_lst.append(item) # Return the list with all redundant values removed. return unique_lst
[ "def", "unique", "(", "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", ")", "<=", "0", ":", "unique_lst", ".", "append", "(", "item", ")", "# Return the list with all redundant values removed.", "return", "unique_lst" ]
Returns a list made up of the unique values found in lst. i.e., it removes the redundant values in lst.
[ "Returns", "a", "list", "made", "up", "of", "the", "unique", "values", "found", "in", "lst", ".", "i", ".", "e", ".", "it", "removes", "the", "redundant", "values", "in", "lst", "." ]
9e9c9992b22ad9a7e296af7e6837666b05db43ef
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L507-L521
train
chrisspen/dtree
dtree.py
choose_attribute
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 gain = fitness(data, attr, class_attr, method=method) best = max(best, (gain, attr)) return best[1]
python
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 gain = fitness(data, attr, class_attr, method=method) best = max(best, (gain, attr)) return best[1]
[ "def", "choose_attribute", "(", "data", ",", "attributes", ",", "class_attr", ",", "fitness", ",", "method", ")", ":", "best", "=", "(", "-", "1e999999", ",", "None", ")", "for", "attr", "in", "attributes", ":", "if", "attr", "==", "class_attr", ":", "continue", "gain", "=", "fitness", "(", "data", ",", "attr", ",", "class_attr", ",", "method", "=", "method", ")", "best", "=", "max", "(", "best", ",", "(", "gain", ",", "attr", ")", ")", "return", "best", "[", "1", "]" ]
Cycles through all the attributes and returns the attribute with the highest information gain (or lowest entropy).
[ "Cycles", "through", "all", "the", "attributes", "and", "returns", "the", "attribute", "with", "the", "highest", "information", "gain", "(", "or", "lowest", "entropy", ")", "." ]
9e9c9992b22ad9a7e296af7e6837666b05db43ef
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L530-L541
train
chrisspen/dtree
dtree.py
create_decision_tree
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 = None data = list(data) if isinstance(data, Data) else data if wrapper.is_continuous_class: stop_value = CDist(seq=[r[class_attr] for r in data]) # For a continuous class case, stop if all the remaining records have # a variance below the given threshold. stop = wrapper.leaf_threshold is not None \ and stop_value.variance <= wrapper.leaf_threshold else: stop_value = DDist(seq=[r[class_attr] for r in data]) # For a discrete class, stop if all remaining records have the same # classification. stop = len(stop_value.counts) <= 1 if not data or len(attributes) <= 0: # If the dataset is empty or the attributes list is empty, return the # default value. The target attribute is not in the attributes list, so # we need not subtract 1 to account for the target attribute. if wrapper: wrapper.leaf_count += 1 return stop_value elif stop: # If all the records in the dataset have the same classification, # return that classification. if wrapper: wrapper.leaf_count += 1 return stop_value else: # Choose the next best attribute to best classify our data best = choose_attribute( data, attributes, class_attr, fitness_func, method=wrapper.metric) # Create a new decision tree/node with the best attribute and an empty # dictionary object--we'll fill that up next. # tree = {best:{}} node = Node(tree=wrapper, attr_name=best) node.n += len(data) # Create a new decision tree/sub-node for each of the values in the # best attribute field for val in get_values(data, best): # Create a subtree for the current value under the "best" field subtree = create_decision_tree( [r for r in data if r[best] == val], [attr for attr in attributes if attr != best], class_attr, fitness_func, split_attr=best, split_val=val, wrapper=wrapper) # Add the new subtree to the empty dictionary object in our new # tree/node we just created. if isinstance(subtree, Node): node._branches[val] = subtree elif isinstance(subtree, (CDist, DDist)): node.set_leaf_dist(attr_value=val, dist=subtree) else: raise Exception("Unknown subtree type: %s" % (type(subtree),)) return node
python
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 = None data = list(data) if isinstance(data, Data) else data if wrapper.is_continuous_class: stop_value = CDist(seq=[r[class_attr] for r in data]) # For a continuous class case, stop if all the remaining records have # a variance below the given threshold. stop = wrapper.leaf_threshold is not None \ and stop_value.variance <= wrapper.leaf_threshold else: stop_value = DDist(seq=[r[class_attr] for r in data]) # For a discrete class, stop if all remaining records have the same # classification. stop = len(stop_value.counts) <= 1 if not data or len(attributes) <= 0: # If the dataset is empty or the attributes list is empty, return the # default value. The target attribute is not in the attributes list, so # we need not subtract 1 to account for the target attribute. if wrapper: wrapper.leaf_count += 1 return stop_value elif stop: # If all the records in the dataset have the same classification, # return that classification. if wrapper: wrapper.leaf_count += 1 return stop_value else: # Choose the next best attribute to best classify our data best = choose_attribute( data, attributes, class_attr, fitness_func, method=wrapper.metric) # Create a new decision tree/node with the best attribute and an empty # dictionary object--we'll fill that up next. # tree = {best:{}} node = Node(tree=wrapper, attr_name=best) node.n += len(data) # Create a new decision tree/sub-node for each of the values in the # best attribute field for val in get_values(data, best): # Create a subtree for the current value under the "best" field subtree = create_decision_tree( [r for r in data if r[best] == val], [attr for attr in attributes if attr != best], class_attr, fitness_func, split_attr=best, split_val=val, wrapper=wrapper) # Add the new subtree to the empty dictionary object in our new # tree/node we just created. if isinstance(subtree, Node): node._branches[val] = subtree elif isinstance(subtree, (CDist, DDist)): node.set_leaf_dist(attr_value=val, dist=subtree) else: raise Exception("Unknown subtree type: %s" % (type(subtree),)) return node
[ "def", "create_decision_tree", "(", "data", ",", "attributes", ",", "class_attr", ",", "fitness_func", ",", "wrapper", ",", "*", "*", "kwargs", ")", ":", "split_attr", "=", "kwargs", ".", "get", "(", "'split_attr'", ",", "None", ")", "split_val", "=", "kwargs", ".", "get", "(", "'split_val'", ",", "None", ")", "assert", "class_attr", "not", "in", "attributes", "node", "=", "None", "data", "=", "list", "(", "data", ")", "if", "isinstance", "(", "data", ",", "Data", ")", "else", "data", "if", "wrapper", ".", "is_continuous_class", ":", "stop_value", "=", "CDist", "(", "seq", "=", "[", "r", "[", "class_attr", "]", "for", "r", "in", "data", "]", ")", "# For a continuous class case, stop if all the remaining records have", "# a variance below the given threshold.", "stop", "=", "wrapper", ".", "leaf_threshold", "is", "not", "None", "and", "stop_value", ".", "variance", "<=", "wrapper", ".", "leaf_threshold", "else", ":", "stop_value", "=", "DDist", "(", "seq", "=", "[", "r", "[", "class_attr", "]", "for", "r", "in", "data", "]", ")", "# For a discrete class, stop if all remaining records have the same", "# classification.", "stop", "=", "len", "(", "stop_value", ".", "counts", ")", "<=", "1", "if", "not", "data", "or", "len", "(", "attributes", ")", "<=", "0", ":", "# If the dataset is empty or the attributes list is empty, return the", "# default value. The target attribute is not in the attributes list, so", "# we need not subtract 1 to account for the target attribute.", "if", "wrapper", ":", "wrapper", ".", "leaf_count", "+=", "1", "return", "stop_value", "elif", "stop", ":", "# If all the records in the dataset have the same classification,", "# return that classification.", "if", "wrapper", ":", "wrapper", ".", "leaf_count", "+=", "1", "return", "stop_value", "else", ":", "# Choose the next best attribute to best classify our data", "best", "=", "choose_attribute", "(", "data", ",", "attributes", ",", "class_attr", ",", "fitness_func", ",", "method", "=", "wrapper", ".", "metric", ")", "# Create a new decision tree/node with the best attribute and an empty", "# dictionary object--we'll fill that up next.", "# tree = {best:{}}", "node", "=", "Node", "(", "tree", "=", "wrapper", ",", "attr_name", "=", "best", ")", "node", ".", "n", "+=", "len", "(", "data", ")", "# Create a new decision tree/sub-node for each of the values in the", "# best attribute field", "for", "val", "in", "get_values", "(", "data", ",", "best", ")", ":", "# Create a subtree for the current value under the \"best\" field", "subtree", "=", "create_decision_tree", "(", "[", "r", "for", "r", "in", "data", "if", "r", "[", "best", "]", "==", "val", "]", ",", "[", "attr", "for", "attr", "in", "attributes", "if", "attr", "!=", "best", "]", ",", "class_attr", ",", "fitness_func", ",", "split_attr", "=", "best", ",", "split_val", "=", "val", ",", "wrapper", "=", "wrapper", ")", "# Add the new subtree to the empty dictionary object in our new", "# tree/node we just created.", "if", "isinstance", "(", "subtree", ",", "Node", ")", ":", "node", ".", "_branches", "[", "val", "]", "=", "subtree", "elif", "isinstance", "(", "subtree", ",", "(", "CDist", ",", "DDist", ")", ")", ":", "node", ".", "set_leaf_dist", "(", "attr_value", "=", "val", ",", "dist", "=", "subtree", ")", "else", ":", "raise", "Exception", "(", "\"Unknown subtree type: %s\"", "%", "(", "type", "(", "subtree", ")", ",", ")", ")", "return", "node" ]
Returns a new decision tree based on the examples given.
[ "Returns", "a", "new", "decision", "tree", "based", "on", "the", "examples", "given", "." ]
9e9c9992b22ad9a7e296af7e6837666b05db43ef
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L546-L619
train
chrisspen/dtree
dtree.py
DDist.add
def add(self, k, count=1): """ Increments the count for the given element. """ self.counts[k] += count self.total += count
python
def add(self, k, count=1): """ Increments the count for the given element. """ self.counts[k] += count self.total += count
[ "def", "add", "(", "self", ",", "k", ",", "count", "=", "1", ")", ":", "self", ".", "counts", "[", "k", "]", "+=", "count", "self", ".", "total", "+=", "count" ]
Increments the count for the given element.
[ "Increments", "the", "count", "for", "the", "given", "element", "." ]
9e9c9992b22ad9a7e296af7e6837666b05db43ef
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L215-L220
train
chrisspen/dtree
dtree.py
DDist.best
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]
python
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", "best", "(", "self", ")", ":", "b", "=", "(", "-", "1e999999", ",", "None", ")", "for", "k", ",", "c", "in", "iteritems", "(", "self", ".", "counts", ")", ":", "b", "=", "max", "(", "b", ",", "(", "c", ",", "k", ")", ")", "return", "b", "[", "1", "]" ]
Returns the element with the highest probability.
[ "Returns", "the", "element", "with", "the", "highest", "probability", "." ]
9e9c9992b22ad9a7e296af7e6837666b05db43ef
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L223-L230
train
chrisspen/dtree
dtree.py
DDist.probs
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) ]
python
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", "probs", "(", "self", ")", ":", "return", "[", "(", "k", ",", "self", ".", "counts", "[", "k", "]", "/", "float", "(", "self", ".", "total", ")", ")", "for", "k", "in", "iterkeys", "(", "self", ".", "counts", ")", "]" ]
Returns a list of probabilities for all elements in the form [(value1,prob1),(value2,prob2),...].
[ "Returns", "a", "list", "of", "probabilities", "for", "all", "elements", "in", "the", "form", "[", "(", "value1", "prob1", ")", "(", "value2", "prob2", ")", "...", "]", "." ]
9e9c9992b22ad9a7e296af7e6837666b05db43ef
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L260-L268
train
chrisspen/dtree
dtree.py
DDist.update
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
python
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", "update", "(", "self", ",", "dist", ")", ":", "assert", "isinstance", "(", "dist", ",", "DDist", ")", "for", "k", ",", "c", "in", "iteritems", "(", "dist", ".", "counts", ")", ":", "self", ".", "counts", "[", "k", "]", "+=", "c", "self", ".", "total", "+=", "dist", ".", "total" ]
Adds the given distribution's counts to the current distribution.
[ "Adds", "the", "given", "distribution", "s", "counts", "to", "the", "current", "distribution", "." ]
9e9c9992b22ad9a7e296af7e6837666b05db43ef
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L270-L277
train
chrisspen/dtree
dtree.py
CDist.probability_lt
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)
python
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_lt", "(", "self", ",", "x", ")", ":", "if", "self", ".", "mean", "is", "None", ":", "return", "return", "normdist", "(", "x", "=", "x", ",", "mu", "=", "self", ".", "mean", ",", "sigma", "=", "self", ".", "standard_deviation", ")" ]
Returns the probability of a random variable being less than the given value.
[ "Returns", "the", "probability", "of", "a", "random", "variable", "being", "less", "than", "the", "given", "value", "." ]
9e9c9992b22ad9a7e296af7e6837666b05db43ef
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L344-L351
train
chrisspen/dtree
dtree.py
CDist.probability_in
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=self.standard_deviation) return abs(p1 - p2)
python
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=self.standard_deviation) return abs(p1 - p2)
[ "def", "probability_in", "(", "self", ",", "a", ",", "b", ")", ":", "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", "=", "self", ".", "standard_deviation", ")", "return", "abs", "(", "p1", "-", "p2", ")" ]
Returns the probability of a random variable falling between the given values.
[ "Returns", "the", "probability", "of", "a", "random", "variable", "falling", "between", "the", "given", "values", "." ]
9e9c9992b22ad9a7e296af7e6837666b05db43ef
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L353-L362
train
chrisspen/dtree
dtree.py
CDist.probability_gt
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
python
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", "probability_gt", "(", "self", ",", "x", ")", ":", "if", "self", ".", "mean", "is", "None", ":", "return", "p", "=", "normdist", "(", "x", "=", "x", ",", "mu", "=", "self", ".", "mean", ",", "sigma", "=", "self", ".", "standard_deviation", ")", "return", "1", "-", "p" ]
Returns the probability of a random variable being greater than the given value.
[ "Returns", "the", "probability", "of", "a", "random", "variable", "being", "greater", "than", "the", "given", "value", "." ]
9e9c9992b22ad9a7e296af7e6837666b05db43ef
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L364-L372
train
chrisspen/dtree
dtree.py
Data.copy_no_data
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())
python
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", "copy_no_data", "(", "self", ")", ":", "return", "type", "(", "self", ")", "(", "[", "]", ",", "order", "=", "list", "(", "self", ".", "header_modes", ")", ",", "types", "=", "self", ".", "header_types", ".", "copy", "(", ")", ",", "modes", "=", "self", ".", "header_modes", ".", "copy", "(", ")", ")" ]
Returns a copy of the object without any data.
[ "Returns", "a", "copy", "of", "the", "object", "without", "any", "data", "." ]
9e9c9992b22ad9a7e296af7e6837666b05db43ef
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L667-L675
train
chrisspen/dtree
dtree.py
Data.is_valid
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 == ATTR_TYPE_DISCRETE: return isinstance(value, int) elif t == ATTR_TYPE_CONTINUOUS: return isinstance(value, (float, Decimal)) return True
python
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 == ATTR_TYPE_DISCRETE: return isinstance(value, int) elif t == ATTR_TYPE_CONTINUOUS: return isinstance(value, (float, Decimal)) return True
[ "def", "is_valid", "(", "self", ",", "name", ",", "value", ")", ":", "if", "name", "not", "in", "self", ".", "header_types", ":", "return", "False", "t", "=", "self", ".", "header_types", "[", "name", "]", "if", "t", "==", "ATTR_TYPE_DISCRETE", ":", "return", "isinstance", "(", "value", ",", "int", ")", "elif", "t", "==", "ATTR_TYPE_CONTINUOUS", ":", "return", "isinstance", "(", "value", ",", "(", "float", ",", "Decimal", ")", ")", "return", "True" ]
Returns true if the given value matches the type for the given name according to the schema. Returns false otherwise.
[ "Returns", "true", "if", "the", "given", "value", "matches", "the", "type", "for", "the", "given", "name", "according", "to", "the", "schema", ".", "Returns", "false", "otherwise", "." ]
9e9c9992b22ad9a7e296af7e6837666b05db43ef
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L710-L723
train
chrisspen/dtree
dtree.py
Data._read_header
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(open(self.filename)) #header = rows.next() header = next(rows) self.header_types = {} # {attr_name:type} self._class_attr_name = None self.header_order = [] # [attr_name,...] for el in header: matches = ATTR_HEADER_PATTERN.findall(el) assert matches, "Invalid header element: %s" % (el,) el_name, el_type, el_mode = matches[0] el_name = el_name.strip() self.header_order.append(el_name) self.header_types[el_name] = el_type if el_mode == ATTR_MODE_CLASS: assert self._class_attr_name is None, \ "Multiple class attributes are not supported." self._class_attr_name = el_name else: assert self.header_types[el_name] != ATTR_TYPE_CONTINUOUS, \ "Non-class continuous attributes are not supported." assert self._class_attr_name, "A class attribute must be specified."
python
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(open(self.filename)) #header = rows.next() header = next(rows) self.header_types = {} # {attr_name:type} self._class_attr_name = None self.header_order = [] # [attr_name,...] for el in header: matches = ATTR_HEADER_PATTERN.findall(el) assert matches, "Invalid header element: %s" % (el,) el_name, el_type, el_mode = matches[0] el_name = el_name.strip() self.header_order.append(el_name) self.header_types[el_name] = el_type if el_mode == ATTR_MODE_CLASS: assert self._class_attr_name is None, \ "Multiple class attributes are not supported." self._class_attr_name = el_name else: assert self.header_types[el_name] != ATTR_TYPE_CONTINUOUS, \ "Non-class continuous attributes are not supported." assert self._class_attr_name, "A class attribute must be specified."
[ "def", "_read_header", "(", "self", ")", ":", "if", "not", "self", ".", "filename", "or", "self", ".", "header_types", ":", "return", "rows", "=", "csv", ".", "reader", "(", "open", "(", "self", ".", "filename", ")", ")", "#header = rows.next()", "header", "=", "next", "(", "rows", ")", "self", ".", "header_types", "=", "{", "}", "# {attr_name:type}", "self", ".", "_class_attr_name", "=", "None", "self", ".", "header_order", "=", "[", "]", "# [attr_name,...]", "for", "el", "in", "header", ":", "matches", "=", "ATTR_HEADER_PATTERN", ".", "findall", "(", "el", ")", "assert", "matches", ",", "\"Invalid header element: %s\"", "%", "(", "el", ",", ")", "el_name", ",", "el_type", ",", "el_mode", "=", "matches", "[", "0", "]", "el_name", "=", "el_name", ".", "strip", "(", ")", "self", ".", "header_order", ".", "append", "(", "el_name", ")", "self", ".", "header_types", "[", "el_name", "]", "=", "el_type", "if", "el_mode", "==", "ATTR_MODE_CLASS", ":", "assert", "self", ".", "_class_attr_name", "is", "None", ",", "\"Multiple class attributes are not supported.\"", "self", ".", "_class_attr_name", "=", "el_name", "else", ":", "assert", "self", ".", "header_types", "[", "el_name", "]", "!=", "ATTR_TYPE_CONTINUOUS", ",", "\"Non-class continuous attributes are not supported.\"", "assert", "self", ".", "_class_attr_name", ",", "\"A class attribute must be specified.\"" ]
When a CSV file is given, extracts header information the file. Otherwise, this header data must be explicitly given when the object is instantiated.
[ "When", "a", "CSV", "file", "is", "given", "extracts", "header", "information", "the", "file", ".", "Otherwise", "this", "header", "data", "must", "be", "explicitly", "given", "when", "the", "object", "is", "instantiated", "." ]
9e9c9992b22ad9a7e296af7e6837666b05db43ef
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L725-L753
train
chrisspen/dtree
dtree.py
Data.validate_row
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), \ "Row length does not match header length." itr = zip(self.header_order, row) else: assert isinstance(row, dict) itr = iteritems(row) for el_name, el_value in itr: if self.header_types[el_name] == ATTR_TYPE_DISCRETE: clean_row[el_name] = int(el_value) elif self.header_types[el_name] == ATTR_TYPE_CONTINUOUS: clean_row[el_name] = float(el_value) else: clean_row[el_name] = el_value return clean_row
python
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), \ "Row length does not match header length." itr = zip(self.header_order, row) else: assert isinstance(row, dict) itr = iteritems(row) for el_name, el_value in itr: if self.header_types[el_name] == ATTR_TYPE_DISCRETE: clean_row[el_name] = int(el_value) elif self.header_types[el_name] == ATTR_TYPE_CONTINUOUS: clean_row[el_name] = float(el_value) else: clean_row[el_name] = el_value return clean_row
[ "def", "validate_row", "(", "self", ",", "row", ")", ":", "clean_row", "=", "{", "}", "if", "isinstance", "(", "row", ",", "(", "tuple", ",", "list", ")", ")", ":", "assert", "self", ".", "header_order", ",", "\"No attribute order specified.\"", "assert", "len", "(", "row", ")", "==", "len", "(", "self", ".", "header_order", ")", ",", "\"Row length does not match header length.\"", "itr", "=", "zip", "(", "self", ".", "header_order", ",", "row", ")", "else", ":", "assert", "isinstance", "(", "row", ",", "dict", ")", "itr", "=", "iteritems", "(", "row", ")", "for", "el_name", ",", "el_value", "in", "itr", ":", "if", "self", ".", "header_types", "[", "el_name", "]", "==", "ATTR_TYPE_DISCRETE", ":", "clean_row", "[", "el_name", "]", "=", "int", "(", "el_value", ")", "elif", "self", ".", "header_types", "[", "el_name", "]", "==", "ATTR_TYPE_CONTINUOUS", ":", "clean_row", "[", "el_name", "]", "=", "float", "(", "el_value", ")", "else", ":", "clean_row", "[", "el_name", "]", "=", "el_value", "return", "clean_row" ]
Ensure each element in the row matches the schema.
[ "Ensure", "each", "element", "in", "the", "row", "matches", "the", "schema", "." ]
9e9c9992b22ad9a7e296af7e6837666b05db43ef
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L755-L775
train
chrisspen/dtree
dtree.py
Data.split
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 ratio of data. If leave_one_out is True, the ratio will be ignored and the first instance will contain exactly one record for each class label, and the second instance will contain all remaining data. """ a_labels = set() a = self.copy_no_data() b = self.copy_no_data() for row in self: if leave_one_out and not self.is_continuous_class: label = row[self.class_attribute_name] if label not in a_labels: a_labels.add(label) a.data.append(row) else: b.data.append(row) elif not a: a.data.append(row) elif not b: b.data.append(row) elif random.random() <= ratio: a.data.append(row) else: b.data.append(row) return a, b
python
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 ratio of data. If leave_one_out is True, the ratio will be ignored and the first instance will contain exactly one record for each class label, and the second instance will contain all remaining data. """ a_labels = set() a = self.copy_no_data() b = self.copy_no_data() for row in self: if leave_one_out and not self.is_continuous_class: label = row[self.class_attribute_name] if label not in a_labels: a_labels.add(label) a.data.append(row) else: b.data.append(row) elif not a: a.data.append(row) elif not b: b.data.append(row) elif random.random() <= ratio: a.data.append(row) else: b.data.append(row) return a, b
[ "def", "split", "(", "self", ",", "ratio", "=", "0.5", ",", "leave_one_out", "=", "False", ")", ":", "a_labels", "=", "set", "(", ")", "a", "=", "self", ".", "copy_no_data", "(", ")", "b", "=", "self", ".", "copy_no_data", "(", ")", "for", "row", "in", "self", ":", "if", "leave_one_out", "and", "not", "self", ".", "is_continuous_class", ":", "label", "=", "row", "[", "self", ".", "class_attribute_name", "]", "if", "label", "not", "in", "a_labels", ":", "a_labels", ".", "add", "(", "label", ")", "a", ".", "data", ".", "append", "(", "row", ")", "else", ":", "b", ".", "data", ".", "append", "(", "row", ")", "elif", "not", "a", ":", "a", ".", "data", ".", "append", "(", "row", ")", "elif", "not", "b", ":", "b", ".", "data", ".", "append", "(", "row", ")", "elif", "random", ".", "random", "(", ")", "<=", "ratio", ":", "a", ".", "data", ".", "append", "(", "row", ")", "else", ":", "b", ".", "data", ".", "append", "(", "row", ")", "return", "a", ",", "b" ]
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 ratio of data. If leave_one_out is True, the ratio will be ignored and the first instance will contain exactly one record for each class label, and the second instance will contain all remaining data.
[ "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", "ratio", "of", "data", ".", "If", "leave_one_out", "is", "True", "the", "ratio", "will", "be", "ignored", "and", "the", "first", "instance", "will", "contain", "exactly", "one", "record", "for", "each", "class", "label", "and", "the", "second", "instance", "will", "contain", "all", "remaining", "data", "." ]
9e9c9992b22ad9a7e296af7e6837666b05db43ef
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L791-L822
train
chrisspen/dtree
dtree.py
Node._get_attribute_value_for_node
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 # Otherwise, lookup the attribute value for this node in the # given record. attr = self.attr_name attr_value = record[attr] attr_values = self.get_values(attr) if attr_value in attr_values: return attr_value else: # The value of the attribute in the given record does not directly # map to any previously known values, so apply a missing value # policy. policy = self.tree.missing_value_policy.get(attr) assert policy, \ ("No missing value policy specified for attribute %s.") \ % (attr,) if policy == USE_NEAREST: # Use the value that the tree has seen that's also has the # smallest Euclidean distance to the actual value. assert self.tree.data.header_types[attr] \ in (ATTR_TYPE_DISCRETE, ATTR_TYPE_CONTINUOUS), \ "The use-nearest policy is invalid for nominal types." nearest = (1e999999, None) for _value in attr_values: nearest = min( nearest, (abs(_value - attr_value), _value)) _, nearest_value = nearest return nearest_value else: raise Exception("Unknown missing value policy: %s" % (policy,))
python
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 # Otherwise, lookup the attribute value for this node in the # given record. attr = self.attr_name attr_value = record[attr] attr_values = self.get_values(attr) if attr_value in attr_values: return attr_value else: # The value of the attribute in the given record does not directly # map to any previously known values, so apply a missing value # policy. policy = self.tree.missing_value_policy.get(attr) assert policy, \ ("No missing value policy specified for attribute %s.") \ % (attr,) if policy == USE_NEAREST: # Use the value that the tree has seen that's also has the # smallest Euclidean distance to the actual value. assert self.tree.data.header_types[attr] \ in (ATTR_TYPE_DISCRETE, ATTR_TYPE_CONTINUOUS), \ "The use-nearest policy is invalid for nominal types." nearest = (1e999999, None) for _value in attr_values: nearest = min( nearest, (abs(_value - attr_value), _value)) _, nearest_value = nearest return nearest_value else: raise Exception("Unknown missing value policy: %s" % (policy,))
[ "def", "_get_attribute_value_for_node", "(", "self", ",", "record", ")", ":", "# Abort if this node has not get split on an attribute. ", "if", "self", ".", "attr_name", "is", "None", ":", "return", "# Otherwise, lookup the attribute value for this node in the", "# given record.", "attr", "=", "self", ".", "attr_name", "attr_value", "=", "record", "[", "attr", "]", "attr_values", "=", "self", ".", "get_values", "(", "attr", ")", "if", "attr_value", "in", "attr_values", ":", "return", "attr_value", "else", ":", "# The value of the attribute in the given record does not directly", "# map to any previously known values, so apply a missing value", "# policy.", "policy", "=", "self", ".", "tree", ".", "missing_value_policy", ".", "get", "(", "attr", ")", "assert", "policy", ",", "(", "\"No missing value policy specified for attribute %s.\"", ")", "%", "(", "attr", ",", ")", "if", "policy", "==", "USE_NEAREST", ":", "# Use the value that the tree has seen that's also has the", "# smallest Euclidean distance to the actual value.", "assert", "self", ".", "tree", ".", "data", ".", "header_types", "[", "attr", "]", "in", "(", "ATTR_TYPE_DISCRETE", ",", "ATTR_TYPE_CONTINUOUS", ")", ",", "\"The use-nearest policy is invalid for nominal types.\"", "nearest", "=", "(", "1e999999", ",", "None", ")", "for", "_value", "in", "attr_values", ":", "nearest", "=", "min", "(", "nearest", ",", "(", "abs", "(", "_value", "-", "attr_value", ")", ",", "_value", ")", ")", "_", ",", "nearest_value", "=", "nearest", "return", "nearest_value", "else", ":", "raise", "Exception", "(", "\"Unknown missing value policy: %s\"", "%", "(", "policy", ",", ")", ")" ]
Gets the closest value for the current node's attribute matching the given record.
[ "Gets", "the", "closest", "value", "for", "the", "current", "node", "s", "attribute", "matching", "the", "given", "record", "." ]
9e9c9992b22ad9a7e296af7e6837666b05db43ef
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L896-L935
train
chrisspen/dtree
dtree.py
Node.get_values
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()) ret = set(ret) return ret
python
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()) ret = set(ret) return ret
[ "def", "get_values", "(", "self", ",", "attr_name", ")", ":", "ret", "=", "list", "(", "self", ".", "_attr_value_cdist", "[", "attr_name", "]", ".", "keys", "(", ")", ")", "+", "list", "(", "self", ".", "_attr_value_counts", "[", "attr_name", "]", ".", "keys", "(", ")", ")", "+", "list", "(", "self", ".", "_branches", ".", "keys", "(", ")", ")", "ret", "=", "set", "(", "ret", ")", "return", "ret" ]
Retrieves the unique set of values seen for the given attribute at this node.
[ "Retrieves", "the", "unique", "set", "of", "values", "seen", "for", "the", "given", "attribute", "at", "this", "node", "." ]
9e9c9992b22ad9a7e296af7e6837666b05db43ef
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L941-L950
train
chrisspen/dtree
dtree.py
Node.get_best_splitting_attr
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
python
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_best_splitting_attr", "(", "self", ")", ":", "best", "=", "(", "-", "1e999999", ",", "None", ")", "for", "attr", "in", "self", ".", "attributes", ":", "best", "=", "max", "(", "best", ",", "(", "self", ".", "get_gain", "(", "attr", ")", ",", "attr", ")", ")", "best_gain", ",", "best_attr", "=", "best", "return", "best_attr" ]
Returns the name of the attribute with the highest gain.
[ "Returns", "the", "name", "of", "the", "attribute", "with", "the", "highest", "gain", "." ]
9e9c9992b22ad9a7e296af7e6837666b05db43ef
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L956-L964
train
chrisspen/dtree
dtree.py
Node.get_entropy
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. var = self._class_cdist.variance else: # Calculate variance of the given attribute. var = self._attr_value_cdist[attr_name][attr_value].variance if self.tree.metric == VARIANCE1 or attr_name is None: return var elif self.tree.metric == VARIANCE2: unique_value_count = len(self._attr_value_counts[attr_name]) attr_total = float(self._attr_value_count_totals[attr_name]) return var*(unique_value_count/attr_total) else: if attr_name is None: # The total number of times this attr/value pair has been seen. total = float(self._class_ddist.total) # The total number of times each class value has been seen for # this attr/value pair. counts = self._class_ddist.counts # The total number of unique values seen for this attribute. unique_value_count = len(self._class_ddist.counts) # The total number of times this attribute has been seen. attr_total = total else: total = float(self._attr_value_counts[attr_name][attr_value]) counts = self._attr_class_value_counts[attr_name][attr_value] unique_value_count = len(self._attr_value_counts[attr_name]) attr_total = float(self._attr_value_count_totals[attr_name]) assert total, "There must be at least one non-zero count." n = max(2, len(counts)) if self._tree.metric == ENTROPY1: # Traditional entropy. return -sum( (count/total)*math.log(count/total, n) for count in itervalues(counts) ) elif self._tree.metric == ENTROPY2: # Modified entropy that down-weights universally unique values. # e.g. If the number of unique attribute values equals the total # count of the attribute, then it has the maximum amount of unique # values. return -sum( (count/total)*math.log(count/total, n) for count in itervalues(counts) #) - ((len(counts)-1)/float(total)) ) + (unique_value_count/attr_total) elif self._tree.metric == ENTROPY3: # Modified entropy that down-weights universally unique values # as well as features with large numbers of values. return -sum( (count/total)*math.log(count/total, n) for count in itervalues(counts) #) - 100*((len(counts)-1)/float(total)) ) + 100*(unique_value_count/attr_total)
python
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. var = self._class_cdist.variance else: # Calculate variance of the given attribute. var = self._attr_value_cdist[attr_name][attr_value].variance if self.tree.metric == VARIANCE1 or attr_name is None: return var elif self.tree.metric == VARIANCE2: unique_value_count = len(self._attr_value_counts[attr_name]) attr_total = float(self._attr_value_count_totals[attr_name]) return var*(unique_value_count/attr_total) else: if attr_name is None: # The total number of times this attr/value pair has been seen. total = float(self._class_ddist.total) # The total number of times each class value has been seen for # this attr/value pair. counts = self._class_ddist.counts # The total number of unique values seen for this attribute. unique_value_count = len(self._class_ddist.counts) # The total number of times this attribute has been seen. attr_total = total else: total = float(self._attr_value_counts[attr_name][attr_value]) counts = self._attr_class_value_counts[attr_name][attr_value] unique_value_count = len(self._attr_value_counts[attr_name]) attr_total = float(self._attr_value_count_totals[attr_name]) assert total, "There must be at least one non-zero count." n = max(2, len(counts)) if self._tree.metric == ENTROPY1: # Traditional entropy. return -sum( (count/total)*math.log(count/total, n) for count in itervalues(counts) ) elif self._tree.metric == ENTROPY2: # Modified entropy that down-weights universally unique values. # e.g. If the number of unique attribute values equals the total # count of the attribute, then it has the maximum amount of unique # values. return -sum( (count/total)*math.log(count/total, n) for count in itervalues(counts) #) - ((len(counts)-1)/float(total)) ) + (unique_value_count/attr_total) elif self._tree.metric == ENTROPY3: # Modified entropy that down-weights universally unique values # as well as features with large numbers of values. return -sum( (count/total)*math.log(count/total, n) for count in itervalues(counts) #) - 100*((len(counts)-1)/float(total)) ) + 100*(unique_value_count/attr_total)
[ "def", "get_entropy", "(", "self", ",", "attr_name", "=", "None", ",", "attr_value", "=", "None", ")", ":", "is_con", "=", "self", ".", "tree", ".", "data", ".", "is_continuous_class", "if", "is_con", ":", "if", "attr_name", "is", "None", ":", "# Calculate variance of class attribute.", "var", "=", "self", ".", "_class_cdist", ".", "variance", "else", ":", "# Calculate variance of the given attribute.", "var", "=", "self", ".", "_attr_value_cdist", "[", "attr_name", "]", "[", "attr_value", "]", ".", "variance", "if", "self", ".", "tree", ".", "metric", "==", "VARIANCE1", "or", "attr_name", "is", "None", ":", "return", "var", "elif", "self", ".", "tree", ".", "metric", "==", "VARIANCE2", ":", "unique_value_count", "=", "len", "(", "self", ".", "_attr_value_counts", "[", "attr_name", "]", ")", "attr_total", "=", "float", "(", "self", ".", "_attr_value_count_totals", "[", "attr_name", "]", ")", "return", "var", "*", "(", "unique_value_count", "/", "attr_total", ")", "else", ":", "if", "attr_name", "is", "None", ":", "# The total number of times this attr/value pair has been seen.", "total", "=", "float", "(", "self", ".", "_class_ddist", ".", "total", ")", "# The total number of times each class value has been seen for", "# this attr/value pair.", "counts", "=", "self", ".", "_class_ddist", ".", "counts", "# The total number of unique values seen for this attribute.", "unique_value_count", "=", "len", "(", "self", ".", "_class_ddist", ".", "counts", ")", "# The total number of times this attribute has been seen.", "attr_total", "=", "total", "else", ":", "total", "=", "float", "(", "self", ".", "_attr_value_counts", "[", "attr_name", "]", "[", "attr_value", "]", ")", "counts", "=", "self", ".", "_attr_class_value_counts", "[", "attr_name", "]", "[", "attr_value", "]", "unique_value_count", "=", "len", "(", "self", ".", "_attr_value_counts", "[", "attr_name", "]", ")", "attr_total", "=", "float", "(", "self", ".", "_attr_value_count_totals", "[", "attr_name", "]", ")", "assert", "total", ",", "\"There must be at least one non-zero count.\"", "n", "=", "max", "(", "2", ",", "len", "(", "counts", ")", ")", "if", "self", ".", "_tree", ".", "metric", "==", "ENTROPY1", ":", "# Traditional entropy.", "return", "-", "sum", "(", "(", "count", "/", "total", ")", "*", "math", ".", "log", "(", "count", "/", "total", ",", "n", ")", "for", "count", "in", "itervalues", "(", "counts", ")", ")", "elif", "self", ".", "_tree", ".", "metric", "==", "ENTROPY2", ":", "# Modified entropy that down-weights universally unique values.", "# e.g. If the number of unique attribute values equals the total", "# count of the attribute, then it has the maximum amount of unique", "# values.", "return", "-", "sum", "(", "(", "count", "/", "total", ")", "*", "math", ".", "log", "(", "count", "/", "total", ",", "n", ")", "for", "count", "in", "itervalues", "(", "counts", ")", "#) - ((len(counts)-1)/float(total))", ")", "+", "(", "unique_value_count", "/", "attr_total", ")", "elif", "self", ".", "_tree", ".", "metric", "==", "ENTROPY3", ":", "# Modified entropy that down-weights universally unique values", "# as well as features with large numbers of values.", "return", "-", "sum", "(", "(", "count", "/", "total", ")", "*", "math", ".", "log", "(", "count", "/", "total", ",", "n", ")", "for", "count", "in", "itervalues", "(", "counts", ")", "#) - 100*((len(counts)-1)/float(total))", ")", "+", "100", "*", "(", "unique_value_count", "/", "attr_total", ")" ]
Calculates the entropy of a specific attribute/value combination.
[ "Calculates", "the", "entropy", "of", "a", "specific", "attribute", "/", "value", "combination", "." ]
9e9c9992b22ad9a7e296af7e6837666b05db43ef
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L966-L1026
train
chrisspen/dtree
dtree.py
Node.get_gain
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_entropy(attr_name, value) subset_entropy += value_prob * e return (self.main_entropy - subset_entropy)
python
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_entropy(attr_name, value) subset_entropy += value_prob * e return (self.main_entropy - subset_entropy)
[ "def", "get_gain", "(", "self", ",", "attr_name", ")", ":", "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_entropy", "(", "attr_name", ",", "value", ")", "subset_entropy", "+=", "value_prob", "*", "e", "return", "(", "self", ".", "main_entropy", "-", "subset_entropy", ")" ]
Calculates the information gain from splitting on the given attribute.
[ "Calculates", "the", "information", "gain", "from", "splitting", "on", "the", "given", "attribute", "." ]
9e9c9992b22ad9a7e296af7e6837666b05db43ef
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L1028-L1037
train
chrisspen/dtree
dtree.py
Node.get_value_ddist
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 types." ddist = DDist() cls_counts = self._attr_class_value_counts[attr_name][attr_value] for cls_value, cls_count in iteritems(cls_counts): ddist.add(cls_value, count=cls_count) return ddist
python
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 types." ddist = DDist() cls_counts = self._attr_class_value_counts[attr_name][attr_value] for cls_value, cls_count in iteritems(cls_counts): ddist.add(cls_value, count=cls_count) return ddist
[ "def", "get_value_ddist", "(", "self", ",", "attr_name", ",", "attr_value", ")", ":", "assert", "not", "self", ".", "tree", ".", "data", ".", "is_continuous_class", ",", "\"Discrete distributions are only maintained for \"", "+", "\"discrete class types.\"", "ddist", "=", "DDist", "(", ")", "cls_counts", "=", "self", ".", "_attr_class_value_counts", "[", "attr_name", "]", "[", "attr_value", "]", "for", "cls_value", ",", "cls_count", "in", "iteritems", "(", "cls_counts", ")", ":", "ddist", ".", "add", "(", "cls_value", ",", "count", "=", "cls_count", ")", "return", "ddist" ]
Returns the class value probability distribution of the given attribute value.
[ "Returns", "the", "class", "value", "probability", "distribution", "of", "the", "given", "attribute", "value", "." ]
9e9c9992b22ad9a7e296af7e6837666b05db43ef
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L1039-L1051
train
chrisspen/dtree
dtree.py
Node.get_value_prob
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[attr_name] return n/float(d)
python
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[attr_name] return n/float(d)
[ "def", "get_value_prob", "(", "self", ",", "attr_name", ",", "value", ")", ":", "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", "[", "attr_name", "]", "return", "n", "/", "float", "(", "d", ")" ]
Returns the value probability of the given attribute at this node.
[ "Returns", "the", "value", "probability", "of", "the", "given", "attribute", "at", "this", "node", "." ]
9e9c9992b22ad9a7e296af7e6837666b05db43ef
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L1053-L1061
train
chrisspen/dtree
dtree.py
Node.predict
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. attr_value = self._get_attribute_value_for_node(record) # Propagate decision to leaf node. if self.attr_name: if attr_value in self._branches: try: return self._branches[attr_value].predict(record, depth=depth+1) except NodeNotReadyToPredict: #TODO:allow re-raise if user doesn't want an intermediate prediction? pass # Otherwise make decision at current node. if self.attr_name: if self._tree.data.is_continuous_class: return self._attr_value_cdist[self.attr_name][attr_value].copy() else: # return self._class_ddist.copy() return self.get_value_ddist(self.attr_name, attr_value) elif self._tree.data.is_continuous_class: # Make decision at current node, which may be a true leaf node # or an incomplete branch in a tree currently being built. assert self._class_cdist is not None return self._class_cdist.copy() else: return self._class_ddist.copy()
python
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. attr_value = self._get_attribute_value_for_node(record) # Propagate decision to leaf node. if self.attr_name: if attr_value in self._branches: try: return self._branches[attr_value].predict(record, depth=depth+1) except NodeNotReadyToPredict: #TODO:allow re-raise if user doesn't want an intermediate prediction? pass # Otherwise make decision at current node. if self.attr_name: if self._tree.data.is_continuous_class: return self._attr_value_cdist[self.attr_name][attr_value].copy() else: # return self._class_ddist.copy() return self.get_value_ddist(self.attr_name, attr_value) elif self._tree.data.is_continuous_class: # Make decision at current node, which may be a true leaf node # or an incomplete branch in a tree currently being built. assert self._class_cdist is not None return self._class_cdist.copy() else: return self._class_ddist.copy()
[ "def", "predict", "(", "self", ",", "record", ",", "depth", "=", "0", ")", ":", "# Check if we're ready to predict.", "if", "not", "self", ".", "ready_to_predict", ":", "raise", "NodeNotReadyToPredict", "# Lookup attribute value.", "attr_value", "=", "self", ".", "_get_attribute_value_for_node", "(", "record", ")", "# Propagate decision to leaf node.", "if", "self", ".", "attr_name", ":", "if", "attr_value", "in", "self", ".", "_branches", ":", "try", ":", "return", "self", ".", "_branches", "[", "attr_value", "]", ".", "predict", "(", "record", ",", "depth", "=", "depth", "+", "1", ")", "except", "NodeNotReadyToPredict", ":", "#TODO:allow re-raise if user doesn't want an intermediate prediction?", "pass", "# Otherwise make decision at current node.", "if", "self", ".", "attr_name", ":", "if", "self", ".", "_tree", ".", "data", ".", "is_continuous_class", ":", "return", "self", ".", "_attr_value_cdist", "[", "self", ".", "attr_name", "]", "[", "attr_value", "]", ".", "copy", "(", ")", "else", ":", "# return self._class_ddist.copy()", "return", "self", ".", "get_value_ddist", "(", "self", ".", "attr_name", ",", "attr_value", ")", "elif", "self", ".", "_tree", ".", "data", ".", "is_continuous_class", ":", "# Make decision at current node, which may be a true leaf node", "# or an incomplete branch in a tree currently being built.", "assert", "self", ".", "_class_cdist", "is", "not", "None", "return", "self", ".", "_class_cdist", ".", "copy", "(", ")", "else", ":", "return", "self", ".", "_class_ddist", ".", "copy", "(", ")" ]
Returns the estimated value of the class attribute for the given record.
[ "Returns", "the", "estimated", "value", "of", "the", "class", "attribute", "for", "the", "given", "record", "." ]
9e9c9992b22ad9a7e296af7e6837666b05db43ef
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L1070-L1105
train
chrisspen/dtree
dtree.py
Node.ready_to_split
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: var = self._class_cdist.variance if var is not None and threshold is not None \ and var <= threshold: return False else: best_prob = self._class_ddist.best_prob if best_prob is not None and threshold is not None \ and best_prob >= threshold: return False return self._tree.auto_grow \ and not self.attr_name \ and self.n >= self._tree.splitting_n
python
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: var = self._class_cdist.variance if var is not None and threshold is not None \ and var <= threshold: return False else: best_prob = self._class_ddist.best_prob if best_prob is not None and threshold is not None \ and best_prob >= threshold: return False return self._tree.auto_grow \ and not self.attr_name \ and self.n >= self._tree.splitting_n
[ "def", "ready_to_split", "(", "self", ")", ":", "# Never split if we're a leaf that predicts adequately.", "threshold", "=", "self", ".", "_tree", ".", "leaf_threshold", "if", "self", ".", "_tree", ".", "data", ".", "is_continuous_class", ":", "var", "=", "self", ".", "_class_cdist", ".", "variance", "if", "var", "is", "not", "None", "and", "threshold", "is", "not", "None", "and", "var", "<=", "threshold", ":", "return", "False", "else", ":", "best_prob", "=", "self", ".", "_class_ddist", ".", "best_prob", "if", "best_prob", "is", "not", "None", "and", "threshold", "is", "not", "None", "and", "best_prob", ">=", "threshold", ":", "return", "False", "return", "self", ".", "_tree", ".", "auto_grow", "and", "not", "self", ".", "attr_name", "and", "self", ".", "n", ">=", "self", ".", "_tree", ".", "splitting_n" ]
Returns true if this node is ready to branch off additional nodes. Returns false otherwise.
[ "Returns", "true", "if", "this", "node", "is", "ready", "to", "branch", "off", "additional", "nodes", ".", "Returns", "false", "otherwise", "." ]
9e9c9992b22ad9a7e296af7e6837666b05db43ef
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L1112-L1132
train
chrisspen/dtree
dtree.py
Node.set_leaf_dist
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_name) if self.is_continuous_class: assert isinstance(dist, CDist) assert self.attr_name self._attr_value_cdist[self.attr_name][attr_value] = dist.copy() # self.n += dist.count else: assert isinstance(dist, DDist) # {attr_name:{attr_value:count}} self._attr_value_counts[self.attr_name][attr_value] += 1 # {attr_name:total} self._attr_value_count_totals[self.attr_name] += 1 # {attr_name:{attr_value:{class_value:count}}} for cls_value, cls_count in iteritems(dist.counts): self._attr_class_value_counts[self.attr_name][attr_value] \ [cls_value] += cls_count
python
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_name) if self.is_continuous_class: assert isinstance(dist, CDist) assert self.attr_name self._attr_value_cdist[self.attr_name][attr_value] = dist.copy() # self.n += dist.count else: assert isinstance(dist, DDist) # {attr_name:{attr_value:count}} self._attr_value_counts[self.attr_name][attr_value] += 1 # {attr_name:total} self._attr_value_count_totals[self.attr_name] += 1 # {attr_name:{attr_value:{class_value:count}}} for cls_value, cls_count in iteritems(dist.counts): self._attr_class_value_counts[self.attr_name][attr_value] \ [cls_value] += cls_count
[ "def", "set_leaf_dist", "(", "self", ",", "attr_value", ",", "dist", ")", ":", "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_name", ")", "if", "self", ".", "is_continuous_class", ":", "assert", "isinstance", "(", "dist", ",", "CDist", ")", "assert", "self", ".", "attr_name", "self", ".", "_attr_value_cdist", "[", "self", ".", "attr_name", "]", "[", "attr_value", "]", "=", "dist", ".", "copy", "(", ")", "# self.n += dist.count", "else", ":", "assert", "isinstance", "(", "dist", ",", "DDist", ")", "# {attr_name:{attr_value:count}}", "self", ".", "_attr_value_counts", "[", "self", ".", "attr_name", "]", "[", "attr_value", "]", "+=", "1", "# {attr_name:total}", "self", ".", "_attr_value_count_totals", "[", "self", ".", "attr_name", "]", "+=", "1", "# {attr_name:{attr_value:{class_value:count}}}", "for", "cls_value", ",", "cls_count", "in", "iteritems", "(", "dist", ".", "counts", ")", ":", "self", ".", "_attr_class_value_counts", "[", "self", ".", "attr_name", "]", "[", "attr_value", "]", "[", "cls_value", "]", "+=", "cls_count" ]
Sets the probability distribution at a leaf node.
[ "Sets", "the", "probability", "distribution", "at", "a", "leaf", "node", "." ]
9e9c9992b22ad9a7e296af7e6837666b05db43ef
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L1134-L1156
train
chrisspen/dtree
dtree.py
Node.train
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 if is_con: # For a continuous class. self._class_cdist += class_value else: # For a discrete class. self._class_ddist.add(class_value) # Update attribute statistics. for an, av in iteritems(record): if an == class_attr: continue self._attr_value_counts[an][av] += 1 self._attr_value_count_totals[an] += 1 if is_con: self._attr_value_cdist[an][av] += class_value else: self._attr_class_value_counts[an][av][class_value] += 1 # Decide if branch should split on an attribute. if self.ready_to_split: self.attr_name = self.get_best_splitting_attr() self.tree.leaf_count -= 1 for av in self._attr_value_counts[self.attr_name]: self._branches[av] = Node(tree=self.tree) self.tree.leaf_count += 1 # If we've split, then propagate the update to appropriate sub-branch. if self.attr_name: key = record[self.attr_name] del record[self.attr_name] self._branches[key].train(record)
python
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 if is_con: # For a continuous class. self._class_cdist += class_value else: # For a discrete class. self._class_ddist.add(class_value) # Update attribute statistics. for an, av in iteritems(record): if an == class_attr: continue self._attr_value_counts[an][av] += 1 self._attr_value_count_totals[an] += 1 if is_con: self._attr_value_cdist[an][av] += class_value else: self._attr_class_value_counts[an][av][class_value] += 1 # Decide if branch should split on an attribute. if self.ready_to_split: self.attr_name = self.get_best_splitting_attr() self.tree.leaf_count -= 1 for av in self._attr_value_counts[self.attr_name]: self._branches[av] = Node(tree=self.tree) self.tree.leaf_count += 1 # If we've split, then propagate the update to appropriate sub-branch. if self.attr_name: key = record[self.attr_name] del record[self.attr_name] self._branches[key].train(record)
[ "def", "train", "(", "self", ",", "record", ")", ":", "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", "if", "is_con", ":", "# For a continuous class.", "self", ".", "_class_cdist", "+=", "class_value", "else", ":", "# For a discrete class.", "self", ".", "_class_ddist", ".", "add", "(", "class_value", ")", "# Update attribute statistics.", "for", "an", ",", "av", "in", "iteritems", "(", "record", ")", ":", "if", "an", "==", "class_attr", ":", "continue", "self", ".", "_attr_value_counts", "[", "an", "]", "[", "av", "]", "+=", "1", "self", ".", "_attr_value_count_totals", "[", "an", "]", "+=", "1", "if", "is_con", ":", "self", ".", "_attr_value_cdist", "[", "an", "]", "[", "av", "]", "+=", "class_value", "else", ":", "self", ".", "_attr_class_value_counts", "[", "an", "]", "[", "av", "]", "[", "class_value", "]", "+=", "1", "# Decide if branch should split on an attribute.", "if", "self", ".", "ready_to_split", ":", "self", ".", "attr_name", "=", "self", ".", "get_best_splitting_attr", "(", ")", "self", ".", "tree", ".", "leaf_count", "-=", "1", "for", "av", "in", "self", ".", "_attr_value_counts", "[", "self", ".", "attr_name", "]", ":", "self", ".", "_branches", "[", "av", "]", "=", "Node", "(", "tree", "=", "self", ".", "tree", ")", "self", ".", "tree", ".", "leaf_count", "+=", "1", "# If we've split, then propagate the update to appropriate sub-branch.", "if", "self", ".", "attr_name", ":", "key", "=", "record", "[", "self", ".", "attr_name", "]", "del", "record", "[", "self", ".", "attr_name", "]", "self", ".", "_branches", "[", "key", "]", ".", "train", "(", "record", ")" ]
Incrementally update the statistics at this node.
[ "Incrementally", "update", "the", "statistics", "at", "this", "node", "." ]
9e9c9992b22ad9a7e296af7e6837666b05db43ef
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L1184-L1224
train
chrisspen/dtree
dtree.py
Tree.build
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: fitness_func = get_gain t = cls(data=data, *args, **kwargs) t._data = data t.sample_count = len(data) t._tree = create_decision_tree( data=data, attributes=data.attribute_names, class_attr=data.class_attribute_name, fitness_func=fitness_func, wrapper=t, ) return t
python
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: fitness_func = get_gain t = cls(data=data, *args, **kwargs) t._data = data t.sample_count = len(data) t._tree = create_decision_tree( data=data, attributes=data.attribute_names, class_attr=data.class_attribute_name, fitness_func=fitness_func, wrapper=t, ) return t
[ "def", "build", "(", "cls", ",", "data", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "assert", "isinstance", "(", "data", ",", "Data", ")", "if", "data", ".", "is_continuous_class", ":", "fitness_func", "=", "gain_variance", "else", ":", "fitness_func", "=", "get_gain", "t", "=", "cls", "(", "data", "=", "data", ",", "*", "args", ",", "*", "*", "kwargs", ")", "t", ".", "_data", "=", "data", "t", ".", "sample_count", "=", "len", "(", "data", ")", "t", ".", "_tree", "=", "create_decision_tree", "(", "data", "=", "data", ",", "attributes", "=", "data", ".", "attribute_names", ",", "class_attr", "=", "data", ".", "class_attribute_name", ",", "fitness_func", "=", "fitness_func", ",", "wrapper", "=", "t", ",", ")", "return", "t" ]
Constructs a classification or regression tree in a single batch by analyzing the given data.
[ "Constructs", "a", "classification", "or", "regression", "tree", "in", "a", "single", "batch", "by", "analyzing", "the", "given", "data", "." ]
9e9c9992b22ad9a7e296af7e6837666b05db43ef
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L1293-L1314
train
chrisspen/dtree
dtree.py
Tree.out_of_bag_mae
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 = True except NodeNotReadyToPredict: return return self._out_of_bag_mae.copy()
python
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 = True except NodeNotReadyToPredict: return return self._out_of_bag_mae.copy()
[ "def", "out_of_bag_mae", "(", "self", ")", ":", "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", "=", "True", "except", "NodeNotReadyToPredict", ":", "return", "return", "self", ".", "_out_of_bag_mae", ".", "copy", "(", ")" ]
Returns the mean absolute error for predictions on the out-of-bag samples.
[ "Returns", "the", "mean", "absolute", "error", "for", "predictions", "on", "the", "out", "-", "of", "-", "bag", "samples", "." ]
9e9c9992b22ad9a7e296af7e6837666b05db43ef
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L1331-L1342
train
chrisspen/dtree
dtree.py
Tree.out_of_bag_samples
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 __len__(self): return len(self.tree._out_of_bag_samples) def append(self, v): self.tree._out_of_bag_mae_clean = False return self.tree._out_of_bag_samples.append(v) def pop(self, v): self.tree._out_of_bag_mae_clean = False return self.tree._out_of_bag_samples.pop(v) def __iter__(self): for _ in self.tree._out_of_bag_samples: yield _ return O(self)
python
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 __len__(self): return len(self.tree._out_of_bag_samples) def append(self, v): self.tree._out_of_bag_mae_clean = False return self.tree._out_of_bag_samples.append(v) def pop(self, v): self.tree._out_of_bag_mae_clean = False return self.tree._out_of_bag_samples.pop(v) def __iter__(self): for _ in self.tree._out_of_bag_samples: yield _ return O(self)
[ "def", "out_of_bag_samples", "(", "self", ")", ":", "#TODO:replace with more a generic pass-through wrapper?", "class", "O", "(", "object", ")", ":", "def", "__init__", "(", "self", ",", "tree", ")", ":", "self", ".", "tree", "=", "tree", "def", "__len__", "(", "self", ")", ":", "return", "len", "(", "self", ".", "tree", ".", "_out_of_bag_samples", ")", "def", "append", "(", "self", ",", "v", ")", ":", "self", ".", "tree", ".", "_out_of_bag_mae_clean", "=", "False", "return", "self", ".", "tree", ".", "_out_of_bag_samples", ".", "append", "(", "v", ")", "def", "pop", "(", "self", ",", "v", ")", ":", "self", ".", "tree", ".", "_out_of_bag_mae_clean", "=", "False", "return", "self", ".", "tree", ".", "_out_of_bag_samples", ".", "pop", "(", "v", ")", "def", "__iter__", "(", "self", ")", ":", "for", "_", "in", "self", ".", "tree", ".", "_out_of_bag_samples", ":", "yield", "_", "return", "O", "(", "self", ")" ]
Returns the out-of-bag samples list, inside a wrapper to keep track of modifications.
[ "Returns", "the", "out", "-", "of", "-", "bag", "samples", "list", "inside", "a", "wrapper", "to", "keep", "track", "of", "modifications", "." ]
9e9c9992b22ad9a7e296af7e6837666b05db43ef
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L1345-L1365
train
chrisspen/dtree
dtree.py
Tree.set_missing_value_policy
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, \ "Unknown policy: %s" % (policy,) for attr_name in self.data.attribute_names: if target_attr_name is not None and target_attr_name != attr_name: continue self.missing_value_policy[attr_name] = policy
python
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, \ "Unknown policy: %s" % (policy,) for attr_name in self.data.attribute_names: if target_attr_name is not None and target_attr_name != attr_name: continue self.missing_value_policy[attr_name] = policy
[ "def", "set_missing_value_policy", "(", "self", ",", "policy", ",", "target_attr_name", "=", "None", ")", ":", "assert", "policy", "in", "MISSING_VALUE_POLICIES", ",", "\"Unknown policy: %s\"", "%", "(", "policy", ",", ")", "for", "attr_name", "in", "self", ".", "data", ".", "attribute_names", ":", "if", "target_attr_name", "is", "not", "None", "and", "target_attr_name", "!=", "attr_name", ":", "continue", "self", ".", "missing_value_policy", "[", "attr_name", "]", "=", "policy" ]
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.
[ "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", "." ]
9e9c9992b22ad9a7e296af7e6837666b05db43ef
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L1374-L1385
train
chrisspen/dtree
dtree.py
Tree.train
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.tree.train(record)
python
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.tree.train(record)
[ "def", "train", "(", "self", ",", "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", ".", "tree", ".", "train", "(", "record", ")" ]
Incrementally updates the tree with the given sample record.
[ "Incrementally", "updates", "the", "tree", "with", "the", "given", "sample", "record", "." ]
9e9c9992b22ad9a7e296af7e6837666b05db43ef
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L1415-L1423
train
chrisspen/dtree
dtree.py
Forest._fell_trees
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)
python
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", "_fell_trees", "(", "self", ")", ":", "if", "callable", "(", "self", ".", "fell_method", ")", ":", "for", "tree", "in", "self", ".", "fell_method", "(", "list", "(", "self", ".", "trees", ")", ")", ":", "self", ".", "trees", ".", "remove", "(", "tree", ")" ]
Removes trees from the forest according to the specified fell method.
[ "Removes", "trees", "from", "the", "forest", "according", "to", "the", "specified", "fell", "method", "." ]
9e9c9992b22ad9a7e296af7e6837666b05db43ef
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L1470-L1476
train
chrisspen/dtree
dtree.py
Forest._get_best_prediction
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)) _, best_tree = best prediction, tree_mae = best_tree.predict(record, train=train) return prediction.mean
python
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)) _, best_tree = best prediction, tree_mae = best_tree.predict(record, train=train) return prediction.mean
[ "def", "_get_best_prediction", "(", "self", ",", "record", ",", "train", "=", "True", ")", ":", "if", "not", "self", ".", "trees", ":", "return", "best", "=", "(", "+", "1e999999", ",", "None", ")", "for", "tree", "in", "self", ".", "trees", ":", "best", "=", "min", "(", "best", ",", "(", "tree", ".", "mae", ".", "mean", ",", "tree", ")", ")", "_", ",", "best_tree", "=", "best", "prediction", ",", "tree_mae", "=", "best_tree", ".", "predict", "(", "record", ",", "train", "=", "train", ")", "return", "prediction", ".", "mean" ]
Gets the prediction from the tree with the lowest mean absolute error.
[ "Gets", "the", "prediction", "from", "the", "tree", "with", "the", "lowest", "mean", "absolute", "error", "." ]
9e9c9992b22ad9a7e296af7e6837666b05db43ef
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L1478-L1489
train
chrisspen/dtree
dtree.py
Forest.best_oob_mae_weight
def best_oob_mae_weight(trees): """ Returns weights so that the tree with smallest out-of-bag mean absolute error """ best = (+1e999999, None) for tree in trees: oob_mae = tree.out_of_bag_mae if oob_mae is None or oob_mae.mean is None: continue best = min(best, (oob_mae.mean, tree)) best_mae, best_tree = best if best_tree is None: return return [(1.0, best_tree)]
python
def best_oob_mae_weight(trees): """ Returns weights so that the tree with smallest out-of-bag mean absolute error """ best = (+1e999999, None) for tree in trees: oob_mae = tree.out_of_bag_mae if oob_mae is None or oob_mae.mean is None: continue best = min(best, (oob_mae.mean, tree)) best_mae, best_tree = best if best_tree is None: return return [(1.0, best_tree)]
[ "def", "best_oob_mae_weight", "(", "trees", ")", ":", "best", "=", "(", "+", "1e999999", ",", "None", ")", "for", "tree", "in", "trees", ":", "oob_mae", "=", "tree", ".", "out_of_bag_mae", "if", "oob_mae", "is", "None", "or", "oob_mae", ".", "mean", "is", "None", ":", "continue", "best", "=", "min", "(", "best", ",", "(", "oob_mae", ".", "mean", ",", "tree", ")", ")", "best_mae", ",", "best_tree", "=", "best", "if", "best_tree", "is", "None", ":", "return", "return", "[", "(", "1.0", ",", "best_tree", ")", "]" ]
Returns weights so that the tree with smallest out-of-bag mean absolute error
[ "Returns", "weights", "so", "that", "the", "tree", "with", "smallest", "out", "-", "of", "-", "bag", "mean", "absolute", "error" ]
9e9c9992b22ad9a7e296af7e6837666b05db43ef
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L1492-L1505
train
chrisspen/dtree
dtree.py
Forest.mean_oob_mae_weight
def mean_oob_mae_weight(trees): """ Returns weights proportional to the out-of-bag mean absolute error for each tree. """ weights = [] active_trees = [] for tree in trees: oob_mae = tree.out_of_bag_mae if oob_mae is None or oob_mae.mean is None: continue weights.append(oob_mae.mean) active_trees.append(tree) if not active_trees: return weights = normalize(weights) return zip(weights, active_trees)
python
def mean_oob_mae_weight(trees): """ Returns weights proportional to the out-of-bag mean absolute error for each tree. """ weights = [] active_trees = [] for tree in trees: oob_mae = tree.out_of_bag_mae if oob_mae is None or oob_mae.mean is None: continue weights.append(oob_mae.mean) active_trees.append(tree) if not active_trees: return weights = normalize(weights) return zip(weights, active_trees)
[ "def", "mean_oob_mae_weight", "(", "trees", ")", ":", "weights", "=", "[", "]", "active_trees", "=", "[", "]", "for", "tree", "in", "trees", ":", "oob_mae", "=", "tree", ".", "out_of_bag_mae", "if", "oob_mae", "is", "None", "or", "oob_mae", ".", "mean", "is", "None", ":", "continue", "weights", ".", "append", "(", "oob_mae", ".", "mean", ")", "active_trees", ".", "append", "(", "tree", ")", "if", "not", "active_trees", ":", "return", "weights", "=", "normalize", "(", "weights", ")", "return", "zip", "(", "weights", ",", "active_trees", ")" ]
Returns weights proportional to the out-of-bag mean absolute error for each tree.
[ "Returns", "weights", "proportional", "to", "the", "out", "-", "of", "-", "bag", "mean", "absolute", "error", "for", "each", "tree", "." ]
9e9c9992b22ad9a7e296af7e6837666b05db43ef
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L1508-L1523
train
chrisspen/dtree
dtree.py
Forest._grow_trees
def _grow_trees(self): """ Adds new trees to the forest according to the specified growth method. """ if self.grow_method == GROW_AUTO_INCREMENTAL: self.tree_kwargs['auto_grow'] = True while len(self.trees) < self.size: self.trees.append(Tree(data=self.data, **self.tree_kwargs))
python
def _grow_trees(self): """ Adds new trees to the forest according to the specified growth method. """ if self.grow_method == GROW_AUTO_INCREMENTAL: self.tree_kwargs['auto_grow'] = True while len(self.trees) < self.size: self.trees.append(Tree(data=self.data, **self.tree_kwargs))
[ "def", "_grow_trees", "(", "self", ")", ":", "if", "self", ".", "grow_method", "==", "GROW_AUTO_INCREMENTAL", ":", "self", ".", "tree_kwargs", "[", "'auto_grow'", "]", "=", "True", "while", "len", "(", "self", ".", "trees", ")", "<", "self", ".", "size", ":", "self", ".", "trees", ".", "append", "(", "Tree", "(", "data", "=", "self", ".", "data", ",", "*", "*", "self", ".", "tree_kwargs", ")", ")" ]
Adds new trees to the forest according to the specified growth method.
[ "Adds", "new", "trees", "to", "the", "forest", "according", "to", "the", "specified", "growth", "method", "." ]
9e9c9992b22ad9a7e296af7e6837666b05db43ef
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L1525-L1533
train
chrisspen/dtree
dtree.py
Forest.predict
def predict(self, record): """ Attempts to predict the value of the class attribute by aggregating the predictions of each tree. Parameters: weighting_formula := a callable that takes a list of trees and returns a list of weights. """ # Get raw predictions. # {tree:raw prediction} predictions = {} for tree in self.trees: _p = tree.predict(record) if _p is None: continue if isinstance(_p, CDist): if _p.mean is None: continue elif isinstance(_p, DDist): if not _p.count: continue predictions[tree] = _p if not predictions: return # Normalize weights and aggregate final prediction. weights = self.weighting_method(predictions.keys()) if not weights: return # assert sum(weights) == 1.0, "Sum of weights must equal 1." if self.data.is_continuous_class: # Merge continuous class predictions. total = sum(w*predictions[tree].mean for w, tree in weights) else: # Merge discrete class predictions. total = DDist() for weight, tree in weights: prediction = predictions[tree] for cls_value, cls_prob in prediction.probs: total.add(cls_value, cls_prob*weight) return total
python
def predict(self, record): """ Attempts to predict the value of the class attribute by aggregating the predictions of each tree. Parameters: weighting_formula := a callable that takes a list of trees and returns a list of weights. """ # Get raw predictions. # {tree:raw prediction} predictions = {} for tree in self.trees: _p = tree.predict(record) if _p is None: continue if isinstance(_p, CDist): if _p.mean is None: continue elif isinstance(_p, DDist): if not _p.count: continue predictions[tree] = _p if not predictions: return # Normalize weights and aggregate final prediction. weights = self.weighting_method(predictions.keys()) if not weights: return # assert sum(weights) == 1.0, "Sum of weights must equal 1." if self.data.is_continuous_class: # Merge continuous class predictions. total = sum(w*predictions[tree].mean for w, tree in weights) else: # Merge discrete class predictions. total = DDist() for weight, tree in weights: prediction = predictions[tree] for cls_value, cls_prob in prediction.probs: total.add(cls_value, cls_prob*weight) return total
[ "def", "predict", "(", "self", ",", "record", ")", ":", "# Get raw predictions.", "# {tree:raw prediction}", "predictions", "=", "{", "}", "for", "tree", "in", "self", ".", "trees", ":", "_p", "=", "tree", ".", "predict", "(", "record", ")", "if", "_p", "is", "None", ":", "continue", "if", "isinstance", "(", "_p", ",", "CDist", ")", ":", "if", "_p", ".", "mean", "is", "None", ":", "continue", "elif", "isinstance", "(", "_p", ",", "DDist", ")", ":", "if", "not", "_p", ".", "count", ":", "continue", "predictions", "[", "tree", "]", "=", "_p", "if", "not", "predictions", ":", "return", "# Normalize weights and aggregate final prediction.", "weights", "=", "self", ".", "weighting_method", "(", "predictions", ".", "keys", "(", ")", ")", "if", "not", "weights", ":", "return", "# assert sum(weights) == 1.0, \"Sum of weights must equal 1.\"", "if", "self", ".", "data", ".", "is_continuous_class", ":", "# Merge continuous class predictions.", "total", "=", "sum", "(", "w", "*", "predictions", "[", "tree", "]", ".", "mean", "for", "w", ",", "tree", "in", "weights", ")", "else", ":", "# Merge discrete class predictions.", "total", "=", "DDist", "(", ")", "for", "weight", ",", "tree", "in", "weights", ":", "prediction", "=", "predictions", "[", "tree", "]", "for", "cls_value", ",", "cls_prob", "in", "prediction", ".", "probs", ":", "total", ".", "add", "(", "cls_value", ",", "cls_prob", "*", "weight", ")", "return", "total" ]
Attempts to predict the value of the class attribute by aggregating the predictions of each tree. Parameters: weighting_formula := a callable that takes a list of trees and returns a list of weights.
[ "Attempts", "to", "predict", "the", "value", "of", "the", "class", "attribute", "by", "aggregating", "the", "predictions", "of", "each", "tree", ".", "Parameters", ":", "weighting_formula", ":", "=", "a", "callable", "that", "takes", "a", "list", "of", "trees", "and", "returns", "a", "list", "of", "weights", "." ]
9e9c9992b22ad9a7e296af7e6837666b05db43ef
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L1539-L1582
train
chrisspen/dtree
dtree.py
Forest.train
def train(self, record): """ Updates the trees with the given training record. """ self._fell_trees() self._grow_trees() for tree in self.trees: if random.random() < self.sample_ratio: tree.train(record) else: tree.out_of_bag_samples.append(record) while len(tree.out_of_bag_samples) > self.max_out_of_bag_samples: tree.out_of_bag_samples.pop(0)
python
def train(self, record): """ Updates the trees with the given training record. """ self._fell_trees() self._grow_trees() for tree in self.trees: if random.random() < self.sample_ratio: tree.train(record) else: tree.out_of_bag_samples.append(record) while len(tree.out_of_bag_samples) > self.max_out_of_bag_samples: tree.out_of_bag_samples.pop(0)
[ "def", "train", "(", "self", ",", "record", ")", ":", "self", ".", "_fell_trees", "(", ")", "self", ".", "_grow_trees", "(", ")", "for", "tree", "in", "self", ".", "trees", ":", "if", "random", ".", "random", "(", ")", "<", "self", ".", "sample_ratio", ":", "tree", ".", "train", "(", "record", ")", "else", ":", "tree", ".", "out_of_bag_samples", ".", "append", "(", "record", ")", "while", "len", "(", "tree", ".", "out_of_bag_samples", ")", ">", "self", ".", "max_out_of_bag_samples", ":", "tree", ".", "out_of_bag_samples", ".", "pop", "(", "0", ")" ]
Updates the trees with the given training record.
[ "Updates", "the", "trees", "with", "the", "given", "training", "record", "." ]
9e9c9992b22ad9a7e296af7e6837666b05db43ef
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L1613-L1625
train
dwavesystems/dwave-cloud-client
dwave/cloud/config.py
get_configfile_paths
def get_configfile_paths(system=True, user=True, local=True, only_existing=True): """Return a list of local configuration file paths. Search paths for configuration files on the local system are based on homebase_ and depend on operating system; for example, for Linux systems these might include ``dwave.conf`` in the current working directory (CWD), user-local ``.config/dwave/``, and system-wide ``/etc/dwave/``. .. _homebase: https://github.com/dwavesystems/homebase Args: system (boolean, default=True): Search for system-wide configuration files. user (boolean, default=True): Search for user-local configuration files. local (boolean, default=True): Search for local configuration files (in CWD). only_existing (boolean, default=True): Return only paths for files that exist on the local system. Returns: list[str]: List of configuration file paths. Examples: This example displays all paths to configuration files on a Windows system running Python 2.7 and then finds the single existing configuration file. >>> import dwave.cloud as dc >>> # Display paths >>> dc.config.get_configfile_paths(only_existing=False) # doctest: +SKIP [u'C:\\ProgramData\\dwavesystem\\dwave\\dwave.conf', u'C:\\Users\\jane\\AppData\\Local\\dwavesystem\\dwave\\dwave.conf', '.\\dwave.conf'] >>> # Find existing files >>> dc.config.get_configfile_paths() # doctest: +SKIP [u'C:\\Users\\jane\\AppData\\Local\\dwavesystem\\dwave\\dwave.conf'] """ candidates = [] # system-wide has the lowest priority, `/etc/dwave/dwave.conf` if system: candidates.extend(homebase.site_config_dir_list( app_author=CONF_AUTHOR, app_name=CONF_APP, use_virtualenv=False, create=False)) # user-local will override it, `~/.config/dwave/dwave.conf` if user: candidates.append(homebase.user_config_dir( app_author=CONF_AUTHOR, app_name=CONF_APP, roaming=False, use_virtualenv=False, create=False)) # highest priority (overrides all): `./dwave.conf` if local: candidates.append(".") paths = [os.path.join(base, CONF_FILENAME) for base in candidates] if only_existing: paths = list(filter(os.path.exists, paths)) return paths
python
def get_configfile_paths(system=True, user=True, local=True, only_existing=True): """Return a list of local configuration file paths. Search paths for configuration files on the local system are based on homebase_ and depend on operating system; for example, for Linux systems these might include ``dwave.conf`` in the current working directory (CWD), user-local ``.config/dwave/``, and system-wide ``/etc/dwave/``. .. _homebase: https://github.com/dwavesystems/homebase Args: system (boolean, default=True): Search for system-wide configuration files. user (boolean, default=True): Search for user-local configuration files. local (boolean, default=True): Search for local configuration files (in CWD). only_existing (boolean, default=True): Return only paths for files that exist on the local system. Returns: list[str]: List of configuration file paths. Examples: This example displays all paths to configuration files on a Windows system running Python 2.7 and then finds the single existing configuration file. >>> import dwave.cloud as dc >>> # Display paths >>> dc.config.get_configfile_paths(only_existing=False) # doctest: +SKIP [u'C:\\ProgramData\\dwavesystem\\dwave\\dwave.conf', u'C:\\Users\\jane\\AppData\\Local\\dwavesystem\\dwave\\dwave.conf', '.\\dwave.conf'] >>> # Find existing files >>> dc.config.get_configfile_paths() # doctest: +SKIP [u'C:\\Users\\jane\\AppData\\Local\\dwavesystem\\dwave\\dwave.conf'] """ candidates = [] # system-wide has the lowest priority, `/etc/dwave/dwave.conf` if system: candidates.extend(homebase.site_config_dir_list( app_author=CONF_AUTHOR, app_name=CONF_APP, use_virtualenv=False, create=False)) # user-local will override it, `~/.config/dwave/dwave.conf` if user: candidates.append(homebase.user_config_dir( app_author=CONF_AUTHOR, app_name=CONF_APP, roaming=False, use_virtualenv=False, create=False)) # highest priority (overrides all): `./dwave.conf` if local: candidates.append(".") paths = [os.path.join(base, CONF_FILENAME) for base in candidates] if only_existing: paths = list(filter(os.path.exists, paths)) return paths
[ "def", "get_configfile_paths", "(", "system", "=", "True", ",", "user", "=", "True", ",", "local", "=", "True", ",", "only_existing", "=", "True", ")", ":", "candidates", "=", "[", "]", "# system-wide has the lowest priority, `/etc/dwave/dwave.conf`", "if", "system", ":", "candidates", ".", "extend", "(", "homebase", ".", "site_config_dir_list", "(", "app_author", "=", "CONF_AUTHOR", ",", "app_name", "=", "CONF_APP", ",", "use_virtualenv", "=", "False", ",", "create", "=", "False", ")", ")", "# user-local will override it, `~/.config/dwave/dwave.conf`", "if", "user", ":", "candidates", ".", "append", "(", "homebase", ".", "user_config_dir", "(", "app_author", "=", "CONF_AUTHOR", ",", "app_name", "=", "CONF_APP", ",", "roaming", "=", "False", ",", "use_virtualenv", "=", "False", ",", "create", "=", "False", ")", ")", "# highest priority (overrides all): `./dwave.conf`", "if", "local", ":", "candidates", ".", "append", "(", "\".\"", ")", "paths", "=", "[", "os", ".", "path", ".", "join", "(", "base", ",", "CONF_FILENAME", ")", "for", "base", "in", "candidates", "]", "if", "only_existing", ":", "paths", "=", "list", "(", "filter", "(", "os", ".", "path", ".", "exists", ",", "paths", ")", ")", "return", "paths" ]
Return a list of local configuration file paths. Search paths for configuration files on the local system are based on homebase_ and depend on operating system; for example, for Linux systems these might include ``dwave.conf`` in the current working directory (CWD), user-local ``.config/dwave/``, and system-wide ``/etc/dwave/``. .. _homebase: https://github.com/dwavesystems/homebase Args: system (boolean, default=True): Search for system-wide configuration files. user (boolean, default=True): Search for user-local configuration files. local (boolean, default=True): Search for local configuration files (in CWD). only_existing (boolean, default=True): Return only paths for files that exist on the local system. Returns: list[str]: List of configuration file paths. Examples: This example displays all paths to configuration files on a Windows system running Python 2.7 and then finds the single existing configuration file. >>> import dwave.cloud as dc >>> # Display paths >>> dc.config.get_configfile_paths(only_existing=False) # doctest: +SKIP [u'C:\\ProgramData\\dwavesystem\\dwave\\dwave.conf', u'C:\\Users\\jane\\AppData\\Local\\dwavesystem\\dwave\\dwave.conf', '.\\dwave.conf'] >>> # Find existing files >>> dc.config.get_configfile_paths() # doctest: +SKIP [u'C:\\Users\\jane\\AppData\\Local\\dwavesystem\\dwave\\dwave.conf']
[ "Return", "a", "list", "of", "local", "configuration", "file", "paths", "." ]
df3221a8385dc0c04d7b4d84f740bf3ad6706230
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/config.py#L239-L304
train
dwavesystems/dwave-cloud-client
dwave/cloud/config.py
get_default_configfile_path
def get_default_configfile_path(): """Return the default configuration-file path. Typically returns a user-local configuration file; e.g: ``~/.config/dwave/dwave.conf``. Returns: str: Configuration file path. Examples: This example displays the default configuration file on an Ubuntu Unix system running IPython 2.7. >>> import dwave.cloud as dc >>> # Display paths >>> dc.config.get_configfile_paths(only_existing=False) # doctest: +SKIP ['/etc/xdg/xdg-ubuntu/dwave/dwave.conf', '/usr/share/upstart/xdg/dwave/dwave.conf', '/etc/xdg/dwave/dwave.conf', '/home/mary/.config/dwave/dwave.conf', './dwave.conf'] >>> # Find default configuration path >>> dc.config.get_default_configfile_path() # doctest: +SKIP '/home/mary/.config/dwave/dwave.conf' """ base = homebase.user_config_dir( app_author=CONF_AUTHOR, app_name=CONF_APP, roaming=False, use_virtualenv=False, create=False) path = os.path.join(base, CONF_FILENAME) return path
python
def get_default_configfile_path(): """Return the default configuration-file path. Typically returns a user-local configuration file; e.g: ``~/.config/dwave/dwave.conf``. Returns: str: Configuration file path. Examples: This example displays the default configuration file on an Ubuntu Unix system running IPython 2.7. >>> import dwave.cloud as dc >>> # Display paths >>> dc.config.get_configfile_paths(only_existing=False) # doctest: +SKIP ['/etc/xdg/xdg-ubuntu/dwave/dwave.conf', '/usr/share/upstart/xdg/dwave/dwave.conf', '/etc/xdg/dwave/dwave.conf', '/home/mary/.config/dwave/dwave.conf', './dwave.conf'] >>> # Find default configuration path >>> dc.config.get_default_configfile_path() # doctest: +SKIP '/home/mary/.config/dwave/dwave.conf' """ base = homebase.user_config_dir( app_author=CONF_AUTHOR, app_name=CONF_APP, roaming=False, use_virtualenv=False, create=False) path = os.path.join(base, CONF_FILENAME) return path
[ "def", "get_default_configfile_path", "(", ")", ":", "base", "=", "homebase", ".", "user_config_dir", "(", "app_author", "=", "CONF_AUTHOR", ",", "app_name", "=", "CONF_APP", ",", "roaming", "=", "False", ",", "use_virtualenv", "=", "False", ",", "create", "=", "False", ")", "path", "=", "os", ".", "path", ".", "join", "(", "base", ",", "CONF_FILENAME", ")", "return", "path" ]
Return the default configuration-file path. Typically returns a user-local configuration file; e.g: ``~/.config/dwave/dwave.conf``. Returns: str: Configuration file path. Examples: This example displays the default configuration file on an Ubuntu Unix system running IPython 2.7. >>> import dwave.cloud as dc >>> # Display paths >>> dc.config.get_configfile_paths(only_existing=False) # doctest: +SKIP ['/etc/xdg/xdg-ubuntu/dwave/dwave.conf', '/usr/share/upstart/xdg/dwave/dwave.conf', '/etc/xdg/dwave/dwave.conf', '/home/mary/.config/dwave/dwave.conf', './dwave.conf'] >>> # Find default configuration path >>> dc.config.get_default_configfile_path() # doctest: +SKIP '/home/mary/.config/dwave/dwave.conf'
[ "Return", "the", "default", "configuration", "-", "file", "path", "." ]
df3221a8385dc0c04d7b4d84f740bf3ad6706230
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/config.py#L336-L367
train
dwavesystems/dwave-cloud-client
dwave/cloud/config.py
load_config_from_files
def load_config_from_files(filenames=None): """Load D-Wave Cloud Client configuration from a list of files. .. note:: This method is not standardly used to set up D-Wave Cloud Client configuration. It is recommended you use :meth:`.Client.from_config` or :meth:`.config.load_config` instead. Configuration files comply with standard Windows INI-like format, parsable with Python's :mod:`configparser`. A section called ``defaults`` contains default values inherited by other sections. Each filename in the list (each configuration file loaded) progressively upgrades the final configuration, on a key by key basis, per each section. Args: filenames (list[str], default=None): D-Wave Cloud Client configuration files (paths and names). If ``None``, searches for a configuration file named ``dwave.conf`` in all system-wide configuration directories, in the user-local configuration directory, and in the current working directory, following the user/system configuration paths of :func:`get_configfile_paths`. Returns: :obj:`~configparser.ConfigParser`: :class:`dict`-like mapping of configuration sections (profiles) to mapping of per-profile keys holding values. Raises: :exc:`~dwave.cloud.exceptions.ConfigFileReadError`: Config file specified or detected could not be opened or read. :exc:`~dwave.cloud.exceptions.ConfigFileParseError`: Config file parse failed. Examples: This example loads configurations from two files. One contains a default section with key/values that are overwritten by any profile section that contains that key/value; for example, profile dw2000b in file dwave_b.conf overwrites the default URL and client type, which profile dw2000a inherits from the defaults section, while profile dw2000a overwrites the API token that profile dw2000b inherits. The files, which are located in the current working directory, are (1) dwave_a.conf:: [defaults] endpoint = https://url.of.some.dwavesystem.com/sapi client = qpu token = ABC-123456789123456789123456789 [dw2000a] solver = EXAMPLE_2000Q_SYSTEM token = DEF-987654321987654321987654321 and (2) dwave_b.conf:: [dw2000b] endpoint = https://url.of.some.other.dwavesystem.com/sapi client = sw solver = EXAMPLE_2000Q_SYSTEM The following example code loads configuration from both these files, with the defined overrides and inheritance. .. code:: python >>> import dwave.cloud as dc >>> import sys >>> configuration = dc.config.load_config_from_files(["./dwave_a.conf", "./dwave_b.conf"]) # doctest: +SKIP >>> configuration.write(sys.stdout) # doctest: +SKIP [defaults] endpoint = https://url.of.some.dwavesystem.com/sapi client = qpu token = ABC-123456789123456789123456789 [dw2000a] solver = EXAMPLE_2000Q_SYSTEM token = DEF-987654321987654321987654321 [dw2000b] endpoint = https://url.of.some.other.dwavesystem.com/sapi client = sw solver = EXAMPLE_2000Q_SYSTEM """ if filenames is None: filenames = get_configfile_paths() config = configparser.ConfigParser(default_section="defaults") for filename in filenames: try: with open(filename, 'r') as f: config.read_file(f, filename) except (IOError, OSError): raise ConfigFileReadError("Failed to read {!r}".format(filename)) except configparser.Error: raise ConfigFileParseError("Failed to parse {!r}".format(filename)) return config
python
def load_config_from_files(filenames=None): """Load D-Wave Cloud Client configuration from a list of files. .. note:: This method is not standardly used to set up D-Wave Cloud Client configuration. It is recommended you use :meth:`.Client.from_config` or :meth:`.config.load_config` instead. Configuration files comply with standard Windows INI-like format, parsable with Python's :mod:`configparser`. A section called ``defaults`` contains default values inherited by other sections. Each filename in the list (each configuration file loaded) progressively upgrades the final configuration, on a key by key basis, per each section. Args: filenames (list[str], default=None): D-Wave Cloud Client configuration files (paths and names). If ``None``, searches for a configuration file named ``dwave.conf`` in all system-wide configuration directories, in the user-local configuration directory, and in the current working directory, following the user/system configuration paths of :func:`get_configfile_paths`. Returns: :obj:`~configparser.ConfigParser`: :class:`dict`-like mapping of configuration sections (profiles) to mapping of per-profile keys holding values. Raises: :exc:`~dwave.cloud.exceptions.ConfigFileReadError`: Config file specified or detected could not be opened or read. :exc:`~dwave.cloud.exceptions.ConfigFileParseError`: Config file parse failed. Examples: This example loads configurations from two files. One contains a default section with key/values that are overwritten by any profile section that contains that key/value; for example, profile dw2000b in file dwave_b.conf overwrites the default URL and client type, which profile dw2000a inherits from the defaults section, while profile dw2000a overwrites the API token that profile dw2000b inherits. The files, which are located in the current working directory, are (1) dwave_a.conf:: [defaults] endpoint = https://url.of.some.dwavesystem.com/sapi client = qpu token = ABC-123456789123456789123456789 [dw2000a] solver = EXAMPLE_2000Q_SYSTEM token = DEF-987654321987654321987654321 and (2) dwave_b.conf:: [dw2000b] endpoint = https://url.of.some.other.dwavesystem.com/sapi client = sw solver = EXAMPLE_2000Q_SYSTEM The following example code loads configuration from both these files, with the defined overrides and inheritance. .. code:: python >>> import dwave.cloud as dc >>> import sys >>> configuration = dc.config.load_config_from_files(["./dwave_a.conf", "./dwave_b.conf"]) # doctest: +SKIP >>> configuration.write(sys.stdout) # doctest: +SKIP [defaults] endpoint = https://url.of.some.dwavesystem.com/sapi client = qpu token = ABC-123456789123456789123456789 [dw2000a] solver = EXAMPLE_2000Q_SYSTEM token = DEF-987654321987654321987654321 [dw2000b] endpoint = https://url.of.some.other.dwavesystem.com/sapi client = sw solver = EXAMPLE_2000Q_SYSTEM """ if filenames is None: filenames = get_configfile_paths() config = configparser.ConfigParser(default_section="defaults") for filename in filenames: try: with open(filename, 'r') as f: config.read_file(f, filename) except (IOError, OSError): raise ConfigFileReadError("Failed to read {!r}".format(filename)) except configparser.Error: raise ConfigFileParseError("Failed to parse {!r}".format(filename)) return config
[ "def", "load_config_from_files", "(", "filenames", "=", "None", ")", ":", "if", "filenames", "is", "None", ":", "filenames", "=", "get_configfile_paths", "(", ")", "config", "=", "configparser", ".", "ConfigParser", "(", "default_section", "=", "\"defaults\"", ")", "for", "filename", "in", "filenames", ":", "try", ":", "with", "open", "(", "filename", ",", "'r'", ")", "as", "f", ":", "config", ".", "read_file", "(", "f", ",", "filename", ")", "except", "(", "IOError", ",", "OSError", ")", ":", "raise", "ConfigFileReadError", "(", "\"Failed to read {!r}\"", ".", "format", "(", "filename", ")", ")", "except", "configparser", ".", "Error", ":", "raise", "ConfigFileParseError", "(", "\"Failed to parse {!r}\"", ".", "format", "(", "filename", ")", ")", "return", "config" ]
Load D-Wave Cloud Client configuration from a list of files. .. note:: This method is not standardly used to set up D-Wave Cloud Client configuration. It is recommended you use :meth:`.Client.from_config` or :meth:`.config.load_config` instead. Configuration files comply with standard Windows INI-like format, parsable with Python's :mod:`configparser`. A section called ``defaults`` contains default values inherited by other sections. Each filename in the list (each configuration file loaded) progressively upgrades the final configuration, on a key by key basis, per each section. Args: filenames (list[str], default=None): D-Wave Cloud Client configuration files (paths and names). If ``None``, searches for a configuration file named ``dwave.conf`` in all system-wide configuration directories, in the user-local configuration directory, and in the current working directory, following the user/system configuration paths of :func:`get_configfile_paths`. Returns: :obj:`~configparser.ConfigParser`: :class:`dict`-like mapping of configuration sections (profiles) to mapping of per-profile keys holding values. Raises: :exc:`~dwave.cloud.exceptions.ConfigFileReadError`: Config file specified or detected could not be opened or read. :exc:`~dwave.cloud.exceptions.ConfigFileParseError`: Config file parse failed. Examples: This example loads configurations from two files. One contains a default section with key/values that are overwritten by any profile section that contains that key/value; for example, profile dw2000b in file dwave_b.conf overwrites the default URL and client type, which profile dw2000a inherits from the defaults section, while profile dw2000a overwrites the API token that profile dw2000b inherits. The files, which are located in the current working directory, are (1) dwave_a.conf:: [defaults] endpoint = https://url.of.some.dwavesystem.com/sapi client = qpu token = ABC-123456789123456789123456789 [dw2000a] solver = EXAMPLE_2000Q_SYSTEM token = DEF-987654321987654321987654321 and (2) dwave_b.conf:: [dw2000b] endpoint = https://url.of.some.other.dwavesystem.com/sapi client = sw solver = EXAMPLE_2000Q_SYSTEM The following example code loads configuration from both these files, with the defined overrides and inheritance. .. code:: python >>> import dwave.cloud as dc >>> import sys >>> configuration = dc.config.load_config_from_files(["./dwave_a.conf", "./dwave_b.conf"]) # doctest: +SKIP >>> configuration.write(sys.stdout) # doctest: +SKIP [defaults] endpoint = https://url.of.some.dwavesystem.com/sapi client = qpu token = ABC-123456789123456789123456789 [dw2000a] solver = EXAMPLE_2000Q_SYSTEM token = DEF-987654321987654321987654321 [dw2000b] endpoint = https://url.of.some.other.dwavesystem.com/sapi client = sw solver = EXAMPLE_2000Q_SYSTEM
[ "Load", "D", "-", "Wave", "Cloud", "Client", "configuration", "from", "a", "list", "of", "files", "." ]
df3221a8385dc0c04d7b4d84f740bf3ad6706230
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/config.py#L370-L468
train
dwavesystems/dwave-cloud-client
dwave/cloud/config.py
load_profile_from_files
def load_profile_from_files(filenames=None, profile=None): """Load a profile from a list of D-Wave Cloud Client configuration files. .. note:: This method is not standardly used to set up D-Wave Cloud Client configuration. It is recommended you use :meth:`.Client.from_config` or :meth:`.config.load_config` instead. Configuration files comply with standard Windows INI-like format, parsable with Python's :mod:`configparser`. Each file in the list is progressively searched until the first profile is found. This function does not input profile information from environment variables. Args: filenames (list[str], default=None): D-Wave cloud client configuration files (path and name). If ``None``, searches for existing configuration files in the standard directories of :func:`get_configfile_paths`. profile (str, default=None): Name of profile to return from reading the configuration from the specified configuration file(s). If ``None``, progressively falls back in the following order: (1) ``profile`` key following ``[defaults]`` section. (2) First non-``[defaults]`` section. (3) ``[defaults]`` section. Returns: dict: Mapping of configuration keys to values. If no valid config/profile is found, returns an empty dict. Raises: :exc:`~dwave.cloud.exceptions.ConfigFileReadError`: Config file specified or detected could not be opened or read. :exc:`~dwave.cloud.exceptions.ConfigFileParseError`: Config file parse failed. :exc:`ValueError`: Profile name not found. Examples: This example loads a profile based on configurations from two files. It finds the first profile, dw2000a, in the first file, dwave_a.conf, and adds to the values of the defaults section, overwriting the existing client value, while ignoring the profile in the second file, dwave_b.conf. The files, which are located in the current working directory, are (1) dwave_a.conf:: [defaults] endpoint = https://url.of.some.dwavesystem.com/sapi client = qpu token = ABC-123456789123456789123456789 [dw2000a] client = sw solver = EXAMPLE_2000Q_SYSTEM_A token = DEF-987654321987654321987654321 and (2) dwave_b.conf:: [dw2000b] endpoint = https://url.of.some.other.dwavesystem.com/sapi client = qpu solver = EXAMPLE_2000Q_SYSTEM_B The following example code loads profile values from parsing both these files, by default loading the first profile encountered or an explicitly specified profile. >>> import dwave.cloud as dc >>> dc.config.load_profile_from_files(["./dwave_a.conf", "./dwave_b.conf"]) # doctest: +SKIP {'client': u'sw', 'endpoint': u'https://url.of.some.dwavesystem.com/sapi', 'solver': u'EXAMPLE_2000Q_SYSTEM_A', 'token': u'DEF-987654321987654321987654321'} >>> dc.config.load_profile_from_files(["./dwave_a.conf", "./dwave_b.conf"], ... profile='dw2000b') # doctest: +SKIP {'client': u'qpu', 'endpoint': u'https://url.of.some.other.dwavesystem.com/sapi', 'solver': u'EXAMPLE_2000Q_SYSTEM_B', 'token': u'ABC-123456789123456789123456789'} """ # progressively build config from a file, or a list of auto-detected files # raises ConfigFileReadError/ConfigFileParseError on error config = load_config_from_files(filenames) # determine profile name fallback: # (1) profile key under [defaults], # (2) first non-[defaults] section # (3) [defaults] section first_section = next(iter(config.sections() + [None])) config_defaults = config.defaults() if not profile: profile = config_defaults.get('profile', first_section) if profile: try: section = dict(config[profile]) except KeyError: raise ValueError("Config profile {!r} not found".format(profile)) else: # as the very last resort (unspecified profile name and # no profiles defined in config), try to use [defaults] if config_defaults: section = config_defaults else: section = {} return section
python
def load_profile_from_files(filenames=None, profile=None): """Load a profile from a list of D-Wave Cloud Client configuration files. .. note:: This method is not standardly used to set up D-Wave Cloud Client configuration. It is recommended you use :meth:`.Client.from_config` or :meth:`.config.load_config` instead. Configuration files comply with standard Windows INI-like format, parsable with Python's :mod:`configparser`. Each file in the list is progressively searched until the first profile is found. This function does not input profile information from environment variables. Args: filenames (list[str], default=None): D-Wave cloud client configuration files (path and name). If ``None``, searches for existing configuration files in the standard directories of :func:`get_configfile_paths`. profile (str, default=None): Name of profile to return from reading the configuration from the specified configuration file(s). If ``None``, progressively falls back in the following order: (1) ``profile`` key following ``[defaults]`` section. (2) First non-``[defaults]`` section. (3) ``[defaults]`` section. Returns: dict: Mapping of configuration keys to values. If no valid config/profile is found, returns an empty dict. Raises: :exc:`~dwave.cloud.exceptions.ConfigFileReadError`: Config file specified or detected could not be opened or read. :exc:`~dwave.cloud.exceptions.ConfigFileParseError`: Config file parse failed. :exc:`ValueError`: Profile name not found. Examples: This example loads a profile based on configurations from two files. It finds the first profile, dw2000a, in the first file, dwave_a.conf, and adds to the values of the defaults section, overwriting the existing client value, while ignoring the profile in the second file, dwave_b.conf. The files, which are located in the current working directory, are (1) dwave_a.conf:: [defaults] endpoint = https://url.of.some.dwavesystem.com/sapi client = qpu token = ABC-123456789123456789123456789 [dw2000a] client = sw solver = EXAMPLE_2000Q_SYSTEM_A token = DEF-987654321987654321987654321 and (2) dwave_b.conf:: [dw2000b] endpoint = https://url.of.some.other.dwavesystem.com/sapi client = qpu solver = EXAMPLE_2000Q_SYSTEM_B The following example code loads profile values from parsing both these files, by default loading the first profile encountered or an explicitly specified profile. >>> import dwave.cloud as dc >>> dc.config.load_profile_from_files(["./dwave_a.conf", "./dwave_b.conf"]) # doctest: +SKIP {'client': u'sw', 'endpoint': u'https://url.of.some.dwavesystem.com/sapi', 'solver': u'EXAMPLE_2000Q_SYSTEM_A', 'token': u'DEF-987654321987654321987654321'} >>> dc.config.load_profile_from_files(["./dwave_a.conf", "./dwave_b.conf"], ... profile='dw2000b') # doctest: +SKIP {'client': u'qpu', 'endpoint': u'https://url.of.some.other.dwavesystem.com/sapi', 'solver': u'EXAMPLE_2000Q_SYSTEM_B', 'token': u'ABC-123456789123456789123456789'} """ # progressively build config from a file, or a list of auto-detected files # raises ConfigFileReadError/ConfigFileParseError on error config = load_config_from_files(filenames) # determine profile name fallback: # (1) profile key under [defaults], # (2) first non-[defaults] section # (3) [defaults] section first_section = next(iter(config.sections() + [None])) config_defaults = config.defaults() if not profile: profile = config_defaults.get('profile', first_section) if profile: try: section = dict(config[profile]) except KeyError: raise ValueError("Config profile {!r} not found".format(profile)) else: # as the very last resort (unspecified profile name and # no profiles defined in config), try to use [defaults] if config_defaults: section = config_defaults else: section = {} return section
[ "def", "load_profile_from_files", "(", "filenames", "=", "None", ",", "profile", "=", "None", ")", ":", "# progressively build config from a file, or a list of auto-detected files", "# raises ConfigFileReadError/ConfigFileParseError on error", "config", "=", "load_config_from_files", "(", "filenames", ")", "# determine profile name fallback:", "# (1) profile key under [defaults],", "# (2) first non-[defaults] section", "# (3) [defaults] section", "first_section", "=", "next", "(", "iter", "(", "config", ".", "sections", "(", ")", "+", "[", "None", "]", ")", ")", "config_defaults", "=", "config", ".", "defaults", "(", ")", "if", "not", "profile", ":", "profile", "=", "config_defaults", ".", "get", "(", "'profile'", ",", "first_section", ")", "if", "profile", ":", "try", ":", "section", "=", "dict", "(", "config", "[", "profile", "]", ")", "except", "KeyError", ":", "raise", "ValueError", "(", "\"Config profile {!r} not found\"", ".", "format", "(", "profile", ")", ")", "else", ":", "# as the very last resort (unspecified profile name and", "# no profiles defined in config), try to use [defaults]", "if", "config_defaults", ":", "section", "=", "config_defaults", "else", ":", "section", "=", "{", "}", "return", "section" ]
Load a profile from a list of D-Wave Cloud Client configuration files. .. note:: This method is not standardly used to set up D-Wave Cloud Client configuration. It is recommended you use :meth:`.Client.from_config` or :meth:`.config.load_config` instead. Configuration files comply with standard Windows INI-like format, parsable with Python's :mod:`configparser`. Each file in the list is progressively searched until the first profile is found. This function does not input profile information from environment variables. Args: filenames (list[str], default=None): D-Wave cloud client configuration files (path and name). If ``None``, searches for existing configuration files in the standard directories of :func:`get_configfile_paths`. profile (str, default=None): Name of profile to return from reading the configuration from the specified configuration file(s). If ``None``, progressively falls back in the following order: (1) ``profile`` key following ``[defaults]`` section. (2) First non-``[defaults]`` section. (3) ``[defaults]`` section. Returns: dict: Mapping of configuration keys to values. If no valid config/profile is found, returns an empty dict. Raises: :exc:`~dwave.cloud.exceptions.ConfigFileReadError`: Config file specified or detected could not be opened or read. :exc:`~dwave.cloud.exceptions.ConfigFileParseError`: Config file parse failed. :exc:`ValueError`: Profile name not found. Examples: This example loads a profile based on configurations from two files. It finds the first profile, dw2000a, in the first file, dwave_a.conf, and adds to the values of the defaults section, overwriting the existing client value, while ignoring the profile in the second file, dwave_b.conf. The files, which are located in the current working directory, are (1) dwave_a.conf:: [defaults] endpoint = https://url.of.some.dwavesystem.com/sapi client = qpu token = ABC-123456789123456789123456789 [dw2000a] client = sw solver = EXAMPLE_2000Q_SYSTEM_A token = DEF-987654321987654321987654321 and (2) dwave_b.conf:: [dw2000b] endpoint = https://url.of.some.other.dwavesystem.com/sapi client = qpu solver = EXAMPLE_2000Q_SYSTEM_B The following example code loads profile values from parsing both these files, by default loading the first profile encountered or an explicitly specified profile. >>> import dwave.cloud as dc >>> dc.config.load_profile_from_files(["./dwave_a.conf", "./dwave_b.conf"]) # doctest: +SKIP {'client': u'sw', 'endpoint': u'https://url.of.some.dwavesystem.com/sapi', 'solver': u'EXAMPLE_2000Q_SYSTEM_A', 'token': u'DEF-987654321987654321987654321'} >>> dc.config.load_profile_from_files(["./dwave_a.conf", "./dwave_b.conf"], ... profile='dw2000b') # doctest: +SKIP {'client': u'qpu', 'endpoint': u'https://url.of.some.other.dwavesystem.com/sapi', 'solver': u'EXAMPLE_2000Q_SYSTEM_B', 'token': u'ABC-123456789123456789123456789'}
[ "Load", "a", "profile", "from", "a", "list", "of", "D", "-", "Wave", "Cloud", "Client", "configuration", "files", "." ]
df3221a8385dc0c04d7b4d84f740bf3ad6706230
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/config.py#L471-L584
train
dwavesystems/dwave-cloud-client
dwave/cloud/config.py
load_config
def load_config(config_file=None, profile=None, client=None, endpoint=None, token=None, solver=None, proxy=None): """Load D-Wave Cloud Client configuration based on a configuration file. Configuration values can be specified in multiple ways, ranked in the following order (with 1 the highest ranked): 1. Values specified as keyword arguments in :func:`load_config()`. These values replace values read from a configuration file, and therefore must be **strings**, including float values for timeouts, boolean flags (tested for "truthiness"), and solver feature constraints (a dictionary encoded as JSON). 2. Values specified as environment variables. 3. Values specified in the configuration file. Configuration-file format is described in :mod:`dwave.cloud.config`. If the location of the configuration file is not specified, auto-detection searches for existing configuration files in the standard directories of :func:`get_configfile_paths`. If a configuration file explicitly specified, via an argument or environment variable, does not exist or is unreadable, loading fails with :exc:`~dwave.cloud.exceptions.ConfigFileReadError`. Loading fails with :exc:`~dwave.cloud.exceptions.ConfigFileParseError` if the file is readable but invalid as a configuration file. Similarly, if a profile explicitly specified, via an argument or environment variable, is not present in the loaded configuration, loading fails with :exc:`ValueError`. Explicit profile selection also fails if the configuration file is not explicitly specified, detected on the system, or defined via an environment variable. Environment variables: ``DWAVE_CONFIG_FILE``, ``DWAVE_PROFILE``, ``DWAVE_API_CLIENT``, ``DWAVE_API_ENDPOINT``, ``DWAVE_API_TOKEN``, ``DWAVE_API_SOLVER``, ``DWAVE_API_PROXY``. Environment variables are described in :mod:`dwave.cloud.config`. Args: config_file (str/[str]/None/False/True, default=None): Path to configuration file(s). If `None`, the value is taken from `DWAVE_CONFIG_FILE` environment variable if defined. If the environment variable is undefined or empty, auto-detection searches for existing configuration files in the standard directories of :func:`get_configfile_paths`. If `False`, loading from file(s) is skipped; if `True`, forces auto-detection (regardless of the `DWAVE_CONFIG_FILE` environment variable). profile (str, default=None): Profile name (name of the profile section in the configuration file). If undefined, inferred from `DWAVE_PROFILE` environment variable if defined. If the environment variable is undefined or empty, a profile is selected in the following order: 1. From the default section if it includes a profile key. 2. The first section (after the default section). 3. If no other section is defined besides `[defaults]`, the defaults section is promoted and selected. client (str, default=None): Client type used for accessing the API. Supported values are `qpu` for :class:`dwave.cloud.qpu.Client` and `sw` for :class:`dwave.cloud.sw.Client`. endpoint (str, default=None): API endpoint URL. token (str, default=None): API authorization token. solver (str, default=None): :term:`solver` features, as a JSON-encoded dictionary of feature constraints, the client should use. See :meth:`~dwave.cloud.client.Client.get_solvers` for semantics of supported feature constraints. If undefined, the client uses a solver definition from environment variables, a configuration file, or falls back to the first available online solver. For backward compatibility, solver name in string format is accepted and converted to ``{"name": <solver name>}``. proxy (str, default=None): URL for proxy to use in connections to D-Wave API. Can include username/password, port, scheme, etc. If undefined, client uses the system-level proxy, if defined, or connects directly to the API. Returns: dict: Mapping of configuration keys to values for the profile (section), as read from the configuration file and optionally overridden by environment values and specified keyword arguments. Always contains the `client`, `endpoint`, `token`, `solver`, and `proxy` keys. Raises: :exc:`ValueError`: Invalid (non-existing) profile name. :exc:`~dwave.cloud.exceptions.ConfigFileReadError`: Config file specified or detected could not be opened or read. :exc:`~dwave.cloud.exceptions.ConfigFileParseError`: Config file parse failed. Examples This example loads the configuration from an auto-detected configuration file in the home directory of a Windows system user. >>> import dwave.cloud as dc >>> dc.config.load_config() {'client': u'qpu', 'endpoint': u'https://url.of.some.dwavesystem.com/sapi', 'proxy': None, 'solver': u'EXAMPLE_2000Q_SYSTEM_A', 'token': u'DEF-987654321987654321987654321'} >>> See which configuration file was loaded >>> dc.config.get_configfile_paths() [u'C:\\Users\\jane\\AppData\\Local\\dwavesystem\\dwave\\dwave.conf'] Additional examples are given in :mod:`dwave.cloud.config`. """ if profile is None: profile = os.getenv("DWAVE_PROFILE") if config_file == False: # skip loading from file altogether section = {} elif config_file == True: # force auto-detection, disregarding DWAVE_CONFIG_FILE section = load_profile_from_files(None, profile) else: # auto-detect if not specified with arg or env if config_file is None: # note: both empty and undefined DWAVE_CONFIG_FILE treated as None config_file = os.getenv("DWAVE_CONFIG_FILE") # handle ''/None/str/[str] for `config_file` (after env) filenames = None if config_file: if isinstance(config_file, six.string_types): filenames = [config_file] else: filenames = config_file section = load_profile_from_files(filenames, profile) # override a selected subset of values via env or kwargs, # pass-through the rest unmodified section['client'] = client or os.getenv("DWAVE_API_CLIENT", section.get('client')) section['endpoint'] = endpoint or os.getenv("DWAVE_API_ENDPOINT", section.get('endpoint')) section['token'] = token or os.getenv("DWAVE_API_TOKEN", section.get('token')) section['solver'] = solver or os.getenv("DWAVE_API_SOLVER", section.get('solver')) section['proxy'] = proxy or os.getenv("DWAVE_API_PROXY", section.get('proxy')) return section
python
def load_config(config_file=None, profile=None, client=None, endpoint=None, token=None, solver=None, proxy=None): """Load D-Wave Cloud Client configuration based on a configuration file. Configuration values can be specified in multiple ways, ranked in the following order (with 1 the highest ranked): 1. Values specified as keyword arguments in :func:`load_config()`. These values replace values read from a configuration file, and therefore must be **strings**, including float values for timeouts, boolean flags (tested for "truthiness"), and solver feature constraints (a dictionary encoded as JSON). 2. Values specified as environment variables. 3. Values specified in the configuration file. Configuration-file format is described in :mod:`dwave.cloud.config`. If the location of the configuration file is not specified, auto-detection searches for existing configuration files in the standard directories of :func:`get_configfile_paths`. If a configuration file explicitly specified, via an argument or environment variable, does not exist or is unreadable, loading fails with :exc:`~dwave.cloud.exceptions.ConfigFileReadError`. Loading fails with :exc:`~dwave.cloud.exceptions.ConfigFileParseError` if the file is readable but invalid as a configuration file. Similarly, if a profile explicitly specified, via an argument or environment variable, is not present in the loaded configuration, loading fails with :exc:`ValueError`. Explicit profile selection also fails if the configuration file is not explicitly specified, detected on the system, or defined via an environment variable. Environment variables: ``DWAVE_CONFIG_FILE``, ``DWAVE_PROFILE``, ``DWAVE_API_CLIENT``, ``DWAVE_API_ENDPOINT``, ``DWAVE_API_TOKEN``, ``DWAVE_API_SOLVER``, ``DWAVE_API_PROXY``. Environment variables are described in :mod:`dwave.cloud.config`. Args: config_file (str/[str]/None/False/True, default=None): Path to configuration file(s). If `None`, the value is taken from `DWAVE_CONFIG_FILE` environment variable if defined. If the environment variable is undefined or empty, auto-detection searches for existing configuration files in the standard directories of :func:`get_configfile_paths`. If `False`, loading from file(s) is skipped; if `True`, forces auto-detection (regardless of the `DWAVE_CONFIG_FILE` environment variable). profile (str, default=None): Profile name (name of the profile section in the configuration file). If undefined, inferred from `DWAVE_PROFILE` environment variable if defined. If the environment variable is undefined or empty, a profile is selected in the following order: 1. From the default section if it includes a profile key. 2. The first section (after the default section). 3. If no other section is defined besides `[defaults]`, the defaults section is promoted and selected. client (str, default=None): Client type used for accessing the API. Supported values are `qpu` for :class:`dwave.cloud.qpu.Client` and `sw` for :class:`dwave.cloud.sw.Client`. endpoint (str, default=None): API endpoint URL. token (str, default=None): API authorization token. solver (str, default=None): :term:`solver` features, as a JSON-encoded dictionary of feature constraints, the client should use. See :meth:`~dwave.cloud.client.Client.get_solvers` for semantics of supported feature constraints. If undefined, the client uses a solver definition from environment variables, a configuration file, or falls back to the first available online solver. For backward compatibility, solver name in string format is accepted and converted to ``{"name": <solver name>}``. proxy (str, default=None): URL for proxy to use in connections to D-Wave API. Can include username/password, port, scheme, etc. If undefined, client uses the system-level proxy, if defined, or connects directly to the API. Returns: dict: Mapping of configuration keys to values for the profile (section), as read from the configuration file and optionally overridden by environment values and specified keyword arguments. Always contains the `client`, `endpoint`, `token`, `solver`, and `proxy` keys. Raises: :exc:`ValueError`: Invalid (non-existing) profile name. :exc:`~dwave.cloud.exceptions.ConfigFileReadError`: Config file specified or detected could not be opened or read. :exc:`~dwave.cloud.exceptions.ConfigFileParseError`: Config file parse failed. Examples This example loads the configuration from an auto-detected configuration file in the home directory of a Windows system user. >>> import dwave.cloud as dc >>> dc.config.load_config() {'client': u'qpu', 'endpoint': u'https://url.of.some.dwavesystem.com/sapi', 'proxy': None, 'solver': u'EXAMPLE_2000Q_SYSTEM_A', 'token': u'DEF-987654321987654321987654321'} >>> See which configuration file was loaded >>> dc.config.get_configfile_paths() [u'C:\\Users\\jane\\AppData\\Local\\dwavesystem\\dwave\\dwave.conf'] Additional examples are given in :mod:`dwave.cloud.config`. """ if profile is None: profile = os.getenv("DWAVE_PROFILE") if config_file == False: # skip loading from file altogether section = {} elif config_file == True: # force auto-detection, disregarding DWAVE_CONFIG_FILE section = load_profile_from_files(None, profile) else: # auto-detect if not specified with arg or env if config_file is None: # note: both empty and undefined DWAVE_CONFIG_FILE treated as None config_file = os.getenv("DWAVE_CONFIG_FILE") # handle ''/None/str/[str] for `config_file` (after env) filenames = None if config_file: if isinstance(config_file, six.string_types): filenames = [config_file] else: filenames = config_file section = load_profile_from_files(filenames, profile) # override a selected subset of values via env or kwargs, # pass-through the rest unmodified section['client'] = client or os.getenv("DWAVE_API_CLIENT", section.get('client')) section['endpoint'] = endpoint or os.getenv("DWAVE_API_ENDPOINT", section.get('endpoint')) section['token'] = token or os.getenv("DWAVE_API_TOKEN", section.get('token')) section['solver'] = solver or os.getenv("DWAVE_API_SOLVER", section.get('solver')) section['proxy'] = proxy or os.getenv("DWAVE_API_PROXY", section.get('proxy')) return section
[ "def", "load_config", "(", "config_file", "=", "None", ",", "profile", "=", "None", ",", "client", "=", "None", ",", "endpoint", "=", "None", ",", "token", "=", "None", ",", "solver", "=", "None", ",", "proxy", "=", "None", ")", ":", "if", "profile", "is", "None", ":", "profile", "=", "os", ".", "getenv", "(", "\"DWAVE_PROFILE\"", ")", "if", "config_file", "==", "False", ":", "# skip loading from file altogether", "section", "=", "{", "}", "elif", "config_file", "==", "True", ":", "# force auto-detection, disregarding DWAVE_CONFIG_FILE", "section", "=", "load_profile_from_files", "(", "None", ",", "profile", ")", "else", ":", "# auto-detect if not specified with arg or env", "if", "config_file", "is", "None", ":", "# note: both empty and undefined DWAVE_CONFIG_FILE treated as None", "config_file", "=", "os", ".", "getenv", "(", "\"DWAVE_CONFIG_FILE\"", ")", "# handle ''/None/str/[str] for `config_file` (after env)", "filenames", "=", "None", "if", "config_file", ":", "if", "isinstance", "(", "config_file", ",", "six", ".", "string_types", ")", ":", "filenames", "=", "[", "config_file", "]", "else", ":", "filenames", "=", "config_file", "section", "=", "load_profile_from_files", "(", "filenames", ",", "profile", ")", "# override a selected subset of values via env or kwargs,", "# pass-through the rest unmodified", "section", "[", "'client'", "]", "=", "client", "or", "os", ".", "getenv", "(", "\"DWAVE_API_CLIENT\"", ",", "section", ".", "get", "(", "'client'", ")", ")", "section", "[", "'endpoint'", "]", "=", "endpoint", "or", "os", ".", "getenv", "(", "\"DWAVE_API_ENDPOINT\"", ",", "section", ".", "get", "(", "'endpoint'", ")", ")", "section", "[", "'token'", "]", "=", "token", "or", "os", ".", "getenv", "(", "\"DWAVE_API_TOKEN\"", ",", "section", ".", "get", "(", "'token'", ")", ")", "section", "[", "'solver'", "]", "=", "solver", "or", "os", ".", "getenv", "(", "\"DWAVE_API_SOLVER\"", ",", "section", ".", "get", "(", "'solver'", ")", ")", "section", "[", "'proxy'", "]", "=", "proxy", "or", "os", ".", "getenv", "(", "\"DWAVE_API_PROXY\"", ",", "section", ".", "get", "(", "'proxy'", ")", ")", "return", "section" ]
Load D-Wave Cloud Client configuration based on a configuration file. Configuration values can be specified in multiple ways, ranked in the following order (with 1 the highest ranked): 1. Values specified as keyword arguments in :func:`load_config()`. These values replace values read from a configuration file, and therefore must be **strings**, including float values for timeouts, boolean flags (tested for "truthiness"), and solver feature constraints (a dictionary encoded as JSON). 2. Values specified as environment variables. 3. Values specified in the configuration file. Configuration-file format is described in :mod:`dwave.cloud.config`. If the location of the configuration file is not specified, auto-detection searches for existing configuration files in the standard directories of :func:`get_configfile_paths`. If a configuration file explicitly specified, via an argument or environment variable, does not exist or is unreadable, loading fails with :exc:`~dwave.cloud.exceptions.ConfigFileReadError`. Loading fails with :exc:`~dwave.cloud.exceptions.ConfigFileParseError` if the file is readable but invalid as a configuration file. Similarly, if a profile explicitly specified, via an argument or environment variable, is not present in the loaded configuration, loading fails with :exc:`ValueError`. Explicit profile selection also fails if the configuration file is not explicitly specified, detected on the system, or defined via an environment variable. Environment variables: ``DWAVE_CONFIG_FILE``, ``DWAVE_PROFILE``, ``DWAVE_API_CLIENT``, ``DWAVE_API_ENDPOINT``, ``DWAVE_API_TOKEN``, ``DWAVE_API_SOLVER``, ``DWAVE_API_PROXY``. Environment variables are described in :mod:`dwave.cloud.config`. Args: config_file (str/[str]/None/False/True, default=None): Path to configuration file(s). If `None`, the value is taken from `DWAVE_CONFIG_FILE` environment variable if defined. If the environment variable is undefined or empty, auto-detection searches for existing configuration files in the standard directories of :func:`get_configfile_paths`. If `False`, loading from file(s) is skipped; if `True`, forces auto-detection (regardless of the `DWAVE_CONFIG_FILE` environment variable). profile (str, default=None): Profile name (name of the profile section in the configuration file). If undefined, inferred from `DWAVE_PROFILE` environment variable if defined. If the environment variable is undefined or empty, a profile is selected in the following order: 1. From the default section if it includes a profile key. 2. The first section (after the default section). 3. If no other section is defined besides `[defaults]`, the defaults section is promoted and selected. client (str, default=None): Client type used for accessing the API. Supported values are `qpu` for :class:`dwave.cloud.qpu.Client` and `sw` for :class:`dwave.cloud.sw.Client`. endpoint (str, default=None): API endpoint URL. token (str, default=None): API authorization token. solver (str, default=None): :term:`solver` features, as a JSON-encoded dictionary of feature constraints, the client should use. See :meth:`~dwave.cloud.client.Client.get_solvers` for semantics of supported feature constraints. If undefined, the client uses a solver definition from environment variables, a configuration file, or falls back to the first available online solver. For backward compatibility, solver name in string format is accepted and converted to ``{"name": <solver name>}``. proxy (str, default=None): URL for proxy to use in connections to D-Wave API. Can include username/password, port, scheme, etc. If undefined, client uses the system-level proxy, if defined, or connects directly to the API. Returns: dict: Mapping of configuration keys to values for the profile (section), as read from the configuration file and optionally overridden by environment values and specified keyword arguments. Always contains the `client`, `endpoint`, `token`, `solver`, and `proxy` keys. Raises: :exc:`ValueError`: Invalid (non-existing) profile name. :exc:`~dwave.cloud.exceptions.ConfigFileReadError`: Config file specified or detected could not be opened or read. :exc:`~dwave.cloud.exceptions.ConfigFileParseError`: Config file parse failed. Examples This example loads the configuration from an auto-detected configuration file in the home directory of a Windows system user. >>> import dwave.cloud as dc >>> dc.config.load_config() {'client': u'qpu', 'endpoint': u'https://url.of.some.dwavesystem.com/sapi', 'proxy': None, 'solver': u'EXAMPLE_2000Q_SYSTEM_A', 'token': u'DEF-987654321987654321987654321'} >>> See which configuration file was loaded >>> dc.config.get_configfile_paths() [u'C:\\Users\\jane\\AppData\\Local\\dwavesystem\\dwave\\dwave.conf'] Additional examples are given in :mod:`dwave.cloud.config`.
[ "Load", "D", "-", "Wave", "Cloud", "Client", "configuration", "based", "on", "a", "configuration", "file", "." ]
df3221a8385dc0c04d7b4d84f740bf3ad6706230
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/config.py#L619-L778
train
dwavesystems/dwave-cloud-client
dwave/cloud/config.py
legacy_load_config
def legacy_load_config(profile=None, endpoint=None, token=None, solver=None, proxy=None, **kwargs): """Load configured URLs and token for the SAPI server. .. warning:: Included only for backward compatibility. Please use :func:`load_config` or the client factory :meth:`~dwave.cloud.client.Client.from_config` instead. This method tries to load a legacy configuration file from ``~/.dwrc``, select a specified `profile` (or, if not specified, the first profile), and override individual keys with values read from environment variables or specified explicitly as key values in the function. Configuration values can be specified in multiple ways, ranked in the following order (with 1 the highest ranked): 1. Values specified as keyword arguments in :func:`legacy_load_config()` 2. Values specified as environment variables 3. Values specified in the legacy ``~/.dwrc`` configuration file Environment variables searched for are: - ``DW_INTERNAL__HTTPLINK`` - ``DW_INTERNAL__TOKEN`` - ``DW_INTERNAL__HTTPPROXY`` - ``DW_INTERNAL__SOLVER`` Legacy configuration file format is a modified CSV where the first comma is replaced with a bar character (``|``). Each line encodes a single profile. Its columns are:: profile_name|endpoint_url,authentication_token,proxy_url,default_solver_name All its fields after ``authentication_token`` are optional. When there are multiple connections in a file, the first one is the default. Any commas in the URLs must be percent-encoded. Args: profile (str): Profile name in the legacy configuration file. endpoint (str, default=None): API endpoint URL. token (str, default=None): API authorization token. solver (str, default=None): Default solver to use in :meth:`~dwave.cloud.client.Client.get_solver`. If undefined, all calls to :meth:`~dwave.cloud.client.Client.get_solver` must explicitly specify the solver name/id. proxy (str, default=None): URL for proxy to use in connections to D-Wave API. Can include username/password, port, scheme, etc. If undefined, client uses a system-level proxy, if defined, or connects directly to the API. Returns: Dictionary with keys: endpoint, token, solver, and proxy. Examples: This example creates a client using the :meth:`~dwave.cloud.client.Client.from_config` method, which falls back on the legacy file by default when it fails to find a D-Wave Cloud Client configuration file (setting its `legacy_config_fallback` parameter to False precludes this fall-back operation). For this example, no D-Wave Cloud Client configuration file is present on the local system; instead the following ``.dwrc`` legacy configuration file is present in the user's home directory:: profile-a|https://one.com,token-one profile-b|https://two.com,token-two The following example code creates a client without explicitly specifying key values, therefore auto-detection searches for existing (non-legacy) configuration files in the standard directories of :func:`get_configfile_paths` and, failing to find one, falls back on the existing legacy configuration file above. >>> import dwave.cloud as dc >>> client = dwave.cloud.Client.from_config() # doctest: +SKIP >>> client.endpoint # doctest: +SKIP 'https://one.com' >>> client.token # doctest: +SKIP 'token-one' The following examples specify a profile and/or token. >>> # Explicitly specify a profile >>> client = dwave.cloud.Client.from_config(profile='profile-b') >>> # Will try to connect with the url `https://two.com` and the token `token-two`. >>> client = dwave.cloud.Client.from_config(profile='profile-b', token='new-token') >>> # Will try to connect with the url `https://two.com` and the token `new-token`. """ def _parse_config(fp, filename): fields = ('endpoint', 'token', 'proxy', 'solver') config = OrderedDict() for line in fp: # strip whitespace, skip blank and comment lines line = line.strip() if not line or line.startswith('#'): continue # parse each record, store in dict with label as key try: label, data = line.split('|', 1) values = [v.strip() or None for v in data.split(',')] config[label] = dict(zip(fields, values)) except: raise ConfigFileParseError( "Failed to parse {!r}, line {!r}".format(filename, line)) return config def _read_config(filename): try: with open(filename, 'r') as f: return _parse_config(f, filename) except (IOError, OSError): raise ConfigFileReadError("Failed to read {!r}".format(filename)) config = {} filename = os.path.expanduser('~/.dwrc') if os.path.exists(filename): config = _read_config(filename) # load profile if specified, or first one in file if profile: try: section = config[profile] except KeyError: raise ValueError("Config profile {!r} not found".format(profile)) else: try: _, section = next(iter(config.items())) except StopIteration: section = {} # override config variables (if any) with environment and then with arguments section['endpoint'] = endpoint or os.getenv("DW_INTERNAL__HTTPLINK", section.get('endpoint')) section['token'] = token or os.getenv("DW_INTERNAL__TOKEN", section.get('token')) section['proxy'] = proxy or os.getenv("DW_INTERNAL__HTTPPROXY", section.get('proxy')) section['solver'] = solver or os.getenv("DW_INTERNAL__SOLVER", section.get('solver')) section.update(kwargs) return section
python
def legacy_load_config(profile=None, endpoint=None, token=None, solver=None, proxy=None, **kwargs): """Load configured URLs and token for the SAPI server. .. warning:: Included only for backward compatibility. Please use :func:`load_config` or the client factory :meth:`~dwave.cloud.client.Client.from_config` instead. This method tries to load a legacy configuration file from ``~/.dwrc``, select a specified `profile` (or, if not specified, the first profile), and override individual keys with values read from environment variables or specified explicitly as key values in the function. Configuration values can be specified in multiple ways, ranked in the following order (with 1 the highest ranked): 1. Values specified as keyword arguments in :func:`legacy_load_config()` 2. Values specified as environment variables 3. Values specified in the legacy ``~/.dwrc`` configuration file Environment variables searched for are: - ``DW_INTERNAL__HTTPLINK`` - ``DW_INTERNAL__TOKEN`` - ``DW_INTERNAL__HTTPPROXY`` - ``DW_INTERNAL__SOLVER`` Legacy configuration file format is a modified CSV where the first comma is replaced with a bar character (``|``). Each line encodes a single profile. Its columns are:: profile_name|endpoint_url,authentication_token,proxy_url,default_solver_name All its fields after ``authentication_token`` are optional. When there are multiple connections in a file, the first one is the default. Any commas in the URLs must be percent-encoded. Args: profile (str): Profile name in the legacy configuration file. endpoint (str, default=None): API endpoint URL. token (str, default=None): API authorization token. solver (str, default=None): Default solver to use in :meth:`~dwave.cloud.client.Client.get_solver`. If undefined, all calls to :meth:`~dwave.cloud.client.Client.get_solver` must explicitly specify the solver name/id. proxy (str, default=None): URL for proxy to use in connections to D-Wave API. Can include username/password, port, scheme, etc. If undefined, client uses a system-level proxy, if defined, or connects directly to the API. Returns: Dictionary with keys: endpoint, token, solver, and proxy. Examples: This example creates a client using the :meth:`~dwave.cloud.client.Client.from_config` method, which falls back on the legacy file by default when it fails to find a D-Wave Cloud Client configuration file (setting its `legacy_config_fallback` parameter to False precludes this fall-back operation). For this example, no D-Wave Cloud Client configuration file is present on the local system; instead the following ``.dwrc`` legacy configuration file is present in the user's home directory:: profile-a|https://one.com,token-one profile-b|https://two.com,token-two The following example code creates a client without explicitly specifying key values, therefore auto-detection searches for existing (non-legacy) configuration files in the standard directories of :func:`get_configfile_paths` and, failing to find one, falls back on the existing legacy configuration file above. >>> import dwave.cloud as dc >>> client = dwave.cloud.Client.from_config() # doctest: +SKIP >>> client.endpoint # doctest: +SKIP 'https://one.com' >>> client.token # doctest: +SKIP 'token-one' The following examples specify a profile and/or token. >>> # Explicitly specify a profile >>> client = dwave.cloud.Client.from_config(profile='profile-b') >>> # Will try to connect with the url `https://two.com` and the token `token-two`. >>> client = dwave.cloud.Client.from_config(profile='profile-b', token='new-token') >>> # Will try to connect with the url `https://two.com` and the token `new-token`. """ def _parse_config(fp, filename): fields = ('endpoint', 'token', 'proxy', 'solver') config = OrderedDict() for line in fp: # strip whitespace, skip blank and comment lines line = line.strip() if not line or line.startswith('#'): continue # parse each record, store in dict with label as key try: label, data = line.split('|', 1) values = [v.strip() or None for v in data.split(',')] config[label] = dict(zip(fields, values)) except: raise ConfigFileParseError( "Failed to parse {!r}, line {!r}".format(filename, line)) return config def _read_config(filename): try: with open(filename, 'r') as f: return _parse_config(f, filename) except (IOError, OSError): raise ConfigFileReadError("Failed to read {!r}".format(filename)) config = {} filename = os.path.expanduser('~/.dwrc') if os.path.exists(filename): config = _read_config(filename) # load profile if specified, or first one in file if profile: try: section = config[profile] except KeyError: raise ValueError("Config profile {!r} not found".format(profile)) else: try: _, section = next(iter(config.items())) except StopIteration: section = {} # override config variables (if any) with environment and then with arguments section['endpoint'] = endpoint or os.getenv("DW_INTERNAL__HTTPLINK", section.get('endpoint')) section['token'] = token or os.getenv("DW_INTERNAL__TOKEN", section.get('token')) section['proxy'] = proxy or os.getenv("DW_INTERNAL__HTTPPROXY", section.get('proxy')) section['solver'] = solver or os.getenv("DW_INTERNAL__SOLVER", section.get('solver')) section.update(kwargs) return section
[ "def", "legacy_load_config", "(", "profile", "=", "None", ",", "endpoint", "=", "None", ",", "token", "=", "None", ",", "solver", "=", "None", ",", "proxy", "=", "None", ",", "*", "*", "kwargs", ")", ":", "def", "_parse_config", "(", "fp", ",", "filename", ")", ":", "fields", "=", "(", "'endpoint'", ",", "'token'", ",", "'proxy'", ",", "'solver'", ")", "config", "=", "OrderedDict", "(", ")", "for", "line", "in", "fp", ":", "# strip whitespace, skip blank and comment lines", "line", "=", "line", ".", "strip", "(", ")", "if", "not", "line", "or", "line", ".", "startswith", "(", "'#'", ")", ":", "continue", "# parse each record, store in dict with label as key", "try", ":", "label", ",", "data", "=", "line", ".", "split", "(", "'|'", ",", "1", ")", "values", "=", "[", "v", ".", "strip", "(", ")", "or", "None", "for", "v", "in", "data", ".", "split", "(", "','", ")", "]", "config", "[", "label", "]", "=", "dict", "(", "zip", "(", "fields", ",", "values", ")", ")", "except", ":", "raise", "ConfigFileParseError", "(", "\"Failed to parse {!r}, line {!r}\"", ".", "format", "(", "filename", ",", "line", ")", ")", "return", "config", "def", "_read_config", "(", "filename", ")", ":", "try", ":", "with", "open", "(", "filename", ",", "'r'", ")", "as", "f", ":", "return", "_parse_config", "(", "f", ",", "filename", ")", "except", "(", "IOError", ",", "OSError", ")", ":", "raise", "ConfigFileReadError", "(", "\"Failed to read {!r}\"", ".", "format", "(", "filename", ")", ")", "config", "=", "{", "}", "filename", "=", "os", ".", "path", ".", "expanduser", "(", "'~/.dwrc'", ")", "if", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "config", "=", "_read_config", "(", "filename", ")", "# load profile if specified, or first one in file", "if", "profile", ":", "try", ":", "section", "=", "config", "[", "profile", "]", "except", "KeyError", ":", "raise", "ValueError", "(", "\"Config profile {!r} not found\"", ".", "format", "(", "profile", ")", ")", "else", ":", "try", ":", "_", ",", "section", "=", "next", "(", "iter", "(", "config", ".", "items", "(", ")", ")", ")", "except", "StopIteration", ":", "section", "=", "{", "}", "# override config variables (if any) with environment and then with arguments", "section", "[", "'endpoint'", "]", "=", "endpoint", "or", "os", ".", "getenv", "(", "\"DW_INTERNAL__HTTPLINK\"", ",", "section", ".", "get", "(", "'endpoint'", ")", ")", "section", "[", "'token'", "]", "=", "token", "or", "os", ".", "getenv", "(", "\"DW_INTERNAL__TOKEN\"", ",", "section", ".", "get", "(", "'token'", ")", ")", "section", "[", "'proxy'", "]", "=", "proxy", "or", "os", ".", "getenv", "(", "\"DW_INTERNAL__HTTPPROXY\"", ",", "section", ".", "get", "(", "'proxy'", ")", ")", "section", "[", "'solver'", "]", "=", "solver", "or", "os", ".", "getenv", "(", "\"DW_INTERNAL__SOLVER\"", ",", "section", ".", "get", "(", "'solver'", ")", ")", "section", ".", "update", "(", "kwargs", ")", "return", "section" ]
Load configured URLs and token for the SAPI server. .. warning:: Included only for backward compatibility. Please use :func:`load_config` or the client factory :meth:`~dwave.cloud.client.Client.from_config` instead. This method tries to load a legacy configuration file from ``~/.dwrc``, select a specified `profile` (or, if not specified, the first profile), and override individual keys with values read from environment variables or specified explicitly as key values in the function. Configuration values can be specified in multiple ways, ranked in the following order (with 1 the highest ranked): 1. Values specified as keyword arguments in :func:`legacy_load_config()` 2. Values specified as environment variables 3. Values specified in the legacy ``~/.dwrc`` configuration file Environment variables searched for are: - ``DW_INTERNAL__HTTPLINK`` - ``DW_INTERNAL__TOKEN`` - ``DW_INTERNAL__HTTPPROXY`` - ``DW_INTERNAL__SOLVER`` Legacy configuration file format is a modified CSV where the first comma is replaced with a bar character (``|``). Each line encodes a single profile. Its columns are:: profile_name|endpoint_url,authentication_token,proxy_url,default_solver_name All its fields after ``authentication_token`` are optional. When there are multiple connections in a file, the first one is the default. Any commas in the URLs must be percent-encoded. Args: profile (str): Profile name in the legacy configuration file. endpoint (str, default=None): API endpoint URL. token (str, default=None): API authorization token. solver (str, default=None): Default solver to use in :meth:`~dwave.cloud.client.Client.get_solver`. If undefined, all calls to :meth:`~dwave.cloud.client.Client.get_solver` must explicitly specify the solver name/id. proxy (str, default=None): URL for proxy to use in connections to D-Wave API. Can include username/password, port, scheme, etc. If undefined, client uses a system-level proxy, if defined, or connects directly to the API. Returns: Dictionary with keys: endpoint, token, solver, and proxy. Examples: This example creates a client using the :meth:`~dwave.cloud.client.Client.from_config` method, which falls back on the legacy file by default when it fails to find a D-Wave Cloud Client configuration file (setting its `legacy_config_fallback` parameter to False precludes this fall-back operation). For this example, no D-Wave Cloud Client configuration file is present on the local system; instead the following ``.dwrc`` legacy configuration file is present in the user's home directory:: profile-a|https://one.com,token-one profile-b|https://two.com,token-two The following example code creates a client without explicitly specifying key values, therefore auto-detection searches for existing (non-legacy) configuration files in the standard directories of :func:`get_configfile_paths` and, failing to find one, falls back on the existing legacy configuration file above. >>> import dwave.cloud as dc >>> client = dwave.cloud.Client.from_config() # doctest: +SKIP >>> client.endpoint # doctest: +SKIP 'https://one.com' >>> client.token # doctest: +SKIP 'token-one' The following examples specify a profile and/or token. >>> # Explicitly specify a profile >>> client = dwave.cloud.Client.from_config(profile='profile-b') >>> # Will try to connect with the url `https://two.com` and the token `token-two`. >>> client = dwave.cloud.Client.from_config(profile='profile-b', token='new-token') >>> # Will try to connect with the url `https://two.com` and the token `new-token`.
[ "Load", "configured", "URLs", "and", "token", "for", "the", "SAPI", "server", "." ]
df3221a8385dc0c04d7b4d84f740bf3ad6706230
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/config.py#L781-L925
train
tuxu/python-samplerate
samplerate/lowlevel.py
_check_data
def _check_data(data): """Check whether `data` is a valid input/output for libsamplerate. Returns ------- num_frames Number of frames in `data`. channels Number of channels in `data`. Raises ------ ValueError: If invalid data is supplied. """ if not (data.dtype == _np.float32 and data.flags.c_contiguous): raise ValueError('supplied data must be float32 and C contiguous') if data.ndim == 2: num_frames, channels = data.shape elif data.ndim == 1: num_frames, channels = data.size, 1 else: raise ValueError('rank > 2 not supported') return num_frames, channels
python
def _check_data(data): """Check whether `data` is a valid input/output for libsamplerate. Returns ------- num_frames Number of frames in `data`. channels Number of channels in `data`. Raises ------ ValueError: If invalid data is supplied. """ if not (data.dtype == _np.float32 and data.flags.c_contiguous): raise ValueError('supplied data must be float32 and C contiguous') if data.ndim == 2: num_frames, channels = data.shape elif data.ndim == 1: num_frames, channels = data.size, 1 else: raise ValueError('rank > 2 not supported') return num_frames, channels
[ "def", "_check_data", "(", "data", ")", ":", "if", "not", "(", "data", ".", "dtype", "==", "_np", ".", "float32", "and", "data", ".", "flags", ".", "c_contiguous", ")", ":", "raise", "ValueError", "(", "'supplied data must be float32 and C contiguous'", ")", "if", "data", ".", "ndim", "==", "2", ":", "num_frames", ",", "channels", "=", "data", ".", "shape", "elif", "data", ".", "ndim", "==", "1", ":", "num_frames", ",", "channels", "=", "data", ".", "size", ",", "1", "else", ":", "raise", "ValueError", "(", "'rank > 2 not supported'", ")", "return", "num_frames", ",", "channels" ]
Check whether `data` is a valid input/output for libsamplerate. Returns ------- num_frames Number of frames in `data`. channels Number of channels in `data`. Raises ------ ValueError: If invalid data is supplied.
[ "Check", "whether", "data", "is", "a", "valid", "input", "/", "output", "for", "libsamplerate", "." ]
ed73d7a39e61bfb34b03dade14ffab59aa27922a
https://github.com/tuxu/python-samplerate/blob/ed73d7a39e61bfb34b03dade14ffab59aa27922a/samplerate/lowlevel.py#L41-L63
train
tuxu/python-samplerate
samplerate/lowlevel.py
src_simple
def src_simple(input_data, output_data, ratio, converter_type, channels): """Perform a single conversion from an input buffer to an output buffer. Simple interface for performing a single conversion from input buffer to output buffer at a fixed conversion ratio. Simple interface does not require initialisation as it can only operate on a single buffer worth of audio. """ input_frames, _ = _check_data(input_data) output_frames, _ = _check_data(output_data) data = ffi.new('SRC_DATA*') data.input_frames = input_frames data.output_frames = output_frames data.src_ratio = ratio data.data_in = ffi.cast('float*', ffi.from_buffer(input_data)) data.data_out = ffi.cast('float*', ffi.from_buffer(output_data)) error = _lib.src_simple(data, converter_type, channels) return error, data.input_frames_used, data.output_frames_gen
python
def src_simple(input_data, output_data, ratio, converter_type, channels): """Perform a single conversion from an input buffer to an output buffer. Simple interface for performing a single conversion from input buffer to output buffer at a fixed conversion ratio. Simple interface does not require initialisation as it can only operate on a single buffer worth of audio. """ input_frames, _ = _check_data(input_data) output_frames, _ = _check_data(output_data) data = ffi.new('SRC_DATA*') data.input_frames = input_frames data.output_frames = output_frames data.src_ratio = ratio data.data_in = ffi.cast('float*', ffi.from_buffer(input_data)) data.data_out = ffi.cast('float*', ffi.from_buffer(output_data)) error = _lib.src_simple(data, converter_type, channels) return error, data.input_frames_used, data.output_frames_gen
[ "def", "src_simple", "(", "input_data", ",", "output_data", ",", "ratio", ",", "converter_type", ",", "channels", ")", ":", "input_frames", ",", "_", "=", "_check_data", "(", "input_data", ")", "output_frames", ",", "_", "=", "_check_data", "(", "output_data", ")", "data", "=", "ffi", ".", "new", "(", "'SRC_DATA*'", ")", "data", ".", "input_frames", "=", "input_frames", "data", ".", "output_frames", "=", "output_frames", "data", ".", "src_ratio", "=", "ratio", "data", ".", "data_in", "=", "ffi", ".", "cast", "(", "'float*'", ",", "ffi", ".", "from_buffer", "(", "input_data", ")", ")", "data", ".", "data_out", "=", "ffi", ".", "cast", "(", "'float*'", ",", "ffi", ".", "from_buffer", "(", "output_data", ")", ")", "error", "=", "_lib", ".", "src_simple", "(", "data", ",", "converter_type", ",", "channels", ")", "return", "error", ",", "data", ".", "input_frames_used", ",", "data", ".", "output_frames_gen" ]
Perform a single conversion from an input buffer to an output buffer. Simple interface for performing a single conversion from input buffer to output buffer at a fixed conversion ratio. Simple interface does not require initialisation as it can only operate on a single buffer worth of audio.
[ "Perform", "a", "single", "conversion", "from", "an", "input", "buffer", "to", "an", "output", "buffer", "." ]
ed73d7a39e61bfb34b03dade14ffab59aa27922a
https://github.com/tuxu/python-samplerate/blob/ed73d7a39e61bfb34b03dade14ffab59aa27922a/samplerate/lowlevel.py#L86-L102
train
tuxu/python-samplerate
samplerate/lowlevel.py
src_new
def src_new(converter_type, channels): """Initialise a new sample rate converter. Parameters ---------- converter_type : int Converter to be used. channels : int Number of channels. Returns ------- state An anonymous pointer to the internal state of the converter. error : int Error code. """ error = ffi.new('int*') state = _lib.src_new(converter_type, channels, error) return state, error[0]
python
def src_new(converter_type, channels): """Initialise a new sample rate converter. Parameters ---------- converter_type : int Converter to be used. channels : int Number of channels. Returns ------- state An anonymous pointer to the internal state of the converter. error : int Error code. """ error = ffi.new('int*') state = _lib.src_new(converter_type, channels, error) return state, error[0]
[ "def", "src_new", "(", "converter_type", ",", "channels", ")", ":", "error", "=", "ffi", ".", "new", "(", "'int*'", ")", "state", "=", "_lib", ".", "src_new", "(", "converter_type", ",", "channels", ",", "error", ")", "return", "state", ",", "error", "[", "0", "]" ]
Initialise a new sample rate converter. Parameters ---------- converter_type : int Converter to be used. channels : int Number of channels. Returns ------- state An anonymous pointer to the internal state of the converter. error : int Error code.
[ "Initialise", "a", "new", "sample", "rate", "converter", "." ]
ed73d7a39e61bfb34b03dade14ffab59aa27922a
https://github.com/tuxu/python-samplerate/blob/ed73d7a39e61bfb34b03dade14ffab59aa27922a/samplerate/lowlevel.py#L105-L124
train
tuxu/python-samplerate
samplerate/lowlevel.py
src_process
def src_process(state, input_data, output_data, ratio, end_of_input=0): """Standard processing function. Returns non zero on error. """ input_frames, _ = _check_data(input_data) output_frames, _ = _check_data(output_data) data = ffi.new('SRC_DATA*') data.input_frames = input_frames data.output_frames = output_frames data.src_ratio = ratio data.data_in = ffi.cast('float*', ffi.from_buffer(input_data)) data.data_out = ffi.cast('float*', ffi.from_buffer(output_data)) data.end_of_input = end_of_input error = _lib.src_process(state, data) return error, data.input_frames_used, data.output_frames_gen
python
def src_process(state, input_data, output_data, ratio, end_of_input=0): """Standard processing function. Returns non zero on error. """ input_frames, _ = _check_data(input_data) output_frames, _ = _check_data(output_data) data = ffi.new('SRC_DATA*') data.input_frames = input_frames data.output_frames = output_frames data.src_ratio = ratio data.data_in = ffi.cast('float*', ffi.from_buffer(input_data)) data.data_out = ffi.cast('float*', ffi.from_buffer(output_data)) data.end_of_input = end_of_input error = _lib.src_process(state, data) return error, data.input_frames_used, data.output_frames_gen
[ "def", "src_process", "(", "state", ",", "input_data", ",", "output_data", ",", "ratio", ",", "end_of_input", "=", "0", ")", ":", "input_frames", ",", "_", "=", "_check_data", "(", "input_data", ")", "output_frames", ",", "_", "=", "_check_data", "(", "output_data", ")", "data", "=", "ffi", ".", "new", "(", "'SRC_DATA*'", ")", "data", ".", "input_frames", "=", "input_frames", "data", ".", "output_frames", "=", "output_frames", "data", ".", "src_ratio", "=", "ratio", "data", ".", "data_in", "=", "ffi", ".", "cast", "(", "'float*'", ",", "ffi", ".", "from_buffer", "(", "input_data", ")", ")", "data", ".", "data_out", "=", "ffi", ".", "cast", "(", "'float*'", ",", "ffi", ".", "from_buffer", "(", "output_data", ")", ")", "data", ".", "end_of_input", "=", "end_of_input", "error", "=", "_lib", ".", "src_process", "(", "state", ",", "data", ")", "return", "error", ",", "data", ".", "input_frames_used", ",", "data", ".", "output_frames_gen" ]
Standard processing function. Returns non zero on error.
[ "Standard", "processing", "function", "." ]
ed73d7a39e61bfb34b03dade14ffab59aa27922a
https://github.com/tuxu/python-samplerate/blob/ed73d7a39e61bfb34b03dade14ffab59aa27922a/samplerate/lowlevel.py#L135-L150
train
tuxu/python-samplerate
samplerate/lowlevel.py
_src_input_callback
def _src_input_callback(cb_data, data): """Internal callback function to be used with the callback API. Pulls the Python callback function from the handle contained in `cb_data` and calls it to fetch frames. Frames are converted to the format required by the API (float, interleaved channels). A reference to these data is kept internally. Returns ------- frames : int The number of frames supplied. """ cb_data = ffi.from_handle(cb_data) ret = cb_data['callback']() if ret is None: cb_data['last_input'] = None return 0 # No frames supplied input_data = _np.require(ret, requirements='C', dtype=_np.float32) input_frames, channels = _check_data(input_data) # Check whether the correct number of channels is supplied by user. if cb_data['channels'] != channels: raise ValueError('Invalid number of channels in callback.') # Store a reference of the input data to ensure it is still alive when # accessed by libsamplerate. cb_data['last_input'] = input_data data[0] = ffi.cast('float*', ffi.from_buffer(input_data)) return input_frames
python
def _src_input_callback(cb_data, data): """Internal callback function to be used with the callback API. Pulls the Python callback function from the handle contained in `cb_data` and calls it to fetch frames. Frames are converted to the format required by the API (float, interleaved channels). A reference to these data is kept internally. Returns ------- frames : int The number of frames supplied. """ cb_data = ffi.from_handle(cb_data) ret = cb_data['callback']() if ret is None: cb_data['last_input'] = None return 0 # No frames supplied input_data = _np.require(ret, requirements='C', dtype=_np.float32) input_frames, channels = _check_data(input_data) # Check whether the correct number of channels is supplied by user. if cb_data['channels'] != channels: raise ValueError('Invalid number of channels in callback.') # Store a reference of the input data to ensure it is still alive when # accessed by libsamplerate. cb_data['last_input'] = input_data data[0] = ffi.cast('float*', ffi.from_buffer(input_data)) return input_frames
[ "def", "_src_input_callback", "(", "cb_data", ",", "data", ")", ":", "cb_data", "=", "ffi", ".", "from_handle", "(", "cb_data", ")", "ret", "=", "cb_data", "[", "'callback'", "]", "(", ")", "if", "ret", "is", "None", ":", "cb_data", "[", "'last_input'", "]", "=", "None", "return", "0", "# No frames supplied", "input_data", "=", "_np", ".", "require", "(", "ret", ",", "requirements", "=", "'C'", ",", "dtype", "=", "_np", ".", "float32", ")", "input_frames", ",", "channels", "=", "_check_data", "(", "input_data", ")", "# Check whether the correct number of channels is supplied by user.", "if", "cb_data", "[", "'channels'", "]", "!=", "channels", ":", "raise", "ValueError", "(", "'Invalid number of channels in callback.'", ")", "# Store a reference of the input data to ensure it is still alive when", "# accessed by libsamplerate.", "cb_data", "[", "'last_input'", "]", "=", "input_data", "data", "[", "0", "]", "=", "ffi", ".", "cast", "(", "'float*'", ",", "ffi", ".", "from_buffer", "(", "input_data", ")", ")", "return", "input_frames" ]
Internal callback function to be used with the callback API. Pulls the Python callback function from the handle contained in `cb_data` and calls it to fetch frames. Frames are converted to the format required by the API (float, interleaved channels). A reference to these data is kept internally. Returns ------- frames : int The number of frames supplied.
[ "Internal", "callback", "function", "to", "be", "used", "with", "the", "callback", "API", "." ]
ed73d7a39e61bfb34b03dade14ffab59aa27922a
https://github.com/tuxu/python-samplerate/blob/ed73d7a39e61bfb34b03dade14ffab59aa27922a/samplerate/lowlevel.py#L184-L214
train
tuxu/python-samplerate
samplerate/lowlevel.py
src_callback_new
def src_callback_new(callback, converter_type, channels): """Initialisation for the callback based API. Parameters ---------- callback : function Called whenever new frames are to be read. Must return a NumPy array of shape (num_frames, channels). converter_type : int Converter to be used. channels : int Number of channels. Returns ------- state An anonymous pointer to the internal state of the converter. handle A CFFI handle to the callback data. error : int Error code. """ cb_data = {'callback': callback, 'channels': channels} handle = ffi.new_handle(cb_data) error = ffi.new('int*') state = _lib.src_callback_new(_src_input_callback, converter_type, channels, error, handle) if state == ffi.NULL: return None, handle, error[0] return state, handle, error[0]
python
def src_callback_new(callback, converter_type, channels): """Initialisation for the callback based API. Parameters ---------- callback : function Called whenever new frames are to be read. Must return a NumPy array of shape (num_frames, channels). converter_type : int Converter to be used. channels : int Number of channels. Returns ------- state An anonymous pointer to the internal state of the converter. handle A CFFI handle to the callback data. error : int Error code. """ cb_data = {'callback': callback, 'channels': channels} handle = ffi.new_handle(cb_data) error = ffi.new('int*') state = _lib.src_callback_new(_src_input_callback, converter_type, channels, error, handle) if state == ffi.NULL: return None, handle, error[0] return state, handle, error[0]
[ "def", "src_callback_new", "(", "callback", ",", "converter_type", ",", "channels", ")", ":", "cb_data", "=", "{", "'callback'", ":", "callback", ",", "'channels'", ":", "channels", "}", "handle", "=", "ffi", ".", "new_handle", "(", "cb_data", ")", "error", "=", "ffi", ".", "new", "(", "'int*'", ")", "state", "=", "_lib", ".", "src_callback_new", "(", "_src_input_callback", ",", "converter_type", ",", "channels", ",", "error", ",", "handle", ")", "if", "state", "==", "ffi", ".", "NULL", ":", "return", "None", ",", "handle", ",", "error", "[", "0", "]", "return", "state", ",", "handle", ",", "error", "[", "0", "]" ]
Initialisation for the callback based API. Parameters ---------- callback : function Called whenever new frames are to be read. Must return a NumPy array of shape (num_frames, channels). converter_type : int Converter to be used. channels : int Number of channels. Returns ------- state An anonymous pointer to the internal state of the converter. handle A CFFI handle to the callback data. error : int Error code.
[ "Initialisation", "for", "the", "callback", "based", "API", "." ]
ed73d7a39e61bfb34b03dade14ffab59aa27922a
https://github.com/tuxu/python-samplerate/blob/ed73d7a39e61bfb34b03dade14ffab59aa27922a/samplerate/lowlevel.py#L217-L247
train
tuxu/python-samplerate
samplerate/lowlevel.py
src_callback_read
def src_callback_read(state, ratio, frames, data): """Read up to `frames` worth of data using the callback API. Returns ------- frames : int Number of frames read or -1 on error. """ data_ptr = ffi.cast('float*f', ffi.from_buffer(data)) return _lib.src_callback_read(state, ratio, frames, data_ptr)
python
def src_callback_read(state, ratio, frames, data): """Read up to `frames` worth of data using the callback API. Returns ------- frames : int Number of frames read or -1 on error. """ data_ptr = ffi.cast('float*f', ffi.from_buffer(data)) return _lib.src_callback_read(state, ratio, frames, data_ptr)
[ "def", "src_callback_read", "(", "state", ",", "ratio", ",", "frames", ",", "data", ")", ":", "data_ptr", "=", "ffi", ".", "cast", "(", "'float*f'", ",", "ffi", ".", "from_buffer", "(", "data", ")", ")", "return", "_lib", ".", "src_callback_read", "(", "state", ",", "ratio", ",", "frames", ",", "data_ptr", ")" ]
Read up to `frames` worth of data using the callback API. Returns ------- frames : int Number of frames read or -1 on error.
[ "Read", "up", "to", "frames", "worth", "of", "data", "using", "the", "callback", "API", "." ]
ed73d7a39e61bfb34b03dade14ffab59aa27922a
https://github.com/tuxu/python-samplerate/blob/ed73d7a39e61bfb34b03dade14ffab59aa27922a/samplerate/lowlevel.py#L250-L259
train
dwavesystems/dwave-cloud-client
dwave/cloud/client.py
Client.from_config
def from_config(cls, config_file=None, profile=None, client=None, endpoint=None, token=None, solver=None, proxy=None, legacy_config_fallback=False, **kwargs): """Client factory method to instantiate a client instance from configuration. Configuration values can be specified in multiple ways, ranked in the following order (with 1 the highest ranked): 1. Values specified as keyword arguments in :func:`from_config()` 2. Values specified as environment variables 3. Values specified in the configuration file Configuration-file format is described in :mod:`dwave.cloud.config`. If the location of the configuration file is not specified, auto-detection searches for existing configuration files in the standard directories of :func:`get_configfile_paths`. If a configuration file explicitly specified, via an argument or environment variable, does not exist or is unreadable, loading fails with :exc:`~dwave.cloud.exceptions.ConfigFileReadError`. Loading fails with :exc:`~dwave.cloud.exceptions.ConfigFileParseError` if the file is readable but invalid as a configuration file. Similarly, if a profile explicitly specified, via an argument or environment variable, is not present in the loaded configuration, loading fails with :exc:`ValueError`. Explicit profile selection also fails if the configuration file is not explicitly specified, detected on the system, or defined via an environment variable. Environment variables: ``DWAVE_CONFIG_FILE``, ``DWAVE_PROFILE``, ``DWAVE_API_CLIENT``, ``DWAVE_API_ENDPOINT``, ``DWAVE_API_TOKEN``, ``DWAVE_API_SOLVER``, ``DWAVE_API_PROXY``. Environment variables are described in :mod:`dwave.cloud.config`. Args: config_file (str/[str]/None/False/True, default=None): Path to configuration file. If ``None``, the value is taken from ``DWAVE_CONFIG_FILE`` environment variable if defined. If the environment variable is undefined or empty, auto-detection searches for existing configuration files in the standard directories of :func:`get_configfile_paths`. If ``False``, loading from file is skipped; if ``True``, forces auto-detection (regardless of the ``DWAVE_CONFIG_FILE`` environment variable). profile (str, default=None): Profile name (name of the profile section in the configuration file). If undefined, inferred from ``DWAVE_PROFILE`` environment variable if defined. If the environment variable is undefined or empty, a profile is selected in the following order: 1. From the default section if it includes a profile key. 2. The first section (after the default section). 3. If no other section is defined besides ``[defaults]``, the defaults section is promoted and selected. client (str, default=None): Client type used for accessing the API. Supported values are ``qpu`` for :class:`dwave.cloud.qpu.Client` and ``sw`` for :class:`dwave.cloud.sw.Client`. endpoint (str, default=None): API endpoint URL. token (str, default=None): API authorization token. solver (dict/str, default=None): Default :term:`solver` features to use in :meth:`~dwave.cloud.client.Client.get_solver`. Defined via dictionary of solver feature constraints (see :meth:`~dwave.cloud.client.Client.get_solvers`). For backward compatibility, a solver name, as a string, is also accepted and converted to ``{"name": <solver name>}``. If undefined, :meth:`~dwave.cloud.client.Client.get_solver` uses a solver definition from environment variables, a configuration file, or falls back to the first available online solver. proxy (str, default=None): URL for proxy to use in connections to D-Wave API. Can include username/password, port, scheme, etc. If undefined, client uses the system-level proxy, if defined, or connects directly to the API. legacy_config_fallback (bool, default=False): If True and loading from a standard D-Wave Cloud Client configuration file (``dwave.conf``) fails, tries loading a legacy configuration file (``~/.dwrc``). Other Parameters: Unrecognized keys (str): All unrecognized keys are passed through to the appropriate client class constructor as string keyword arguments. An explicit key value overrides an identical user-defined key value loaded from a configuration file. Returns: :class:`~dwave.cloud.client.Client` (:class:`dwave.cloud.qpu.Client` or :class:`dwave.cloud.sw.Client`, default=:class:`dwave.cloud.qpu.Client`): Appropriate instance of a QPU or software client. Raises: :exc:`~dwave.cloud.exceptions.ConfigFileReadError`: Config file specified or detected could not be opened or read. :exc:`~dwave.cloud.exceptions.ConfigFileParseError`: Config file parse failed. Examples: A variety of examples are given in :mod:`dwave.cloud.config`. This example initializes :class:`~dwave.cloud.client.Client` from an explicitly specified configuration file, "~/jane/my_path_to_config/my_cloud_conf.conf":: >>> from dwave.cloud import Client >>> client = Client.from_config(config_file='~/jane/my_path_to_config/my_cloud_conf.conf') # doctest: +SKIP >>> # code that uses client >>> client.close() """ # try loading configuration from a preferred new config subsystem # (`./dwave.conf`, `~/.config/dwave/dwave.conf`, etc) config = load_config( config_file=config_file, profile=profile, client=client, endpoint=endpoint, token=token, solver=solver, proxy=proxy) _LOGGER.debug("Config loaded: %r", config) # fallback to legacy `.dwrc` if key variables missing if legacy_config_fallback: warnings.warn("'legacy_config_fallback' is deprecated, please convert " "your legacy .dwrc file to the new config format.", DeprecationWarning) if not config.get('token'): config = legacy_load_config( profile=profile, client=client, endpoint=endpoint, token=token, solver=solver, proxy=proxy) _LOGGER.debug("Legacy config loaded: %r", config) # manual override of other (client-custom) arguments config.update(kwargs) from dwave.cloud import qpu, sw _clients = {'qpu': qpu.Client, 'sw': sw.Client, 'base': cls} _client = config.pop('client', None) or 'base' _LOGGER.debug("Final config used for %s.Client(): %r", _client, config) return _clients[_client](**config)
python
def from_config(cls, config_file=None, profile=None, client=None, endpoint=None, token=None, solver=None, proxy=None, legacy_config_fallback=False, **kwargs): """Client factory method to instantiate a client instance from configuration. Configuration values can be specified in multiple ways, ranked in the following order (with 1 the highest ranked): 1. Values specified as keyword arguments in :func:`from_config()` 2. Values specified as environment variables 3. Values specified in the configuration file Configuration-file format is described in :mod:`dwave.cloud.config`. If the location of the configuration file is not specified, auto-detection searches for existing configuration files in the standard directories of :func:`get_configfile_paths`. If a configuration file explicitly specified, via an argument or environment variable, does not exist or is unreadable, loading fails with :exc:`~dwave.cloud.exceptions.ConfigFileReadError`. Loading fails with :exc:`~dwave.cloud.exceptions.ConfigFileParseError` if the file is readable but invalid as a configuration file. Similarly, if a profile explicitly specified, via an argument or environment variable, is not present in the loaded configuration, loading fails with :exc:`ValueError`. Explicit profile selection also fails if the configuration file is not explicitly specified, detected on the system, or defined via an environment variable. Environment variables: ``DWAVE_CONFIG_FILE``, ``DWAVE_PROFILE``, ``DWAVE_API_CLIENT``, ``DWAVE_API_ENDPOINT``, ``DWAVE_API_TOKEN``, ``DWAVE_API_SOLVER``, ``DWAVE_API_PROXY``. Environment variables are described in :mod:`dwave.cloud.config`. Args: config_file (str/[str]/None/False/True, default=None): Path to configuration file. If ``None``, the value is taken from ``DWAVE_CONFIG_FILE`` environment variable if defined. If the environment variable is undefined or empty, auto-detection searches for existing configuration files in the standard directories of :func:`get_configfile_paths`. If ``False``, loading from file is skipped; if ``True``, forces auto-detection (regardless of the ``DWAVE_CONFIG_FILE`` environment variable). profile (str, default=None): Profile name (name of the profile section in the configuration file). If undefined, inferred from ``DWAVE_PROFILE`` environment variable if defined. If the environment variable is undefined or empty, a profile is selected in the following order: 1. From the default section if it includes a profile key. 2. The first section (after the default section). 3. If no other section is defined besides ``[defaults]``, the defaults section is promoted and selected. client (str, default=None): Client type used for accessing the API. Supported values are ``qpu`` for :class:`dwave.cloud.qpu.Client` and ``sw`` for :class:`dwave.cloud.sw.Client`. endpoint (str, default=None): API endpoint URL. token (str, default=None): API authorization token. solver (dict/str, default=None): Default :term:`solver` features to use in :meth:`~dwave.cloud.client.Client.get_solver`. Defined via dictionary of solver feature constraints (see :meth:`~dwave.cloud.client.Client.get_solvers`). For backward compatibility, a solver name, as a string, is also accepted and converted to ``{"name": <solver name>}``. If undefined, :meth:`~dwave.cloud.client.Client.get_solver` uses a solver definition from environment variables, a configuration file, or falls back to the first available online solver. proxy (str, default=None): URL for proxy to use in connections to D-Wave API. Can include username/password, port, scheme, etc. If undefined, client uses the system-level proxy, if defined, or connects directly to the API. legacy_config_fallback (bool, default=False): If True and loading from a standard D-Wave Cloud Client configuration file (``dwave.conf``) fails, tries loading a legacy configuration file (``~/.dwrc``). Other Parameters: Unrecognized keys (str): All unrecognized keys are passed through to the appropriate client class constructor as string keyword arguments. An explicit key value overrides an identical user-defined key value loaded from a configuration file. Returns: :class:`~dwave.cloud.client.Client` (:class:`dwave.cloud.qpu.Client` or :class:`dwave.cloud.sw.Client`, default=:class:`dwave.cloud.qpu.Client`): Appropriate instance of a QPU or software client. Raises: :exc:`~dwave.cloud.exceptions.ConfigFileReadError`: Config file specified or detected could not be opened or read. :exc:`~dwave.cloud.exceptions.ConfigFileParseError`: Config file parse failed. Examples: A variety of examples are given in :mod:`dwave.cloud.config`. This example initializes :class:`~dwave.cloud.client.Client` from an explicitly specified configuration file, "~/jane/my_path_to_config/my_cloud_conf.conf":: >>> from dwave.cloud import Client >>> client = Client.from_config(config_file='~/jane/my_path_to_config/my_cloud_conf.conf') # doctest: +SKIP >>> # code that uses client >>> client.close() """ # try loading configuration from a preferred new config subsystem # (`./dwave.conf`, `~/.config/dwave/dwave.conf`, etc) config = load_config( config_file=config_file, profile=profile, client=client, endpoint=endpoint, token=token, solver=solver, proxy=proxy) _LOGGER.debug("Config loaded: %r", config) # fallback to legacy `.dwrc` if key variables missing if legacy_config_fallback: warnings.warn("'legacy_config_fallback' is deprecated, please convert " "your legacy .dwrc file to the new config format.", DeprecationWarning) if not config.get('token'): config = legacy_load_config( profile=profile, client=client, endpoint=endpoint, token=token, solver=solver, proxy=proxy) _LOGGER.debug("Legacy config loaded: %r", config) # manual override of other (client-custom) arguments config.update(kwargs) from dwave.cloud import qpu, sw _clients = {'qpu': qpu.Client, 'sw': sw.Client, 'base': cls} _client = config.pop('client', None) or 'base' _LOGGER.debug("Final config used for %s.Client(): %r", _client, config) return _clients[_client](**config)
[ "def", "from_config", "(", "cls", ",", "config_file", "=", "None", ",", "profile", "=", "None", ",", "client", "=", "None", ",", "endpoint", "=", "None", ",", "token", "=", "None", ",", "solver", "=", "None", ",", "proxy", "=", "None", ",", "legacy_config_fallback", "=", "False", ",", "*", "*", "kwargs", ")", ":", "# try loading configuration from a preferred new config subsystem", "# (`./dwave.conf`, `~/.config/dwave/dwave.conf`, etc)", "config", "=", "load_config", "(", "config_file", "=", "config_file", ",", "profile", "=", "profile", ",", "client", "=", "client", ",", "endpoint", "=", "endpoint", ",", "token", "=", "token", ",", "solver", "=", "solver", ",", "proxy", "=", "proxy", ")", "_LOGGER", ".", "debug", "(", "\"Config loaded: %r\"", ",", "config", ")", "# fallback to legacy `.dwrc` if key variables missing", "if", "legacy_config_fallback", ":", "warnings", ".", "warn", "(", "\"'legacy_config_fallback' is deprecated, please convert \"", "\"your legacy .dwrc file to the new config format.\"", ",", "DeprecationWarning", ")", "if", "not", "config", ".", "get", "(", "'token'", ")", ":", "config", "=", "legacy_load_config", "(", "profile", "=", "profile", ",", "client", "=", "client", ",", "endpoint", "=", "endpoint", ",", "token", "=", "token", ",", "solver", "=", "solver", ",", "proxy", "=", "proxy", ")", "_LOGGER", ".", "debug", "(", "\"Legacy config loaded: %r\"", ",", "config", ")", "# manual override of other (client-custom) arguments", "config", ".", "update", "(", "kwargs", ")", "from", "dwave", ".", "cloud", "import", "qpu", ",", "sw", "_clients", "=", "{", "'qpu'", ":", "qpu", ".", "Client", ",", "'sw'", ":", "sw", ".", "Client", ",", "'base'", ":", "cls", "}", "_client", "=", "config", ".", "pop", "(", "'client'", ",", "None", ")", "or", "'base'", "_LOGGER", ".", "debug", "(", "\"Final config used for %s.Client(): %r\"", ",", "_client", ",", "config", ")", "return", "_clients", "[", "_client", "]", "(", "*", "*", "config", ")" ]
Client factory method to instantiate a client instance from configuration. Configuration values can be specified in multiple ways, ranked in the following order (with 1 the highest ranked): 1. Values specified as keyword arguments in :func:`from_config()` 2. Values specified as environment variables 3. Values specified in the configuration file Configuration-file format is described in :mod:`dwave.cloud.config`. If the location of the configuration file is not specified, auto-detection searches for existing configuration files in the standard directories of :func:`get_configfile_paths`. If a configuration file explicitly specified, via an argument or environment variable, does not exist or is unreadable, loading fails with :exc:`~dwave.cloud.exceptions.ConfigFileReadError`. Loading fails with :exc:`~dwave.cloud.exceptions.ConfigFileParseError` if the file is readable but invalid as a configuration file. Similarly, if a profile explicitly specified, via an argument or environment variable, is not present in the loaded configuration, loading fails with :exc:`ValueError`. Explicit profile selection also fails if the configuration file is not explicitly specified, detected on the system, or defined via an environment variable. Environment variables: ``DWAVE_CONFIG_FILE``, ``DWAVE_PROFILE``, ``DWAVE_API_CLIENT``, ``DWAVE_API_ENDPOINT``, ``DWAVE_API_TOKEN``, ``DWAVE_API_SOLVER``, ``DWAVE_API_PROXY``. Environment variables are described in :mod:`dwave.cloud.config`. Args: config_file (str/[str]/None/False/True, default=None): Path to configuration file. If ``None``, the value is taken from ``DWAVE_CONFIG_FILE`` environment variable if defined. If the environment variable is undefined or empty, auto-detection searches for existing configuration files in the standard directories of :func:`get_configfile_paths`. If ``False``, loading from file is skipped; if ``True``, forces auto-detection (regardless of the ``DWAVE_CONFIG_FILE`` environment variable). profile (str, default=None): Profile name (name of the profile section in the configuration file). If undefined, inferred from ``DWAVE_PROFILE`` environment variable if defined. If the environment variable is undefined or empty, a profile is selected in the following order: 1. From the default section if it includes a profile key. 2. The first section (after the default section). 3. If no other section is defined besides ``[defaults]``, the defaults section is promoted and selected. client (str, default=None): Client type used for accessing the API. Supported values are ``qpu`` for :class:`dwave.cloud.qpu.Client` and ``sw`` for :class:`dwave.cloud.sw.Client`. endpoint (str, default=None): API endpoint URL. token (str, default=None): API authorization token. solver (dict/str, default=None): Default :term:`solver` features to use in :meth:`~dwave.cloud.client.Client.get_solver`. Defined via dictionary of solver feature constraints (see :meth:`~dwave.cloud.client.Client.get_solvers`). For backward compatibility, a solver name, as a string, is also accepted and converted to ``{"name": <solver name>}``. If undefined, :meth:`~dwave.cloud.client.Client.get_solver` uses a solver definition from environment variables, a configuration file, or falls back to the first available online solver. proxy (str, default=None): URL for proxy to use in connections to D-Wave API. Can include username/password, port, scheme, etc. If undefined, client uses the system-level proxy, if defined, or connects directly to the API. legacy_config_fallback (bool, default=False): If True and loading from a standard D-Wave Cloud Client configuration file (``dwave.conf``) fails, tries loading a legacy configuration file (``~/.dwrc``). Other Parameters: Unrecognized keys (str): All unrecognized keys are passed through to the appropriate client class constructor as string keyword arguments. An explicit key value overrides an identical user-defined key value loaded from a configuration file. Returns: :class:`~dwave.cloud.client.Client` (:class:`dwave.cloud.qpu.Client` or :class:`dwave.cloud.sw.Client`, default=:class:`dwave.cloud.qpu.Client`): Appropriate instance of a QPU or software client. Raises: :exc:`~dwave.cloud.exceptions.ConfigFileReadError`: Config file specified or detected could not be opened or read. :exc:`~dwave.cloud.exceptions.ConfigFileParseError`: Config file parse failed. Examples: A variety of examples are given in :mod:`dwave.cloud.config`. This example initializes :class:`~dwave.cloud.client.Client` from an explicitly specified configuration file, "~/jane/my_path_to_config/my_cloud_conf.conf":: >>> from dwave.cloud import Client >>> client = Client.from_config(config_file='~/jane/my_path_to_config/my_cloud_conf.conf') # doctest: +SKIP >>> # code that uses client >>> client.close()
[ "Client", "factory", "method", "to", "instantiate", "a", "client", "instance", "from", "configuration", "." ]
df3221a8385dc0c04d7b4d84f740bf3ad6706230
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/client.py#L168-L318
train
dwavesystems/dwave-cloud-client
dwave/cloud/client.py
Client.close
def close(self): """Perform a clean shutdown. Waits for all the currently scheduled work to finish, kills the workers, and closes the connection pool. .. note:: Ensure your code does not submit new work while the connection is closing. Where possible, it is recommended you use a context manager (a :code:`with Client.from_config(...) as` construct) to ensure your code properly closes all resources. Examples: This example creates a client (based on an auto-detected configuration file), executes some code (represented by a placeholder comment), and then closes the client. >>> from dwave.cloud import Client >>> client = Client.from_config() >>> # code that uses client >>> client.close() """ # Finish all the work that requires the connection _LOGGER.debug("Joining submission queue") self._submission_queue.join() _LOGGER.debug("Joining cancel queue") self._cancel_queue.join() _LOGGER.debug("Joining poll queue") self._poll_queue.join() _LOGGER.debug("Joining load queue") self._load_queue.join() # Send kill-task to all worker threads # Note: threads can't be 'killed' in Python, they have to die by # natural causes for _ in self._submission_workers: self._submission_queue.put(None) for _ in self._cancel_workers: self._cancel_queue.put(None) for _ in self._poll_workers: self._poll_queue.put((-1, None)) for _ in self._load_workers: self._load_queue.put(None) # Wait for threads to die for worker in chain(self._submission_workers, self._cancel_workers, self._poll_workers, self._load_workers): worker.join() # Close the requests session self.session.close()
python
def close(self): """Perform a clean shutdown. Waits for all the currently scheduled work to finish, kills the workers, and closes the connection pool. .. note:: Ensure your code does not submit new work while the connection is closing. Where possible, it is recommended you use a context manager (a :code:`with Client.from_config(...) as` construct) to ensure your code properly closes all resources. Examples: This example creates a client (based on an auto-detected configuration file), executes some code (represented by a placeholder comment), and then closes the client. >>> from dwave.cloud import Client >>> client = Client.from_config() >>> # code that uses client >>> client.close() """ # Finish all the work that requires the connection _LOGGER.debug("Joining submission queue") self._submission_queue.join() _LOGGER.debug("Joining cancel queue") self._cancel_queue.join() _LOGGER.debug("Joining poll queue") self._poll_queue.join() _LOGGER.debug("Joining load queue") self._load_queue.join() # Send kill-task to all worker threads # Note: threads can't be 'killed' in Python, they have to die by # natural causes for _ in self._submission_workers: self._submission_queue.put(None) for _ in self._cancel_workers: self._cancel_queue.put(None) for _ in self._poll_workers: self._poll_queue.put((-1, None)) for _ in self._load_workers: self._load_queue.put(None) # Wait for threads to die for worker in chain(self._submission_workers, self._cancel_workers, self._poll_workers, self._load_workers): worker.join() # Close the requests session self.session.close()
[ "def", "close", "(", "self", ")", ":", "# Finish all the work that requires the connection", "_LOGGER", ".", "debug", "(", "\"Joining submission queue\"", ")", "self", ".", "_submission_queue", ".", "join", "(", ")", "_LOGGER", ".", "debug", "(", "\"Joining cancel queue\"", ")", "self", ".", "_cancel_queue", ".", "join", "(", ")", "_LOGGER", ".", "debug", "(", "\"Joining poll queue\"", ")", "self", ".", "_poll_queue", ".", "join", "(", ")", "_LOGGER", ".", "debug", "(", "\"Joining load queue\"", ")", "self", ".", "_load_queue", ".", "join", "(", ")", "# Send kill-task to all worker threads", "# Note: threads can't be 'killed' in Python, they have to die by", "# natural causes", "for", "_", "in", "self", ".", "_submission_workers", ":", "self", ".", "_submission_queue", ".", "put", "(", "None", ")", "for", "_", "in", "self", ".", "_cancel_workers", ":", "self", ".", "_cancel_queue", ".", "put", "(", "None", ")", "for", "_", "in", "self", ".", "_poll_workers", ":", "self", ".", "_poll_queue", ".", "put", "(", "(", "-", "1", ",", "None", ")", ")", "for", "_", "in", "self", ".", "_load_workers", ":", "self", ".", "_load_queue", ".", "put", "(", "None", ")", "# Wait for threads to die", "for", "worker", "in", "chain", "(", "self", ".", "_submission_workers", ",", "self", ".", "_cancel_workers", ",", "self", ".", "_poll_workers", ",", "self", ".", "_load_workers", ")", ":", "worker", ".", "join", "(", ")", "# Close the requests session", "self", ".", "session", ".", "close", "(", ")" ]
Perform a clean shutdown. Waits for all the currently scheduled work to finish, kills the workers, and closes the connection pool. .. note:: Ensure your code does not submit new work while the connection is closing. Where possible, it is recommended you use a context manager (a :code:`with Client.from_config(...) as` construct) to ensure your code properly closes all resources. Examples: This example creates a client (based on an auto-detected configuration file), executes some code (represented by a placeholder comment), and then closes the client. >>> from dwave.cloud import Client >>> client = Client.from_config() >>> # code that uses client >>> client.close()
[ "Perform", "a", "clean", "shutdown", "." ]
df3221a8385dc0c04d7b4d84f740bf3ad6706230
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/client.py#L427-L476
train
dwavesystems/dwave-cloud-client
dwave/cloud/client.py
Client.get_solvers
def get_solvers(self, refresh=False, order_by='avg_load', **filters): """Return a filtered list of solvers handled by this client. Args: refresh (bool, default=False): Force refresh of cached list of solvers/properties. order_by (callable/str/None, default='avg_load'): Solver sorting key function (or :class:`Solver` attribute/item dot-separated path). By default, solvers are sorted by average load. To explicitly not sort the solvers (and use the API-returned order), set ``order_by=None``. Signature of the `key` `callable` is:: key :: (Solver s, Ord k) => s -> k Basic structure of the `key` string path is:: "-"? (attr|item) ( "." (attr|item) )* For example, to use solver property named ``max_anneal_schedule_points``, available in ``Solver.properties`` dict, you can either specify a callable `key`:: key=lambda solver: solver.properties['max_anneal_schedule_points'] or, you can use a short string path based key:: key='properties.max_anneal_schedule_points' Solver derived properties, available as :class:`Solver` properties can also be used (e.g. ``num_active_qubits``, ``online``, ``avg_load``, etc). Ascending sort order is implied, unless the key string path does not start with ``-``, in which case descending sort is used. Note: the sort used for ordering solvers by `key` is **stable**, meaning that if multiple solvers have the same value for the key, their relative order is preserved, and effectively they are in the same order as returned by the API. Note: solvers with ``None`` for key appear last in the list of solvers. When providing a key callable, ensure all values returned are of the same type (particularly in Python 3). For solvers with undefined key value, return ``None``. **filters: See `Filtering forms` and `Operators` below. Solver filters are defined, similarly to Django QuerySet filters, with keyword arguments of form `<key1>__...__<keyN>[__<operator>]=<value>`. Each `<operator>` is a predicate (boolean) function that acts on two arguments: value of feature `<name>` (described with keys path `<key1.key2...keyN>`) and the required `<value>`. Feature `<name>` can be: 1) a derived solver property, available as an identically named :class:`Solver`'s property (`name`, `qpu`, `software`, `online`, `num_active_qubits`, `avg_load`) 2) a solver parameter, available in :obj:`Solver.parameters` 3) a solver property, available in :obj:`Solver.properties` 4) a path describing a property in nested dictionaries Filtering forms are: * <derived_property>__<operator> (object <value>) * <derived_property> (bool) This form ensures the value of solver's property bound to `derived_property`, after applying `operator` equals the `value`. The default operator is `eq`. For example:: >>> client.get_solvers(avg_load__gt=0.5) but also:: >>> client.get_solvers(online=True) >>> # identical to: >>> client.get_solvers(online__eq=True) * <parameter>__<operator> (object <value>) * <parameter> (bool) This form ensures that the solver supports `parameter`. General operator form can be used but usually does not make sense for parameters, since values are human-readable descriptions. The default operator is `available`. Example:: >>> client.get_solvers(flux_biases=True) >>> # identical to: >>> client.get_solvers(flux_biases__available=True) * <property>__<operator> (object <value>) * <property> (bool) This form ensures the value of the solver's `property`, after applying `operator` equals the righthand side `value`. The default operator is `eq`. Note: if a non-existing parameter/property name/key given, the default operator is `eq`. Operators are: * `available` (<name>: str, <value>: bool): Test availability of <name> feature. * `eq`, `lt`, `lte`, `gt`, `gte` (<name>: str, <value>: any): Standard relational operators that compare feature <name> value with <value>. * `regex` (<name>: str, <value>: str): Test regular expression matching feature value. * `covers` (<name>: str, <value>: single value or range expressed as 2-tuple/list): Test feature <name> value (which should be a *range*) covers a given value or a subrange. * `within` (<name>: str, <value>: range expressed as 2-tuple/list): Test feature <name> value (which can be a *single value* or a *range*) is within a given range. * `in` (<name>: str, <value>: container type): Test feature <name> value is *in* <value> container. * `contains` (<name>: str, <value>: any): Test feature <name> value (container type) *contains* <value>. * `issubset` (<name>: str, <value>: container type): Test feature <name> value (container type) is a subset of <value>. * `issuperset` (<name>: str, <value>: container type): Test feature <name> value (container type) is a superset of <value>. Derived properies are: * `name` (str): Solver name/id. * `qpu` (bool): Is solver QPU based? * `software` (bool): Is solver software based? * `online` (bool, default=True): Is solver online? * `num_active_qubits` (int): Number of active qubits. Less then or equal to `num_qubits`. * `avg_load` (float): Solver's average load (similar to Unix load average). Common solver parameters are: * `flux_biases`: Should solver accept flux biases? * `anneal_schedule`: Should solver accept anneal schedule? Common solver properties are: * `num_qubits` (int): Number of qubits available. * `vfyc` (bool): Should solver work on "virtual full-yield chip"? * `max_anneal_schedule_points` (int): Piecewise linear annealing schedule points. * `h_range` ([int,int]), j_range ([int,int]): Biases/couplings values range. * `num_reads_range` ([int,int]): Range of allowed values for `num_reads` parameter. Returns: list[Solver]: List of all solvers that satisfy the conditions. Note: Client subclasses (e.g. :class:`dwave.cloud.qpu.Client` or :class:`dwave.cloud.sw.Client`) already filter solvers by resource type, so for `qpu` and `software` filters to have effect, call :meth:`.get_solvers` on base class :class:`~dwave.cloud.client.Client`. Examples:: client.get_solvers( num_qubits__gt=2000, # we need more than 2000 qubits num_qubits__lt=4000, # ... but fewer than 4000 qubits num_qubits__within=(2000, 4000), # an alternative to the previous two lines num_active_qubits=1089, # we want a particular number of active qubits vfyc=True, # we require a fully yielded Chimera vfyc__in=[False, None], # inverse of the previous filter vfyc__available=False, # we want solvers that do not advertize the vfyc property anneal_schedule=True, # we need support for custom anneal schedule max_anneal_schedule_points__gte=4, # we need at least 4 points for our anneal schedule num_reads_range__covers=1000, # our solver must support returning 1000 reads extended_j_range__covers=[-2, 2], # we need extended J range to contain subrange [-2,2] couplings__contains=[0, 128], # coupling (edge between) qubits (0,128) must exist couplings__issuperset=[[0,128], [0,4]], # two couplings required: (0,128) and (0,4) qubits__issuperset={0, 4, 215}, # qubits 0, 4 and 215 must exist supported_problem_types__issubset={'ising', 'qubo'}, # require Ising, QUBO or both to be supported name='DW_2000Q_3', # full solver name/ID match name__regex='.*2000.*', # partial/regex-based solver name match chip_id__regex='DW_.*', # chip ID prefix must be DW_ topology__type__eq="chimera" # topology.type must be chimera ) """ def covers_op(prop, val): """Does LHS `prop` (range) fully cover RHS `val` (range or item)?""" # `prop` must be a 2-element list/tuple range. if not isinstance(prop, (list, tuple)) or not len(prop) == 2: raise ValueError("2-element list/tuple range required for LHS value") llo, lhi = min(prop), max(prop) # `val` can be a single value, or a range (2-list/2-tuple). if isinstance(val, (list, tuple)) and len(val) == 2: # val range within prop range? rlo, rhi = min(val), max(val) return llo <= rlo and lhi >= rhi else: # val item within prop range? return llo <= val <= lhi def within_op(prop, val): """Is LHS `prop` (range or item) fully covered by RHS `val` (range)?""" try: return covers_op(val, prop) except ValueError: raise ValueError("2-element list/tuple range required for RHS value") def _set(iterable): """Like set(iterable), but works for lists as items in iterable. Before constructing a set, lists are converted to tuples. """ first = next(iter(iterable)) if isinstance(first, list): return set(tuple(x) for x in iterable) return set(iterable) def with_valid_lhs(op): @wraps(op) def _wrapper(prop, val): if prop is None: return False return op(prop, val) return _wrapper # available filtering operators ops = { 'lt': with_valid_lhs(operator.lt), 'lte': with_valid_lhs(operator.le), 'gt': with_valid_lhs(operator.gt), 'gte': with_valid_lhs(operator.ge), 'eq': operator.eq, 'available': lambda prop, val: prop is not None if val else prop is None, 'regex': with_valid_lhs(lambda prop, val: re.match("^{}$".format(val), prop)), # range operations 'covers': with_valid_lhs(covers_op), 'within': with_valid_lhs(within_op), # membership tests 'in': lambda prop, val: prop in val, 'contains': with_valid_lhs(lambda prop, val: val in prop), # set tests 'issubset': with_valid_lhs(lambda prop, val: _set(prop).issubset(_set(val))), 'issuperset': with_valid_lhs(lambda prop, val: _set(prop).issuperset(_set(val))), } def predicate(solver, query, val): # needs to handle kwargs like these: # key=val # key__op=val # key__key=val # key__key__op=val # LHS is split on __ in `query` assert len(query) >= 1 potential_path, potential_op_name = query[:-1], query[-1] if potential_op_name in ops: # op is explicit, and potential path is correct op_name = potential_op_name else: # op is implied and depends on property type, path is the whole query op_name = None potential_path = query path = '.'.join(potential_path) if path in solver.derived_properties: op = ops[op_name or 'eq'] return op(getattr(solver, path), val) elif pluck(solver.parameters, path, None) is not None: op = ops[op_name or 'available'] return op(pluck(solver.parameters, path), val) elif pluck(solver.properties, path, None) is not None: op = ops[op_name or 'eq'] return op(pluck(solver.properties, path), val) else: op = ops[op_name or 'eq'] return op(None, val) # param validation sort_reverse = False if not order_by: sort_key = None elif isinstance(order_by, six.string_types): if order_by[0] == '-': sort_reverse = True order_by = order_by[1:] if not order_by: sort_key = None else: sort_key = lambda solver: pluck(solver, order_by, None) elif callable(order_by): sort_key = order_by else: raise TypeError("expected string or callable for 'order_by'") # default filters: filters.setdefault('online', True) predicates = [] for lhs, val in filters.items(): query = lhs.split('__') predicates.append(partial(predicate, query=query, val=val)) _LOGGER.debug("Filtering solvers with predicates=%r", predicates) # optimization for case when exact solver name/id is known: # we can fetch only that solver # NOTE: in future, complete feature-based filtering will be on server-side query = dict(refresh_=refresh) if 'name' in filters: query['name'] = filters['name'] if 'name__eq' in filters: query['name'] = filters['name__eq'] # filter solvers = self._fetch_solvers(**query) solvers = [s for s in solvers if all(p(s) for p in predicates)] # sort: undefined (None) key values go last if sort_key is not None: solvers_with_keys = [(sort_key(solver), solver) for solver in solvers] solvers_with_invalid_keys = [(key, solver) for key, solver in solvers_with_keys if key is None] solvers_with_valid_keys = [(key, solver) for key, solver in solvers_with_keys if key is not None] solvers_with_valid_keys.sort(key=operator.itemgetter(0)) solvers = [solver for key, solver in chain(solvers_with_valid_keys, solvers_with_invalid_keys)] # reverse if necessary (as a separate step from sorting, so it works for invalid keys # and plain list reverse without sorting) if sort_reverse: solvers.reverse() return solvers
python
def get_solvers(self, refresh=False, order_by='avg_load', **filters): """Return a filtered list of solvers handled by this client. Args: refresh (bool, default=False): Force refresh of cached list of solvers/properties. order_by (callable/str/None, default='avg_load'): Solver sorting key function (or :class:`Solver` attribute/item dot-separated path). By default, solvers are sorted by average load. To explicitly not sort the solvers (and use the API-returned order), set ``order_by=None``. Signature of the `key` `callable` is:: key :: (Solver s, Ord k) => s -> k Basic structure of the `key` string path is:: "-"? (attr|item) ( "." (attr|item) )* For example, to use solver property named ``max_anneal_schedule_points``, available in ``Solver.properties`` dict, you can either specify a callable `key`:: key=lambda solver: solver.properties['max_anneal_schedule_points'] or, you can use a short string path based key:: key='properties.max_anneal_schedule_points' Solver derived properties, available as :class:`Solver` properties can also be used (e.g. ``num_active_qubits``, ``online``, ``avg_load``, etc). Ascending sort order is implied, unless the key string path does not start with ``-``, in which case descending sort is used. Note: the sort used for ordering solvers by `key` is **stable**, meaning that if multiple solvers have the same value for the key, their relative order is preserved, and effectively they are in the same order as returned by the API. Note: solvers with ``None`` for key appear last in the list of solvers. When providing a key callable, ensure all values returned are of the same type (particularly in Python 3). For solvers with undefined key value, return ``None``. **filters: See `Filtering forms` and `Operators` below. Solver filters are defined, similarly to Django QuerySet filters, with keyword arguments of form `<key1>__...__<keyN>[__<operator>]=<value>`. Each `<operator>` is a predicate (boolean) function that acts on two arguments: value of feature `<name>` (described with keys path `<key1.key2...keyN>`) and the required `<value>`. Feature `<name>` can be: 1) a derived solver property, available as an identically named :class:`Solver`'s property (`name`, `qpu`, `software`, `online`, `num_active_qubits`, `avg_load`) 2) a solver parameter, available in :obj:`Solver.parameters` 3) a solver property, available in :obj:`Solver.properties` 4) a path describing a property in nested dictionaries Filtering forms are: * <derived_property>__<operator> (object <value>) * <derived_property> (bool) This form ensures the value of solver's property bound to `derived_property`, after applying `operator` equals the `value`. The default operator is `eq`. For example:: >>> client.get_solvers(avg_load__gt=0.5) but also:: >>> client.get_solvers(online=True) >>> # identical to: >>> client.get_solvers(online__eq=True) * <parameter>__<operator> (object <value>) * <parameter> (bool) This form ensures that the solver supports `parameter`. General operator form can be used but usually does not make sense for parameters, since values are human-readable descriptions. The default operator is `available`. Example:: >>> client.get_solvers(flux_biases=True) >>> # identical to: >>> client.get_solvers(flux_biases__available=True) * <property>__<operator> (object <value>) * <property> (bool) This form ensures the value of the solver's `property`, after applying `operator` equals the righthand side `value`. The default operator is `eq`. Note: if a non-existing parameter/property name/key given, the default operator is `eq`. Operators are: * `available` (<name>: str, <value>: bool): Test availability of <name> feature. * `eq`, `lt`, `lte`, `gt`, `gte` (<name>: str, <value>: any): Standard relational operators that compare feature <name> value with <value>. * `regex` (<name>: str, <value>: str): Test regular expression matching feature value. * `covers` (<name>: str, <value>: single value or range expressed as 2-tuple/list): Test feature <name> value (which should be a *range*) covers a given value or a subrange. * `within` (<name>: str, <value>: range expressed as 2-tuple/list): Test feature <name> value (which can be a *single value* or a *range*) is within a given range. * `in` (<name>: str, <value>: container type): Test feature <name> value is *in* <value> container. * `contains` (<name>: str, <value>: any): Test feature <name> value (container type) *contains* <value>. * `issubset` (<name>: str, <value>: container type): Test feature <name> value (container type) is a subset of <value>. * `issuperset` (<name>: str, <value>: container type): Test feature <name> value (container type) is a superset of <value>. Derived properies are: * `name` (str): Solver name/id. * `qpu` (bool): Is solver QPU based? * `software` (bool): Is solver software based? * `online` (bool, default=True): Is solver online? * `num_active_qubits` (int): Number of active qubits. Less then or equal to `num_qubits`. * `avg_load` (float): Solver's average load (similar to Unix load average). Common solver parameters are: * `flux_biases`: Should solver accept flux biases? * `anneal_schedule`: Should solver accept anneal schedule? Common solver properties are: * `num_qubits` (int): Number of qubits available. * `vfyc` (bool): Should solver work on "virtual full-yield chip"? * `max_anneal_schedule_points` (int): Piecewise linear annealing schedule points. * `h_range` ([int,int]), j_range ([int,int]): Biases/couplings values range. * `num_reads_range` ([int,int]): Range of allowed values for `num_reads` parameter. Returns: list[Solver]: List of all solvers that satisfy the conditions. Note: Client subclasses (e.g. :class:`dwave.cloud.qpu.Client` or :class:`dwave.cloud.sw.Client`) already filter solvers by resource type, so for `qpu` and `software` filters to have effect, call :meth:`.get_solvers` on base class :class:`~dwave.cloud.client.Client`. Examples:: client.get_solvers( num_qubits__gt=2000, # we need more than 2000 qubits num_qubits__lt=4000, # ... but fewer than 4000 qubits num_qubits__within=(2000, 4000), # an alternative to the previous two lines num_active_qubits=1089, # we want a particular number of active qubits vfyc=True, # we require a fully yielded Chimera vfyc__in=[False, None], # inverse of the previous filter vfyc__available=False, # we want solvers that do not advertize the vfyc property anneal_schedule=True, # we need support for custom anneal schedule max_anneal_schedule_points__gte=4, # we need at least 4 points for our anneal schedule num_reads_range__covers=1000, # our solver must support returning 1000 reads extended_j_range__covers=[-2, 2], # we need extended J range to contain subrange [-2,2] couplings__contains=[0, 128], # coupling (edge between) qubits (0,128) must exist couplings__issuperset=[[0,128], [0,4]], # two couplings required: (0,128) and (0,4) qubits__issuperset={0, 4, 215}, # qubits 0, 4 and 215 must exist supported_problem_types__issubset={'ising', 'qubo'}, # require Ising, QUBO or both to be supported name='DW_2000Q_3', # full solver name/ID match name__regex='.*2000.*', # partial/regex-based solver name match chip_id__regex='DW_.*', # chip ID prefix must be DW_ topology__type__eq="chimera" # topology.type must be chimera ) """ def covers_op(prop, val): """Does LHS `prop` (range) fully cover RHS `val` (range or item)?""" # `prop` must be a 2-element list/tuple range. if not isinstance(prop, (list, tuple)) or not len(prop) == 2: raise ValueError("2-element list/tuple range required for LHS value") llo, lhi = min(prop), max(prop) # `val` can be a single value, or a range (2-list/2-tuple). if isinstance(val, (list, tuple)) and len(val) == 2: # val range within prop range? rlo, rhi = min(val), max(val) return llo <= rlo and lhi >= rhi else: # val item within prop range? return llo <= val <= lhi def within_op(prop, val): """Is LHS `prop` (range or item) fully covered by RHS `val` (range)?""" try: return covers_op(val, prop) except ValueError: raise ValueError("2-element list/tuple range required for RHS value") def _set(iterable): """Like set(iterable), but works for lists as items in iterable. Before constructing a set, lists are converted to tuples. """ first = next(iter(iterable)) if isinstance(first, list): return set(tuple(x) for x in iterable) return set(iterable) def with_valid_lhs(op): @wraps(op) def _wrapper(prop, val): if prop is None: return False return op(prop, val) return _wrapper # available filtering operators ops = { 'lt': with_valid_lhs(operator.lt), 'lte': with_valid_lhs(operator.le), 'gt': with_valid_lhs(operator.gt), 'gte': with_valid_lhs(operator.ge), 'eq': operator.eq, 'available': lambda prop, val: prop is not None if val else prop is None, 'regex': with_valid_lhs(lambda prop, val: re.match("^{}$".format(val), prop)), # range operations 'covers': with_valid_lhs(covers_op), 'within': with_valid_lhs(within_op), # membership tests 'in': lambda prop, val: prop in val, 'contains': with_valid_lhs(lambda prop, val: val in prop), # set tests 'issubset': with_valid_lhs(lambda prop, val: _set(prop).issubset(_set(val))), 'issuperset': with_valid_lhs(lambda prop, val: _set(prop).issuperset(_set(val))), } def predicate(solver, query, val): # needs to handle kwargs like these: # key=val # key__op=val # key__key=val # key__key__op=val # LHS is split on __ in `query` assert len(query) >= 1 potential_path, potential_op_name = query[:-1], query[-1] if potential_op_name in ops: # op is explicit, and potential path is correct op_name = potential_op_name else: # op is implied and depends on property type, path is the whole query op_name = None potential_path = query path = '.'.join(potential_path) if path in solver.derived_properties: op = ops[op_name or 'eq'] return op(getattr(solver, path), val) elif pluck(solver.parameters, path, None) is not None: op = ops[op_name or 'available'] return op(pluck(solver.parameters, path), val) elif pluck(solver.properties, path, None) is not None: op = ops[op_name or 'eq'] return op(pluck(solver.properties, path), val) else: op = ops[op_name or 'eq'] return op(None, val) # param validation sort_reverse = False if not order_by: sort_key = None elif isinstance(order_by, six.string_types): if order_by[0] == '-': sort_reverse = True order_by = order_by[1:] if not order_by: sort_key = None else: sort_key = lambda solver: pluck(solver, order_by, None) elif callable(order_by): sort_key = order_by else: raise TypeError("expected string or callable for 'order_by'") # default filters: filters.setdefault('online', True) predicates = [] for lhs, val in filters.items(): query = lhs.split('__') predicates.append(partial(predicate, query=query, val=val)) _LOGGER.debug("Filtering solvers with predicates=%r", predicates) # optimization for case when exact solver name/id is known: # we can fetch only that solver # NOTE: in future, complete feature-based filtering will be on server-side query = dict(refresh_=refresh) if 'name' in filters: query['name'] = filters['name'] if 'name__eq' in filters: query['name'] = filters['name__eq'] # filter solvers = self._fetch_solvers(**query) solvers = [s for s in solvers if all(p(s) for p in predicates)] # sort: undefined (None) key values go last if sort_key is not None: solvers_with_keys = [(sort_key(solver), solver) for solver in solvers] solvers_with_invalid_keys = [(key, solver) for key, solver in solvers_with_keys if key is None] solvers_with_valid_keys = [(key, solver) for key, solver in solvers_with_keys if key is not None] solvers_with_valid_keys.sort(key=operator.itemgetter(0)) solvers = [solver for key, solver in chain(solvers_with_valid_keys, solvers_with_invalid_keys)] # reverse if necessary (as a separate step from sorting, so it works for invalid keys # and plain list reverse without sorting) if sort_reverse: solvers.reverse() return solvers
[ "def", "get_solvers", "(", "self", ",", "refresh", "=", "False", ",", "order_by", "=", "'avg_load'", ",", "*", "*", "filters", ")", ":", "def", "covers_op", "(", "prop", ",", "val", ")", ":", "\"\"\"Does LHS `prop` (range) fully cover RHS `val` (range or item)?\"\"\"", "# `prop` must be a 2-element list/tuple range.", "if", "not", "isinstance", "(", "prop", ",", "(", "list", ",", "tuple", ")", ")", "or", "not", "len", "(", "prop", ")", "==", "2", ":", "raise", "ValueError", "(", "\"2-element list/tuple range required for LHS value\"", ")", "llo", ",", "lhi", "=", "min", "(", "prop", ")", ",", "max", "(", "prop", ")", "# `val` can be a single value, or a range (2-list/2-tuple).", "if", "isinstance", "(", "val", ",", "(", "list", ",", "tuple", ")", ")", "and", "len", "(", "val", ")", "==", "2", ":", "# val range within prop range?", "rlo", ",", "rhi", "=", "min", "(", "val", ")", ",", "max", "(", "val", ")", "return", "llo", "<=", "rlo", "and", "lhi", ">=", "rhi", "else", ":", "# val item within prop range?", "return", "llo", "<=", "val", "<=", "lhi", "def", "within_op", "(", "prop", ",", "val", ")", ":", "\"\"\"Is LHS `prop` (range or item) fully covered by RHS `val` (range)?\"\"\"", "try", ":", "return", "covers_op", "(", "val", ",", "prop", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "\"2-element list/tuple range required for RHS value\"", ")", "def", "_set", "(", "iterable", ")", ":", "\"\"\"Like set(iterable), but works for lists as items in iterable.\n Before constructing a set, lists are converted to tuples.\n \"\"\"", "first", "=", "next", "(", "iter", "(", "iterable", ")", ")", "if", "isinstance", "(", "first", ",", "list", ")", ":", "return", "set", "(", "tuple", "(", "x", ")", "for", "x", "in", "iterable", ")", "return", "set", "(", "iterable", ")", "def", "with_valid_lhs", "(", "op", ")", ":", "@", "wraps", "(", "op", ")", "def", "_wrapper", "(", "prop", ",", "val", ")", ":", "if", "prop", "is", "None", ":", "return", "False", "return", "op", "(", "prop", ",", "val", ")", "return", "_wrapper", "# available filtering operators", "ops", "=", "{", "'lt'", ":", "with_valid_lhs", "(", "operator", ".", "lt", ")", ",", "'lte'", ":", "with_valid_lhs", "(", "operator", ".", "le", ")", ",", "'gt'", ":", "with_valid_lhs", "(", "operator", ".", "gt", ")", ",", "'gte'", ":", "with_valid_lhs", "(", "operator", ".", "ge", ")", ",", "'eq'", ":", "operator", ".", "eq", ",", "'available'", ":", "lambda", "prop", ",", "val", ":", "prop", "is", "not", "None", "if", "val", "else", "prop", "is", "None", ",", "'regex'", ":", "with_valid_lhs", "(", "lambda", "prop", ",", "val", ":", "re", ".", "match", "(", "\"^{}$\"", ".", "format", "(", "val", ")", ",", "prop", ")", ")", ",", "# range operations", "'covers'", ":", "with_valid_lhs", "(", "covers_op", ")", ",", "'within'", ":", "with_valid_lhs", "(", "within_op", ")", ",", "# membership tests", "'in'", ":", "lambda", "prop", ",", "val", ":", "prop", "in", "val", ",", "'contains'", ":", "with_valid_lhs", "(", "lambda", "prop", ",", "val", ":", "val", "in", "prop", ")", ",", "# set tests", "'issubset'", ":", "with_valid_lhs", "(", "lambda", "prop", ",", "val", ":", "_set", "(", "prop", ")", ".", "issubset", "(", "_set", "(", "val", ")", ")", ")", ",", "'issuperset'", ":", "with_valid_lhs", "(", "lambda", "prop", ",", "val", ":", "_set", "(", "prop", ")", ".", "issuperset", "(", "_set", "(", "val", ")", ")", ")", ",", "}", "def", "predicate", "(", "solver", ",", "query", ",", "val", ")", ":", "# needs to handle kwargs like these:", "# key=val", "# key__op=val", "# key__key=val", "# key__key__op=val", "# LHS is split on __ in `query`", "assert", "len", "(", "query", ")", ">=", "1", "potential_path", ",", "potential_op_name", "=", "query", "[", ":", "-", "1", "]", ",", "query", "[", "-", "1", "]", "if", "potential_op_name", "in", "ops", ":", "# op is explicit, and potential path is correct", "op_name", "=", "potential_op_name", "else", ":", "# op is implied and depends on property type, path is the whole query", "op_name", "=", "None", "potential_path", "=", "query", "path", "=", "'.'", ".", "join", "(", "potential_path", ")", "if", "path", "in", "solver", ".", "derived_properties", ":", "op", "=", "ops", "[", "op_name", "or", "'eq'", "]", "return", "op", "(", "getattr", "(", "solver", ",", "path", ")", ",", "val", ")", "elif", "pluck", "(", "solver", ".", "parameters", ",", "path", ",", "None", ")", "is", "not", "None", ":", "op", "=", "ops", "[", "op_name", "or", "'available'", "]", "return", "op", "(", "pluck", "(", "solver", ".", "parameters", ",", "path", ")", ",", "val", ")", "elif", "pluck", "(", "solver", ".", "properties", ",", "path", ",", "None", ")", "is", "not", "None", ":", "op", "=", "ops", "[", "op_name", "or", "'eq'", "]", "return", "op", "(", "pluck", "(", "solver", ".", "properties", ",", "path", ")", ",", "val", ")", "else", ":", "op", "=", "ops", "[", "op_name", "or", "'eq'", "]", "return", "op", "(", "None", ",", "val", ")", "# param validation", "sort_reverse", "=", "False", "if", "not", "order_by", ":", "sort_key", "=", "None", "elif", "isinstance", "(", "order_by", ",", "six", ".", "string_types", ")", ":", "if", "order_by", "[", "0", "]", "==", "'-'", ":", "sort_reverse", "=", "True", "order_by", "=", "order_by", "[", "1", ":", "]", "if", "not", "order_by", ":", "sort_key", "=", "None", "else", ":", "sort_key", "=", "lambda", "solver", ":", "pluck", "(", "solver", ",", "order_by", ",", "None", ")", "elif", "callable", "(", "order_by", ")", ":", "sort_key", "=", "order_by", "else", ":", "raise", "TypeError", "(", "\"expected string or callable for 'order_by'\"", ")", "# default filters:", "filters", ".", "setdefault", "(", "'online'", ",", "True", ")", "predicates", "=", "[", "]", "for", "lhs", ",", "val", "in", "filters", ".", "items", "(", ")", ":", "query", "=", "lhs", ".", "split", "(", "'__'", ")", "predicates", ".", "append", "(", "partial", "(", "predicate", ",", "query", "=", "query", ",", "val", "=", "val", ")", ")", "_LOGGER", ".", "debug", "(", "\"Filtering solvers with predicates=%r\"", ",", "predicates", ")", "# optimization for case when exact solver name/id is known:", "# we can fetch only that solver", "# NOTE: in future, complete feature-based filtering will be on server-side", "query", "=", "dict", "(", "refresh_", "=", "refresh", ")", "if", "'name'", "in", "filters", ":", "query", "[", "'name'", "]", "=", "filters", "[", "'name'", "]", "if", "'name__eq'", "in", "filters", ":", "query", "[", "'name'", "]", "=", "filters", "[", "'name__eq'", "]", "# filter", "solvers", "=", "self", ".", "_fetch_solvers", "(", "*", "*", "query", ")", "solvers", "=", "[", "s", "for", "s", "in", "solvers", "if", "all", "(", "p", "(", "s", ")", "for", "p", "in", "predicates", ")", "]", "# sort: undefined (None) key values go last", "if", "sort_key", "is", "not", "None", ":", "solvers_with_keys", "=", "[", "(", "sort_key", "(", "solver", ")", ",", "solver", ")", "for", "solver", "in", "solvers", "]", "solvers_with_invalid_keys", "=", "[", "(", "key", ",", "solver", ")", "for", "key", ",", "solver", "in", "solvers_with_keys", "if", "key", "is", "None", "]", "solvers_with_valid_keys", "=", "[", "(", "key", ",", "solver", ")", "for", "key", ",", "solver", "in", "solvers_with_keys", "if", "key", "is", "not", "None", "]", "solvers_with_valid_keys", ".", "sort", "(", "key", "=", "operator", ".", "itemgetter", "(", "0", ")", ")", "solvers", "=", "[", "solver", "for", "key", ",", "solver", "in", "chain", "(", "solvers_with_valid_keys", ",", "solvers_with_invalid_keys", ")", "]", "# reverse if necessary (as a separate step from sorting, so it works for invalid keys", "# and plain list reverse without sorting)", "if", "sort_reverse", ":", "solvers", ".", "reverse", "(", ")", "return", "solvers" ]
Return a filtered list of solvers handled by this client. Args: refresh (bool, default=False): Force refresh of cached list of solvers/properties. order_by (callable/str/None, default='avg_load'): Solver sorting key function (or :class:`Solver` attribute/item dot-separated path). By default, solvers are sorted by average load. To explicitly not sort the solvers (and use the API-returned order), set ``order_by=None``. Signature of the `key` `callable` is:: key :: (Solver s, Ord k) => s -> k Basic structure of the `key` string path is:: "-"? (attr|item) ( "." (attr|item) )* For example, to use solver property named ``max_anneal_schedule_points``, available in ``Solver.properties`` dict, you can either specify a callable `key`:: key=lambda solver: solver.properties['max_anneal_schedule_points'] or, you can use a short string path based key:: key='properties.max_anneal_schedule_points' Solver derived properties, available as :class:`Solver` properties can also be used (e.g. ``num_active_qubits``, ``online``, ``avg_load``, etc). Ascending sort order is implied, unless the key string path does not start with ``-``, in which case descending sort is used. Note: the sort used for ordering solvers by `key` is **stable**, meaning that if multiple solvers have the same value for the key, their relative order is preserved, and effectively they are in the same order as returned by the API. Note: solvers with ``None`` for key appear last in the list of solvers. When providing a key callable, ensure all values returned are of the same type (particularly in Python 3). For solvers with undefined key value, return ``None``. **filters: See `Filtering forms` and `Operators` below. Solver filters are defined, similarly to Django QuerySet filters, with keyword arguments of form `<key1>__...__<keyN>[__<operator>]=<value>`. Each `<operator>` is a predicate (boolean) function that acts on two arguments: value of feature `<name>` (described with keys path `<key1.key2...keyN>`) and the required `<value>`. Feature `<name>` can be: 1) a derived solver property, available as an identically named :class:`Solver`'s property (`name`, `qpu`, `software`, `online`, `num_active_qubits`, `avg_load`) 2) a solver parameter, available in :obj:`Solver.parameters` 3) a solver property, available in :obj:`Solver.properties` 4) a path describing a property in nested dictionaries Filtering forms are: * <derived_property>__<operator> (object <value>) * <derived_property> (bool) This form ensures the value of solver's property bound to `derived_property`, after applying `operator` equals the `value`. The default operator is `eq`. For example:: >>> client.get_solvers(avg_load__gt=0.5) but also:: >>> client.get_solvers(online=True) >>> # identical to: >>> client.get_solvers(online__eq=True) * <parameter>__<operator> (object <value>) * <parameter> (bool) This form ensures that the solver supports `parameter`. General operator form can be used but usually does not make sense for parameters, since values are human-readable descriptions. The default operator is `available`. Example:: >>> client.get_solvers(flux_biases=True) >>> # identical to: >>> client.get_solvers(flux_biases__available=True) * <property>__<operator> (object <value>) * <property> (bool) This form ensures the value of the solver's `property`, after applying `operator` equals the righthand side `value`. The default operator is `eq`. Note: if a non-existing parameter/property name/key given, the default operator is `eq`. Operators are: * `available` (<name>: str, <value>: bool): Test availability of <name> feature. * `eq`, `lt`, `lte`, `gt`, `gte` (<name>: str, <value>: any): Standard relational operators that compare feature <name> value with <value>. * `regex` (<name>: str, <value>: str): Test regular expression matching feature value. * `covers` (<name>: str, <value>: single value or range expressed as 2-tuple/list): Test feature <name> value (which should be a *range*) covers a given value or a subrange. * `within` (<name>: str, <value>: range expressed as 2-tuple/list): Test feature <name> value (which can be a *single value* or a *range*) is within a given range. * `in` (<name>: str, <value>: container type): Test feature <name> value is *in* <value> container. * `contains` (<name>: str, <value>: any): Test feature <name> value (container type) *contains* <value>. * `issubset` (<name>: str, <value>: container type): Test feature <name> value (container type) is a subset of <value>. * `issuperset` (<name>: str, <value>: container type): Test feature <name> value (container type) is a superset of <value>. Derived properies are: * `name` (str): Solver name/id. * `qpu` (bool): Is solver QPU based? * `software` (bool): Is solver software based? * `online` (bool, default=True): Is solver online? * `num_active_qubits` (int): Number of active qubits. Less then or equal to `num_qubits`. * `avg_load` (float): Solver's average load (similar to Unix load average). Common solver parameters are: * `flux_biases`: Should solver accept flux biases? * `anneal_schedule`: Should solver accept anneal schedule? Common solver properties are: * `num_qubits` (int): Number of qubits available. * `vfyc` (bool): Should solver work on "virtual full-yield chip"? * `max_anneal_schedule_points` (int): Piecewise linear annealing schedule points. * `h_range` ([int,int]), j_range ([int,int]): Biases/couplings values range. * `num_reads_range` ([int,int]): Range of allowed values for `num_reads` parameter. Returns: list[Solver]: List of all solvers that satisfy the conditions. Note: Client subclasses (e.g. :class:`dwave.cloud.qpu.Client` or :class:`dwave.cloud.sw.Client`) already filter solvers by resource type, so for `qpu` and `software` filters to have effect, call :meth:`.get_solvers` on base class :class:`~dwave.cloud.client.Client`. Examples:: client.get_solvers( num_qubits__gt=2000, # we need more than 2000 qubits num_qubits__lt=4000, # ... but fewer than 4000 qubits num_qubits__within=(2000, 4000), # an alternative to the previous two lines num_active_qubits=1089, # we want a particular number of active qubits vfyc=True, # we require a fully yielded Chimera vfyc__in=[False, None], # inverse of the previous filter vfyc__available=False, # we want solvers that do not advertize the vfyc property anneal_schedule=True, # we need support for custom anneal schedule max_anneal_schedule_points__gte=4, # we need at least 4 points for our anneal schedule num_reads_range__covers=1000, # our solver must support returning 1000 reads extended_j_range__covers=[-2, 2], # we need extended J range to contain subrange [-2,2] couplings__contains=[0, 128], # coupling (edge between) qubits (0,128) must exist couplings__issuperset=[[0,128], [0,4]], # two couplings required: (0,128) and (0,4) qubits__issuperset={0, 4, 215}, # qubits 0, 4 and 215 must exist supported_problem_types__issubset={'ising', 'qubo'}, # require Ising, QUBO or both to be supported name='DW_2000Q_3', # full solver name/ID match name__regex='.*2000.*', # partial/regex-based solver name match chip_id__regex='DW_.*', # chip ID prefix must be DW_ topology__type__eq="chimera" # topology.type must be chimera )
[ "Return", "a", "filtered", "list", "of", "solvers", "handled", "by", "this", "client", "." ]
df3221a8385dc0c04d7b4d84f740bf3ad6706230
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/client.py#L553-L885
train
dwavesystems/dwave-cloud-client
dwave/cloud/client.py
Client.solvers
def solvers(self, refresh=False, **filters): """Deprecated in favor of :meth:`.get_solvers`.""" warnings.warn("'solvers' is deprecated in favor of 'get_solvers'.", DeprecationWarning) return self.get_solvers(refresh=refresh, **filters)
python
def solvers(self, refresh=False, **filters): """Deprecated in favor of :meth:`.get_solvers`.""" warnings.warn("'solvers' is deprecated in favor of 'get_solvers'.", DeprecationWarning) return self.get_solvers(refresh=refresh, **filters)
[ "def", "solvers", "(", "self", ",", "refresh", "=", "False", ",", "*", "*", "filters", ")", ":", "warnings", ".", "warn", "(", "\"'solvers' is deprecated in favor of 'get_solvers'.\"", ",", "DeprecationWarning", ")", "return", "self", ".", "get_solvers", "(", "refresh", "=", "refresh", ",", "*", "*", "filters", ")" ]
Deprecated in favor of :meth:`.get_solvers`.
[ "Deprecated", "in", "favor", "of", ":", "meth", ":", ".", "get_solvers", "." ]
df3221a8385dc0c04d7b4d84f740bf3ad6706230
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/client.py#L887-L890
train