def replace_qubits( circuit: cirq.Circuit, qubit_map: typing.Mapping ): old_qubits = set(qubit_map.keys()) new_qubits = set(qubit_map.values()) if len(old_qubits) != len(new_qubits): raise ValueError( "`qubit_map` must be a bijective mapping." ) qubits_in_circuit = circuit.all_qubits() unknown_old_qubits = old_qubits - qubits_in_circuit if unknown_old_qubits: raise ValueError( "Some qubits in `old_qubits` do not exist in the original circuit: " f"{unknown_old_qubits}" ) new_circuit = cirq.Circuit() for moment in circuit: new_moment = cirq.Moment() for operation in moment: new_operation = operation.gate.on( *(qubit_map[q] for q in operation.qubits) ) new_moment += new_operation new_circuit += new_moment return new_circuit
def onedict_value(d: t.Mapping) -> t.Any: """ Get the value of a single-entry dictionary. Parameters ---------- d : mapping A single-entry mapping. Returns ------- object Unwrapped value. Raises ------ ValueError If ``d`` has more than a single element. Notes ----- This function is basically ``next(iter(d.values()))`` with a safeguard. Examples -------- >>> onedict_value({"foo": "bar"}) "bar" """ if len(d) != 1: raise ValueError(f"dictionary has wrong length (expected 1, got {len(d)}") return next(iter(d.values()))
def _map_allotypes(df: pd.DataFrame, df_name: str, mapping: t.Mapping) -> pd.DataFrame: """ A helper function helping to map allotype names in df having `accession` field to accessions. Logging will warn a user about unmapped allotypes. :param df: DataFrame with `allotype` field present. :param df_name: Name of the df (used for logging) :param mapping: Mapping between allotype names and accessions. :return: DataFrame with a new `accession` field. """ # Prevent SettingWithCopyWarning df = df.copy() # Map allotypes accessions df['accession'] = df['allotype'].map(mapping) # Warn about unmapped allotypes unmapped_allotypes_loc = ~df['accession'].isin(set(mapping.values())) if unmapped_allotypes_loc.any(): df.loc[unmapped_allotypes_loc, 'accession'] = np.nan unmapped_allotypes = df.loc[unmapped_allotypes_loc, "allotype"].sort_values().unique() logging.warning( f'{df_name} -- could not map {len(unmapped_allotypes)} ' f'allotypes {unmapped_allotypes} corresponding to ' f'{unmapped_allotypes_loc.sum()} records') # Filter out unmapped allotypes df = df[~df['accession'].isna()] logging.info( f'{df_name} -- filtered out unmapped allotypes; records: {len(df)}') return df
def saturate_mapping(self, value: t.Mapping) -> None: try: assert isinstance(value, t.Mapping), "must be a mapping" assert value, "must not be empty" assert dict_depth(value) == 1, "must be a mapping of depth 1" assert all(isinstance(_, int) for _ in value.values()), "must have int values" except AssertionError as e: raise LayerMisconfigured("saturate_mapping {}, got {}".format(*e.args, value)) if any(isinstance(_, str) for _ in value.keys()): _ = {} for k, v in value.items(): _[int(k)] = v value = _ self._saturate_mapping = dict(sorted(value.items(), key=lambda i: i[0]))
def from_dict(cls, dikt: typing.Mapping) -> 'About': dikt = dict(zip((x.strip('__') for x in dikt.keys()), dikt.values())) sig = inspect.signature(cls) return cls(**sig.bind( **{x: y for x, y in dikt.items() if x in sig.parameters}).arguments)
def mis_vals(d: typ.Mapping) -> typ.Generator[typ.Any, None, None]: yield from d.values()