def relabel(self, mapping): try: old_labels = set(mapping) new_labels = set(mapping.values()) except TypeError: raise ValueError("mapping targets must be hashable objects") for v in new_labels: if v in self and v not in old_labels: raise ValueError(( 'A variable cannot be relabeled "{}" without also relabeling ' "the existing variable of the same name").format(v)) if any(v in new_labels for v in old_labels): old_to_intermediate, intermediate_to_new = resolve_label_conflict( mapping, old_labels, new_labels) self.relabel(old_to_intermediate) self.relabel(intermediate_to_new) return label = self._label index = self.index for old, new in mapping.items(): label[index[old]] = new index[new] = index[old] del index[old]
def relabel_variables(self, mapping, inplace=True): """Relabel a response's variables as per a given mapping. Args: mapping (dict): Dict mapping current variable labels to new. If an incomplete mapping is provided, unmapped variables keep their original labels inplace (bool, optional, default=True): If True, the original response is updated; otherwise a new response is returned. Returns: :class:`.Response`: Response with relabeled variables. If inplace=True, returns itself. Examples: Create a relabeled copy of a response >>> import dimod ... >>> response = dimod.ExactSolver().sample_ising({'a': -0.5, 'b': 1.0}, {('a', 'b'): -1}) >>> new_response = response.relabel_variables({'a': 0, 'b': 1}, inplace=False) >>> response.variable_labels # doctest: +SKIP [0, 1] """ if not inplace: return self.copy().relabel_variables(mapping, inplace=True) try: old_labels = set(mapping.keys()) new_labels = set(mapping.values()) except TypeError: raise ValueError("mapping targets must be hashable objects") for v in self.variable_labels: if v in new_labels and v not in old_labels: raise ValueError(( 'A variable cannot be relabeled "{}" without also relabeling ' "the existing variable of the same name").format(v)) shared = old_labels & new_labels if shared: old_to_intermediate, intermediate_to_new = resolve_label_conflict( mapping, old_labels, new_labels) self.relabel_variables(old_to_intermediate, inplace=True) self.relabel_variables(intermediate_to_new, inplace=True) return self self._variable_labels = labels = [ mapping.get(v, v) for v in self.variable_labels ] self._label_to_idx = {v: idx for idx, v in enumerate(labels)} return self
def relabel_variables(self, mapping, inplace=True): """Relabel the variables of a :class:`SampleSet` according to the specified mapping. Args: mapping (dict): Mapping from current variable labels to new, as a dict. If incomplete mapping is specified, unmapped variables keep their current labels. inplace (bool, optional, default=True): If True, the current :class:`SampleSet` is updated; otherwise, a new :class:`SampleSet` is returned. Returns: :class:`.SampleSet`: SampleSet with relabeled variables. If `inplace` is True, returns itself. Examples: This example creates a relabeled copy of a :class:`SampleSet`. >>> import dimod ... >>> sampleset = dimod.ExactSolver().sample_ising({'a': -0.5, 'b': 1.0}, {('a', 'b'): -1}) >>> new_sampleset = sampleset.relabel_variables({'a': 0, 'b': 1}, inplace=False) >>> sampleset.variable_labels # doctest: +SKIP [0, 1] """ if not inplace: return self.copy().relabel_variables(mapping, inplace=True) try: old_labels = set(mapping.keys()) new_labels = set(mapping.values()) except TypeError: raise ValueError("mapping targets must be hashable objects") for v in self.variables: if v in new_labels and v not in old_labels: raise ValueError(( 'A variable cannot be relabeled "{}" without also relabeling ' "the existing variable of the same name").format(v)) shared = old_labels & new_labels if shared: old_to_intermediate, intermediate_to_new = resolve_label_conflict( mapping, old_labels, new_labels) self.relabel_variables(old_to_intermediate, inplace=True) self.relabel_variables(intermediate_to_new, inplace=True) return self self._variables = VariableIndexView( mapping.get(v, v) for v in self.variables) return self
def relabel_variables(self, mapping, inplace=True): """Relabel variables of a binary polynomial as specified by mapping. Args: mapping (dict): Dict mapping current variable labels to new ones. If an incomplete mapping is provided, unmapped variables retain their current labels. inplace (bool, optional, default=True): If True, the binary polynomial is updated in-place; otherwise, a new binary polynomial is returned. Returns: :class:`.BinaryPolynomial`: A binary polynomial with the variables relabeled. If `inplace` is set to True, returns itself. """ if not inplace: return self.copy().relabel_variables(mapping, inplace=True) try: old_labels = set(mapping) new_labels = set(mapping.values()) except TypeError: raise ValueError("mapping targets must be hashable objects") variables = self.variables for v in new_labels: if v in variables and v not in old_labels: raise ValueError(( 'A variable cannot be relabeled "{}" without also relabeling ' "the existing variable of the same name").format(v)) shared = old_labels & new_labels if shared: old_to_intermediate, intermediate_to_new = resolve_label_conflict( mapping, old_labels, new_labels) self.relabel_variables(old_to_intermediate, inplace=True) self.relabel_variables(intermediate_to_new, inplace=True) return self for oldterm, bias in list(self.items()): newterm = frozenset((mapping.get(v, v) for v in oldterm)) if newterm != oldterm: self[newterm] = bias del self[oldterm] return self
def relabel(self, mapping): # put the new labels into a set for fast lookup try: new_labels = set(mapping.values()) except TypeError: # when new labels are not hashable raise ValueError("mapping targets must be hashable objects") if PY3: old_labels = mapping.keys() else: # we actually want old_labels to be a keysview like in python3 # but since we don't get that in python2 we just use the mapping # itself and treat it as a set rather than a dict. old_labels = mapping for v in new_labels: if v in self and v not in old_labels: msg = ("A variable cannot be relabeled {!r} without also " "relabeling the existing variable of the same name") raise ValueError(msg.format(v)) if any(v in new_labels for v in old_labels): old_to_intermediate, intermediate_to_new = resolve_label_conflict( mapping, old_labels, new_labels) self.relabel(old_to_intermediate) self.relabel(intermediate_to_new) return label = self._label index = self.index for old, new in mapping.items(): if old not in self: continue label[index[old]] = new index[new] = index[old] del index[old]
def relabel_variables(self, mapping, inplace=True): """Relabel a response's variables as per a given mapping. Args: mapping (dict): Dict mapping current variable labels to new. If an incomplete mapping is provided, unmapped variables keep their original labels inplace (bool, optional, default=True): If True, the original response is updated; otherwise a new response is returned. Returns: :class:`.Response`: Response with relabeled variables. If inplace=True, returns itself. Examples: This example relabels variables in a response. .. code-block:: python response = dimod.Response.from_dicts([{'a': -1}, {'a': +1}], {'energy': [-1, 1]}) response.relabel_variables({'a': 0}) This example creates a new response with relabeled variables. .. code-block:: python response = dimod.Response.from_dicts([{'a': -1}, {'a': +1}], {'energy': [-1, 1]}) new_response = response.relabel_variables({'a': 0}, inplace=False) """ if not inplace: return self.copy().relabel_variables(mapping, inplace=True) # we need labels if self.variable_labels is None: __, num_variables = self.samples_matrix.shape self.variable_labels = list(range(num_variables)) try: old_labels = set(mapping) new_labels = set(itervalues(mapping)) except TypeError: raise ValueError("mapping targets must be hashable objects") for v in new_labels: if v in self.variable_labels and v not in old_labels: raise ValueError(( 'A variable cannot be relabeled "{}" without also relabeling ' "the existing variable of the same name").format(v)) shared = old_labels & new_labels if shared: old_to_intermediate, intermediate_to_new = resolve_label_conflict( mapping, old_labels, new_labels) self.relabel_variables(old_to_intermediate, inplace=True) self.relabel_variables(intermediate_to_new, inplace=True) return self self.variable_labels = variable_labels = [ mapping.get(v, v) for v in self.variable_labels ] self.label_to_idx = {v: idx for idx, v in enumerate(variable_labels)} return self