text
stringlengths
81
112k
载入用户自定义的单字拼音库 :param pinyin_dict: 单字拼音库。比如: ``{0x963F: u"ā,ē"}`` :param style: pinyin_dict 参数值的拼音库风格. 支持 'default', 'tone2' :type pinyin_dict: dict def load_single_dict(pinyin_dict, style='default'): """载入用户自定义的单字拼音库 :param pinyin_dict: 单字拼音库。比如: ``{0x963F: u"ā,ē"}`` :param style: pinyin_dict...
载入用户自定义的词语拼音库 :param phrases_dict: 词语拼音库。比如: ``{u"阿爸": [[u"ā"], [u"bà"]]}`` :param style: phrases_dict 参数值的拼音库风格. 支持 'default', 'tone2' :type phrases_dict: dict def load_phrases_dict(phrases_dict, style='default'): """载入用户自定义的词语拼音库 :param phrases_dict: 词语拼音库。比如: ``{u"阿爸": [[u"ā"], [u"bà"]]}`` ...
根据拼音风格格式化带声调的拼音. :param pinyin: 单个拼音 :param style: 拼音风格 :param strict: 是否严格遵照《汉语拼音方案》来处理声母和韵母 :return: 根据拼音风格格式化后的拼音字符串 :rtype: unicode def to_fixed(pinyin, style, strict=True): """根据拼音风格格式化带声调的拼音. :param pinyin: 单个拼音 :param style: 拼音风格 :param strict: 是否严格遵照《汉语拼音方案》来处理声母和韵母 :r...
处理没有拼音的字符 def _handle_nopinyin_char(chars, errors='default'): """处理没有拼音的字符""" if callable_check(errors): return errors(chars) if errors == 'default': return chars elif errors == 'ignore': return None elif errors == 'replace': if len(chars) > 1: return ''...
单字拼音转换. :param han: 单个汉字 :param errors: 指定如何处理没有拼音的字符,详情请参考 :py:func:`~pypinyin.pinyin` :param strict: 是否严格遵照《汉语拼音方案》来处理声母和韵母 :return: 返回拼音列表,多音字会有多个拼音项 :rtype: list def single_pinyin(han, style, heteronym, errors='default', strict=True): """单字拼音转换. :param han: 单个汉字 ...
词语拼音转换. :param phrase: 词语 :param errors: 指定如何处理没有拼音的字符 :param strict: 是否严格遵照《汉语拼音方案》来处理声母和韵母 :return: 拼音列表 :rtype: list def phrase_pinyin(phrase, style, heteronym, errors='default', strict=True): """词语拼音转换. :param phrase: 词语 :param errors: 指定如何处理没有拼音的字符 :param strict: 是否严格遵照《汉语拼音方...
:param words: 经过分词处理后的字符串,只包含中文字符或只包含非中文字符, 不存在混合的情况。 def _pinyin(words, style, heteronym, errors, strict=True): """ :param words: 经过分词处理后的字符串,只包含中文字符或只包含非中文字符, 不存在混合的情况。 """ pys = [] # 初步过滤没有拼音的字符 if RE_HANS.match(words): pys = phrase_pinyin(words, s...
将汉字转换为拼音. :param hans: 汉字字符串( ``'你好吗'`` )或列表( ``['你好', '吗']`` ). 可以使用自己喜爱的分词模块对字符串进行分词处理, 只需将经过分词处理的字符串列表传进来就可以了。 :type hans: unicode 字符串或字符串列表 :param style: 指定拼音风格,默认是 :py:attr:`~pypinyin.Style.TONE` 风格。 更多拼音风格详见 :class:`~pypinyin.Style` :param error...
生成 slug 字符串. :param hans: 汉字 :type hans: unicode or list :param style: 指定拼音风格,默认是 :py:attr:`~pypinyin.Style.NORMAL` 风格。 更多拼音风格详见 :class:`~pypinyin.Style` :param heteronym: 是否启用多音字 :param separstor: 两个拼音间的分隔符/连接符 :param errors: 指定如何处理没有拼音的字符,详情请参考 :py:func:`~...
不包含多音字的拼音列表. 与 :py:func:`~pypinyin.pinyin` 的区别是返回的拼音是个字符串, 并且每个字只包含一个读音. :param hans: 汉字 :type hans: unicode or list :param style: 指定拼音风格,默认是 :py:attr:`~pypinyin.Style.NORMAL` 风格。 更多拼音风格详见 :class:`~pypinyin.Style`。 :param errors: 指定如何处理没有拼音的字符,详情请参考 :py:fun...
根据拼音风格把原始拼音转换为不同的格式 :param pinyin: 原始有声调的单个拼音 :type pinyin: unicode :param style: 拼音风格 :param strict: 是否严格遵照《汉语拼音方案》来处理声母和韵母,详见 :ref:`strict` :type strict: bool :param default: 拼音风格对应的实现不存在时返回的默认值 :return: 按照拼音风格进行处理过后的拼音字符串 :rtype: unicode def convert(pinyin, style, strict, default=No...
注册一个拼音风格实现 :: @register('echo') def echo(pinyin, **kwargs): return pinyin # or register('echo', echo) def register(style, func=None): """注册一个拼音风格实现 :: @register('echo') def echo(pinyin, **kwargs): return pinyin # or ...
获取单个拼音中的声母. :param pinyin: 单个拼音 :type pinyin: unicode :param strict: 是否严格遵照《汉语拼音方案》来处理声母和韵母 :return: 声母 :rtype: unicode def get_initials(pinyin, strict): """获取单个拼音中的声母. :param pinyin: 单个拼音 :type pinyin: unicode :param strict: 是否严格遵照《汉语拼音方案》来处理声母和韵母 :return: 声母 :rtype: unic...
获取单个拼音中的韵母. :param pinyin: 单个拼音 :type pinyin: unicode :param strict: 是否严格遵照《汉语拼音方案》来处理声母和韵母 :return: 韵母 :rtype: unicode def get_finals(pinyin, strict): """获取单个拼音中的韵母. :param pinyin: 单个拼音 :type pinyin: unicode :param strict: 是否严格遵照《汉语拼音方案》来处理声母和韵母 :return: 韵母 :rtype: unicod...
把声调替换为数字 def replace_symbol_to_number(pinyin): """把声调替换为数字""" def _replace(match): symbol = match.group(0) # 带声调的字符 # 返回使用数字标识声调的字符 return PHONETIC_SYMBOL_DICT[symbol] # 替换拼音中的带声调字符 return RE_PHONETIC_SYMBOL.sub(_replace, pinyin)
把带声调字符替换为没有声调的字符 def replace_symbol_to_no_symbol(pinyin): """把带声调字符替换为没有声调的字符""" def _replace(match): symbol = match.group(0) # 带声调的字符 # 去掉声调: a1 -> a return RE_NUMBER.sub(r'', PHONETIC_SYMBOL_DICT[symbol]) # 替换拼音中的带声调字符 return RE_PHONETIC_SYMBOL.sub(_replace, pinyin)
分词 :param text: 待分词的文本 :yield: 单个词语 def cut(self, text): """分词 :param text: 待分词的文本 :yield: 单个词语 """ remain = text while remain: matched = '' # 一次加一个字的匹配 for index in range(len(remain)): word = remain[:...
更新 prefix set :param word_s: 词语库列表 :type word_s: iterable :return: None def train(self, word_s): """更新 prefix set :param word_s: 词语库列表 :type word_s: iterable :return: None """ for word in word_s: # 把词语的每个前缀更新到 prefix_set 中 ...
0, 汉字 1, 英文字母 2. 数字 3. 其他 def get_char_type(ch): """ 0, 汉字 1, 英文字母 2. 数字 3. 其他 """ if re.match(en_p, ch): return 1 elif re.match("\d+", ch): return 2 elif re.match(re_han, ch): return 3 else: return 4
Translates a given pyquil Program to a TikZ picture in a Latex document. :param Program circuit: The circuit to be drawn, represented as a pyquil program. :param dict settings: An optional dictionary with settings for drawing the circuit. See `get_default_settings` in `latex_config` for more information a...
Return the body of the Latex document, including the entire circuit in TikZ format. :param Program circuit: The circuit to be drawn, represented as a pyquil program. :param dict settings: :return: Latex string to draw the entire circuit. :rtype: string def body(circuit, settings): """ Ret...
Generate the TikZ code for one line of the circuit up to a certain gate. It modifies the circuit to include only the gates which have not been drawn. It automatically switches to other lines if the gates on those lines have to be drawn earlier. :param int line: Line to generate...
Return the string representation of the gate. Tries to use gate.tex_str and, if that is not available, uses str(gate) instead. :param string gate: Gate object of which to get the name / LaTeX representation. :return: LaTeX gate name. :rtype: string def _gate_name(self, gate): ...
Return the TikZ code for a Swap-gate. :param lines: List of length 2 denoting the target qubit of the Swap gate. :type: list[int] :param ctrl_lines: List of qubit lines which act as controls. :type: list[int] def _swap_gate(self, lines, ctrl_lines): """ Return the TikZ ...
Return the TikZ code for a NOT-gate. :param lines: List of length 1 denoting the target qubit of the NOT / X gate. :type: list[int] :param ctrl_lines: List of qubit lines which act as controls. :type: list[int] def _x_gate(self, lines, ctrl_lines): """ Return the TikZ c...
Return the TikZ code for an n-controlled Z-gate. :param lines: List of all qubits involved. :type: list[int] def _cz_gate(self, lines): """ Return the TikZ code for an n-controlled Z-gate. :param lines: List of all qubits involved. :type: list[int] """ ...
Return the gate width, using the settings (if available). :param string gate: The name of the gate whose height is desired. :return: Width of the gate. :rtype: float def _gate_width(self, gate): """ Return the gate width, using the settings (if available). :param strin...
Return the offset to use before placing this gate. :param string gate: The name of the gate whose pre-offset is desired. :return: Offset to use before the gate. :rtype: float def _gate_pre_offset(self, gate): """ Return the offset to use before placing this gate. :para...
Return the height to use for this gate. :param string gate: The name of the gate whose height is desired. :return: Height of the gate. :rtype: float def _gate_height(self, gate): """ Return the height to use for this gate. :param string gate: The name of the gate whose...
Places a phase / control circle on a qubit line at a given position. :param int line: Qubit line at which to place the circle. :param float pos: Position at which to place the circle. :return: Latex string representing a control circle at the given position. :rtype: string def _phase(s...
Returns the gate name for placing a gate on a line. :param int line: Line number. :param int op: Operation number or, by default, uses the current op count. :return: Gate name. :rtype: string def _op(self, line, op=None, offset=0): """ Returns the gate name for placing ...
Connects p1 and p2, where p1 and p2 are either to qubit line indices, in which case the two most recent gates are connected, or two gate indices, in which case line denotes the line number and the two gates are connected on the given line. :param int p1: Index of the first object to con...
Draw a regular gate. :param string gate: Gate to draw. :param lines: Lines the gate acts on. :type: list[int] :param int ctrl_lines: Control lines. :param int used_lines: The lines that are actually involved in the gate. :return: LaTeX string drawing a regular gate at th...
Simulate a Quil program and return the wavefunction. .. note:: If your program contains measurements or noisy gates, this method may not do what you want. If the execution of ``quil_program`` is **non-deterministic** then the final wavefunction only represents a stochastically generated...
Calculate the expectation value of Pauli operators given a state prepared by prep_program. If ``pauli_terms`` is a ``PauliSum`` then the returned value is a single ``float``, otherwise the returned value is an array of values, one for each ``PauliTerm`` in the list. .. note:: If your p...
Run a Quil program once to determine the final wavefunction, and measure multiple times. Alternatively, consider using ``wavefunction`` and calling ``sample_bitstrings`` on the resulting object. For a large wavefunction and a low-medium number of trials, use this function. On the other...
Return an object to identify dataclass fields. default is the default value of the field. default_factory is a 0-argument function called to initialize a field's value. If init is True, the field will be a parameter to the class's __init__() function. If repr is True, the field will be included in t...
Returns the same class as was passed in, with dunder methods added based on the fields defined in the class. Examines PEP 526 __annotations__ to determine fields. If init is true, an __init__() method is added to the class. If repr is true, a __repr__() method is added. If order is true, rich comp...
Return a tuple describing the fields of this dataclass. Accepts a dataclass or an instance of one. Tuple elements are of type Field. def fields(class_or_instance): """Return a tuple describing the fields of this dataclass. Accepts a dataclass or an instance of one. Tuple elements are of type Fiel...
Return the fields of a dataclass instance as a new dictionary mapping field names to field values. Example usage: @dataclass class C: x: int y: int c = C(1, 2) assert asdict(c) == {'x': 1, 'y': 2} If given, 'dict_factory' will be used instead of built-in dict....
Return the fields of a dataclass instance as a new tuple of field values. Example usage:: @dataclass class C: x: int y: int c = C(1, 2) assert astuple(c) == (1, 2) If given, 'tuple_factory' will be used instead of built-in tuple. The function applies recursively t...
Return a new dynamically created dataclass. The dataclass name will be 'cls_name'. 'fields' is an iterable of either (name), (name, type) or (name, type, Field) objects. If type is omitted, use the string 'typing.Any'. Field objects are created by the equivalent of calling 'field(name, type [, Field-...
Return a new object replacing specified fields with new values. This is especially useful for frozen classes. Example usage: @dataclass(frozen=True) class C: x: int y: int c = C(1, 2) c1 = replace(c, x=3) assert c1.x == 3 and c1.y == 2 def replace(obj, **change...
Construct a randomized benchmarking experiment on the given qubits, decomposing into gateset. If interleaver is not provided, the returned sequence will have the form C_1 C_2 ... C_(depth-1) C_inv , where each C is a Clifford element drawn from gateset, C_{< depth} are randomly selected, ...
Function that returns a QAOA ansatz program for a list of angles betas and gammas. len(betas) == len(gammas) == P for a QAOA program of order P. :param list(float) gammas: Angles over which to parameterize the cost Hamiltonian. :param list(float) betas: Angles over which to parameterize the driver Hamilton...
Query the Forest 2.0 server for a list of underlying QPU devices. NOTE: These can't directly be used to manufacture pyQuil Device objects, but this gives a list of legal values that can be supplied to list_lattices to filter its (potentially very noisy) output. :return: A list of device na...
Query the Forest 2.0 server for its knowledge of lattices. Optionally filters by underlying device name and lattice qubit count. :return: A dictionary keyed on lattice names and valued in dictionaries of the form { "device_name": device_name, "qubits": num_qubits ...
Produces a dictionary of raw data for a lattice as queried from the Forest 2.0 server. Returns a dictionary of the form { "name": the name of the lattice as a string, "device_name": the name of the device, given as a string, that the lattice lies on, "specs": a Specs object...
Returns the bitstring in lexical order that corresponds to the given index in 0 to 2^(qubit_num) :param int index: :param int qubit_num: :return: the bitstring :rtype: str def get_bitstring_from_index(index, qubit_num): """ Returns the bitstring in lexical order that corresponds to the given in...
Round up the the next multiple. :param n: The number to round up. :param m: The multiple. :return: The rounded number def _round_to_next_multiple(n, m): """ Round up the the next multiple. :param n: The number to round up. :param m: The multiple. :return: The rounded number """ ...
Get the bits of an octet. :param o: The octets. :return: The bits as a list in LSB-to-MSB order. :rtype: list def _octet_bits(o): """ Get the bits of an octet. :param o: The octets. :return: The bits as a list in LSB-to-MSB order. :rtype: list """ if not isinstance(o, integer_...
From a bit packed string, unpacks to get the wavefunction :param bytes coef_string: :return: def from_bit_packed_string(coef_string): """ From a bit packed string, unpacks to get the wavefunction :param bytes coef_string: :return: """ num_octets = len(coe...
Parses a wavefunction (array of complex amplitudes) and returns a dictionary of outcomes and associated probabilities. :return: A dict with outcomes as keys and probabilities as values. :rtype: dict def get_outcome_probs(self): """ Parses a wavefunction (array of complex amplit...
Prints outcome probabilities, ignoring all outcomes with approximately zero probabilities (up to a certain number of decimal digits) and rounding the probabilities to decimal_digits. :param int decimal_digits: The number of digits to truncate to. :return: A dict with outcomes as keys and probab...
Returns a string repr of the wavefunction, ignoring all outcomes with approximately zero amplitude (up to a certain number of decimal digits) and rounding the amplitudes to decimal_digits. :param int decimal_digits: The number of digits to truncate to. :return: A dict with outcomes as k...
Plots a bar chart with bitstring on the x axis and probability on the y axis. :param list qubit_subset: Optional parameter used for plotting a subset of the Hilbert space. def plot(self, qubit_subset=None): """ Plots a bar chart with bitstring on the x axis and probability on the y axis. ...
Sample bitstrings from the distribution defined by the wavefunction. :param n_samples: The number of bitstrings to sample :return: An array of shape (n_samples, n_qubits) def sample_bitstrings(self, n_samples): """ Sample bitstrings from the distribution defined by the wavefunction. ...
Return the default settings for generating LaTeX circuits. settings is a dictionary with the following keys: gate_shadow: Whether or not to apply shadowing to the gates. lines: Settings for the lines. gates: Settings for the gates. control: Settings for the control symbols. :return: De...
Writes the Latex header using the settings file. The header includes all packages and defines all tikz styles. :param dictionary settings: LaTeX settings for document. :return: Header of the LaTeX document. :rtype: string def header(settings): """ Writes the Latex header using the settings fi...
Verify that the Kraus operators are of the correct shape and satisfy the correct normalization. :param int n: Number of qubits :param list|tuple kraus_ops: The Kraus operators as numpy.ndarrays. def _check_kraus_ops(n, kraus_ops): """ Verify that the Kraus operators are of the correct shape and satisf...
Generate the pragmas to define a Kraus map for a specific gate on some qubits. :param str name: The name of the gate. :param list|tuple qubit_indices: The qubits :param list|tuple kraus_ops: The Kraus operators as matrices. :return: A QUIL string with PRAGMA ADD-KRAUS ... statements. :rtype: str d...
r""" Generate the Kraus operators corresponding to a pauli channel. :params list|floats probabilities: The 4^num_qubits list of probabilities specifying the desired pauli channel. There should be either 4 or 16 probabilities specified in the order I, X, Y, Z for 1 qubit or II, IX, IY, IZ, XI, XX, XY, e...
Generate the Kraus operators corresponding to an amplitude damping noise channel. :param float p: The one-step damping probability. :return: A list [k1, k2] of the Kraus operators that parametrize the map. :rtype: list def damping_kraus_map(p=0.10): """ Generate the Kraus operators correspondi...
Generate the Kraus operators corresponding to a dephasing channel. :params float p: The one-step dephasing probability. :return: A list [k1, k2] of the Kraus operators that parametrize the map. :rtype: list def dephasing_kraus_map(p=0.10): """ Generate the Kraus operators corresponding to a dephas...
Generate the Kraus map corresponding to the composition of two maps on different qubits. :param list k1: The Kraus operators for the first qubit. :param list k2: The Kraus operators for the second qubit. :return: A list of tensored Kraus operators. def tensor_kraus_maps(k1, k2): """ Generate t...
Generate the Kraus map corresponding to the composition of two maps on the same qubits with k1 being applied to the state after k2. :param list k1: The list of Kraus operators that are applied second. :param list k2: The list of Kraus operators that are applied first. :return: A combinatorially gen...
Generate the Kraus map corresponding to the composition of a dephasing channel followed by an amplitude damping channel. :param float T1: The amplitude damping time :param float T2: The dephasing time :param float gate_time: The gate duration. :return: A list of Kraus operators. def damping_after_...
Look up the numerical gate representation and a proposed 'noisy' name. :param str gate_name: The Quil gate name :param Tuple[float] params: The gate parameters. :return: A tuple (matrix, noisy_name) with the representation of the ideal gate matrix and a proposed name for the noisy version. :rty...
Get all gate applications appearing in prog. :param Program prog: The program :return: A list of all Gates in prog (without duplicates). :rtype: List[Gate] def _get_program_gates(prog): """ Get all gate applications appearing in prog. :param Program prog: The program :return: A list of al...
The default noise parameters - T1 = 30 us - T2 = 30 us - 1q gate time = 50 ns - 2q gate time = 150 ns are currently typical for near-term devices. This function will define new gates and add Kraus noise to these gates. It will translate the input program to use the noisy version of the ga...
Similar to :py:func:`_decoherence_noise_model`, but with asymmetric readout. For simplicity, we use the default values for T1, T2, gate times, et al. and only allow the specification of readout fidelities. def decoherence_noise_with_asymmetric_ro(gates: Sequence[Gate], p00=0.975, p11=0.911): """Similar to...
Generate the header for a pyquil Program that uses ``noise_model`` to overload noisy gates. The program header consists of 3 sections: - The ``DEFGATE`` statements that define the meaning of the newly introduced "noisy" gate names. - The ``PRAGMA ADD-KRAUS`` statements to overload these n...
Apply a noise model to a program and generated a 'noisy-fied' version of the program. :param Program prog: A Quil Program object. :param NoiseModel noise_model: A NoiseModel, either generated from an ISA or from a simple decoherence model. :return: A new program translated to a noisy gateset and wi...
Add generic damping and dephasing noise to a program. This high-level function is provided as a convenience to investigate the effects of a generic noise model on a program. For more fine-grained control, please investigate the other methods available in the ``pyquil.noise`` module. In an attempt to c...
Ensure that an array ``p`` with bitstring probabilities has a separate axis for each qubit such that ``p[i,j,...,k]`` gives the estimated probability of bitstring ``ij...k``. This should not allocate much memory if ``p`` is already in ``C``-contiguous order (row-major). :param np.array p: An array that en...
Given an array of single shot results estimate the probability distribution over all bitstrings. :param np.array results: A 2d array where the outer axis iterates over shots and the inner axis over bits. :return: An array with as many axes as there are qubit and normalized such that it sums to one. ...
Given a 2d array of single shot results (outer axis iterates over shots, inner axis over bits) and a list of assignment probability matrices (one for each bit in the readout, ordered like the inner axis of results) apply local 2x2 matrices to each bit index. :param np.array p: An array that enumerates a fu...
Given a 2d array of corrupted bitstring probabilities (outer axis iterates over shots, inner axis over bits) and a list of assignment probability matrices (one for each bit in the readout) compute the corrected probabilities. :param np.array p: An array that enumerates bitstring probabilities. When ...
Convert between bitstring probabilities and joint Z moment expectations. :param np.array p: An array that enumerates bitstring probabilities. When flattened out ``p = [p_00...0, p_00...1, ...,p_11...1]``. The total number of elements must therefore be a power of 2. The canonical shape has a separat...
Estimate the readout assignment probabilities for a given qubit ``q``. The returned matrix is of the form:: [[p00 p01] [p10 p11]] :param int q: The index of the qubit. :param int trials: The number of samples for each state preparation. :param Union[QVMConnection,QPUConnection...
Helper to optionally unpack a JSON compatible representation of a complex Kraus matrix. :param Union[list,np.array] m: The representation of a Kraus operator. Either a complex square matrix (as numpy array or nested lists) or a JSON-able pair of real matrices (as nested lists) represent...
Create a dictionary representation of a KrausModel. For example:: { "gate": "RX", "params": np.pi, "targets": [0], "kraus_ops": [ # In this example single Kraus op = ideal RX(pi) gate [[[0, 0], ...
Recreate a KrausModel from the dictionary representation. :param dict d: The dictionary representing the KrausModel. See `to_dict` for an example. :return: The deserialized KrausModel. :rtype: KrausModel def from_dict(d): """ Recreate a KrausModel from the dictionar...
Create a JSON serializable representation of the noise model. For example:: { "gates": [ # list of embedded dictionary representations of KrausModels here [...] ] "assignment_probs": { "0": [[.8, .1], ...
Re-create the noise model from a dictionary representation. :param Dict[str,Any] d: The dictionary representation. :return: The restored noise model. :rtype: NoiseModel def from_dict(d): """ Re-create the noise model from a dictionary representation. :param Dict[str,An...
Return all defined noisy gates of a particular gate name. :param str name: The gate name. :return: A list of noise models representing that gate. :rtype: Sequence[KrausModel] def gates_by_name(self, name): """ Return all defined noisy gates of a particular gate name. :...
Collects the attributes from PYQUIL_PROGRAM_PROPERTIES on the Program object program into a dictionary. :param program: Program to collect attributes from. :return: Dictionary of attributes, keyed on the string attribute name. def _extract_attribute_dictionary_from_program(program: Program) -> Dict[str, A...
Unpacks a rpcq PyQuilExecutableResponse object into a pyQuil Program object. :param response: PyQuilExecutableResponse object to be unpacked. :return: Resulting pyQuil Program object. def _extract_program_from_pyquil_executable_response(response: PyQuilExecutableResponse) -> Program: """ Unpacks a rpc...
Collect classical memory locations that are the destination of MEASURE instructions These locations are important for munging output buffers returned from the QPU server to the shape expected by the user. This is secretly stored on BinaryExecutableResponse. We're careful to make sure these objects are...
Collect Declare instructions that are important for building the patch table. This is secretly stored on BinaryExecutableResponse. We're careful to make sure these objects are json serializable. :return: A dictionary of variable names to specs about the declared region. def _collect_memory_descriptors(pr...
Teleport a qubit from start to end using an ancilla qubit def teleport(start_index, end_index, ancilla_index): """Teleport a qubit from start to end using an ancilla qubit """ program = make_bell_pair(end_index, ancilla_index) ro = program.declare('ro', memory_size=3) # do the teleportation p...
Generate a quantum program to roll a die of n faces. def die_program(number_of_sides): """ Generate a quantum program to roll a die of n faces. """ prog = Program() n_qubits = qubits_needed(number_of_sides) ro = prog.declare('ro', 'BIT', n_qubits) # Hadamard initialize. for q in range(n...
Convert n digit binary result from the QVM to a value on a die. def process_results(results): """ Convert n digit binary result from the QVM to a value on a die. """ raw_results = results[0] processing_result = 0 for each_qubit_measurement in raw_results: processing_result = 2*processin...
Roll an n-sided quantum die. def roll_die(qvm, number_of_sides): """ Roll an n-sided quantum die. """ die_compiled = qvm.compile(die_program(number_of_sides)) return process_results(qvm.run(die_compiled))
Add the CONTROLLED modifier to the gate with the given control qubit. def controlled(self, control_qubit): """ Add the CONTROLLED modifier to the gate with the given control qubit. """ control_qubit = unpack_qubit(control_qubit) self.modifiers.insert(0, "CONTROLLED") se...
Prints a readable Quil string representation of this gate. :returns: String representation of a gate :rtype: string def out(self): """ Prints a readable Quil string representation of this gate. :returns: String representation of a gate :rtype: string """ ...
:returns: A function that constructs this gate on variable qubit indices. E.g. `mygate.get_constructor()(1) applies the gate to qubit 1.` def get_constructor(self): """ :returns: A function that constructs this gate on variable qubit indices. E.g. `mygate.get_constru...
:return: The number of qubit arguments the gate takes. :rtype: int def num_args(self): """ :return: The number of qubit arguments the gate takes. :rtype: int """ rows = len(self.matrix) return int(np.log2(rows))
Generate the full gateset associated with an ISA. :param ISA isa: The instruction set architecture for a QPU. :return: A sequence of Gate objects encapsulating all gates compatible with the ISA. :rtype: Sequence[Gate] def gates_in_isa(isa): """ Generate the full gateset associated with an ISA. ...
Generate an ISA object from a NetworkX graph. :param graph: The graph :param oneq_type: The type of 1-qubit gate. Currently 'Xhalves' :param twoq_type: The type of 2-qubit gate. One of 'CZ' or 'CPHASE'. def isa_from_graph(graph: nx.Graph, oneq_type='Xhalves', twoq_type='CZ') -> ISA: """ Generate a...