text
stringlengths
81
112k
Gates implementing the secret function f(x). def make_oracle(q0, q1, secret_function): """ Gates implementing the secret function f(x).""" # coverage: ignore if secret_function[0]: yield [CNOT(q0, q1), X(q1)] if secret_function[1]: yield CNOT(q0, q1)
Gives adjacency list representation of a chip. The adjacency list is constructed in order of above, left_of, below and right_of consecutively. Args: device: Chip to be converted. Returns: Map from nodes to list of qubits which represent all the neighbours of given qubit. def ...
Constructs the HHL circuit. A is the input Hermitian matrix. C and t are tunable parameters for the algorithm. register_size is the size of the eigenvalue register. input_prep_gates is a list of gates to be applied to |0> to generate the desired input state |b>. def hhl_circuit(A, C, t, register...
Simulates HHL with matrix input, and outputs Pauli observables of the resulting qubit state |x>. Expected observables are calculated from the expected solution |x>. def main(): """ Simulates HHL with matrix input, and outputs Pauli observables of the resulting qubit state |x>. Expected observab...
See definition in `cirq.SimulatesSamples`. def _run( self, circuit: circuits.Circuit, param_resolver: study.ParamResolver, repetitions: int, ) -> Dict[str, List[np.ndarray]]: """See definition in `cirq.SimulatesSamples`.""" circuit = protocols.resolve_parameters(cir...
See definition in `cirq.SimulatesIntermediateState`. If the initial state is an int, the state is set to the computational basis state corresponding to this state. Otherwise if the initial state is a np.ndarray it is the full initial state. In this case it must be the correct size, be ...
Updates the state of the simulator to the given new state. Args: state: If this is an int, then this is the state to reset the stepper to, expressed as an integer of the computational basis. Integer to bitwise indices is little endian. Otherwise if this is a np.n...
Samples from the wave function at this point in the computation. Note that this does not collapse the wave function. Returns: Measurement results with True corresponding to the `|1>` state. The outer list is for repetitions, and the inner corresponds to measurements...
Adds possibly stateful noise to a series of moments. Args: moments: The moments to add noise to. system_qubits: A list of all qubits in the system. Returns: A sequence of OP_TREEs, with the k'th tree corresponding to the noisy operations for the k'th mom...
Adds noise to the operations from a moment. Args: moment: The moment to add noise to. system_qubits: A list of all qubits in the system. Returns: An OP_TREE corresponding to the noisy operations for the moment. def noisy_moment(self, moment: 'cirq.Moment', ...
Adds noise to an individual operation. Args: operation: The operation to make noisy. Returns: An OP_TREE corresponding to the noisy operations implementing the noisy version of the given operation. def noisy_operation(self, operation: 'cirq.Operation') -> 'cirq.OP_...
Get the measurement key for the given value. Args: val: The value which has the measurement key.. default: Determines the fallback behavior when `val` doesn't have a measurement key. If `default` is not set, a TypeError is raised. If default is set to a value, that value is ...
Generates Google Random Circuits v2 as in github.com/sboixo/GRCS cz_v2. See also https://arxiv.org/abs/1807.10749 Args: qubits: qubit grid in which to generate the circuit. cz_depth: number of layers with CZ gates. seed: seed for the random instance. Returns: A circuit corr...
Generates Google Random Circuits v2 as in github.com/sboixo/GRCS cz_v2. See also https://arxiv.org/abs/1807.10749 Args: n_rows: number of rows of a 2D lattice. n_cols: number of columns. cz_depth: number of layers with CZ gates. seed: seed for the random instance. Returns: ...
Generates Google Random Circuits v2 in Bristlecone. See also https://arxiv.org/abs/1807.10749 Args: n_rows: number of rows in a Bristlecone lattice. Note that we do not include single qubit corners. cz_depth: number of layers with CZ gates. seed: seed for the random instance. ...
Choose a random element from a non-empty sequence. Use this instead of random.choice, with random.random(), for reproducibility def _choice(rand_gen: Callable[[], float], sequence: Sequence[T]) -> T: """Choose a random element from a non-empty sequence. Use this instead of random.choice, with random.rand...
Each layer index corresponds to a shift/transpose of this CZ pattern: ●───● ● ● ●───● ● ● . . . ● ● ●───● ● ● ●───● . . . ●───● ● ● ●───● ● ● . . . ● ● ●───● ● ● ●───● . . . ●───● ● ● ●───● ● ● . . . ● ● ●───● ...
Determines the effect of an operation on the given qubits. If the operation is a 1-qubit operation on one of the given qubits, or a 2-qubit operation on both of the given qubits, and also the operation has a known matrix, then a matrix is returned. Otherwise None is returned. A...
Accumulates operations affecting the given pair of qubits. The scan terminates when it hits the end of the circuit, finds an operation without a known matrix, or finds an operation that interacts the given qubits with other qubits. Args: circuit: The circuit to scan for ope...
Given M = sum(kron(a_i, b_i)), returns M' = sum(kron(b_i, a_i)). def _flip_kron_order(mat4x4: np.ndarray) -> np.ndarray: """Given M = sum(kron(a_i, b_i)), returns M' = sum(kron(b_i, a_i)).""" result = np.array([[0] * 4] * 4, dtype=np.complex128) order = [0, 2, 1, 3] for i in range(4): ...
Returns a Controlled version of the given value, if defined. Controllees define how to be controlled by defining a method controlled_by(self, control_qubits). Note that the method may return NotImplemented to indicate a particular controlling can't be done. Args: controllee: The gate, operatio...
Returns the inverse `val**-1` of the given value, if defined. An object can define an inverse by defining a __pow__(self, exponent) method that returns something besides NotImplemented when given the exponent -1. The inverse of iterables is by default defined to be the iterable's items, each inverted, ...
Decomposes a two-qubit operation into MS/single-qubit rotation gates. Args: q0: The first qubit being operated on. q1: The other qubit being operated on. mat: Defines the operation to apply to the pair of qubits. tolerance: A limit on the amount of error introduced by the ...
Yields an XX interaction framed by the given operation. def _parity_interaction(q0: ops.Qid, q1: ops.Qid, rads: float, atol: float, gate: Optional[ops.Gate] = None): """Yields an XX interaction framed by the given opera...
Yields non-local operation of KAK decomposition. def _non_local_part(q0: ops.Qid, q1: ops.Qid, interaction_coefficients: Tuple[float, float, float], atol: float = 1e-8): """Yields non-local operation of KAK decomposition.""" x, y, z = interaction_coe...
Attempt to resolve a Symbol or name or float to its assigned value. If unable to resolve a sympy.Symbol, returns it unchanged. If unable to resolve a name, returns a sympy.Symbol with that name. Args: value: The sympy.Symbol or name or float to try to resolve into just ...
Implements __eq__/__ne__/__hash__ via a _value_equality_values_ method. _value_equality_values_ is a method that the decorated class must implement. _value_equality_approximate_values_ is a method that the decorated class might implement if special support for approximate equality is required. This is...
Extracts a set of 'interesting' lines out of a GNU unified diff format. Format: gnu.org/software/diffutils/manual/html_node/Detailed-Unified.html @@ from-line-numbers to-line-numbers @@ line-from-either-file ... @@ start,count start,count @@ line-from-either-file ...
Uses git diff and the annotation files created by `pytest --cov-report annotate` to find touched but uncovered lines in the given file. Args: abs_path: The path of a file to look for uncovered lines in. base_commit: Old state to diff against. actual_commit: Current state. Use None t...
Args: content: A line with indentation and tail comments/space removed. Returns: Whether the line could be included in the coverage report. def line_content_counts_as_uncovered_manual(content: str) -> bool: """ Args: content: A line with indentation and tail comments/space removed....
Args: line: The line of code (including coverage annotation). is_from_cover_annotation_file: Whether this line has been annotated. Returns: Does the line count as uncovered? def line_counts_as_uncovered(line: str, is_from_cover_annotation_file: bool) -> bool: ...
Determines if a file should be included in incremental coverage analysis. Args: rel_path: The repo-relative file path being considered. Returns: Whether to include the file. def is_applicable_python_file(rel_path: str) -> bool: """ Determines if a file should be included in incremental...
Finds a value that is nearly an integer multiple of multiple periods. The returned value should be the smallest non-negative number with this property. If `approx_denom` is too small the computation can fail to satisfy the `reject_atol` criteria and return `None`. This is actually desirable behavior, s...
Finds the least common integer multiple of some fractions. The solution is the smallest positive integer c such that there exists integers n_k satisfying p_k * n_k = c for all k. def _common_rational_period(rational_periods: List[fractions.Fraction] ) -> fractions.Fraction: """...
Fit label encoder Parameters ---------- y : array-like of shape (n_samples,) Target values. Returns ------- self : returns an instance of self. def fit(self, X): """Fit label encoder Parameters ---------- y : array-like of s...
Fit label encoder and return encoded labels Parameters ---------- y : array-like of shape [n_samples] Target values. Returns ------- y : array-like of shape [n_samples] def fit_transform(self, X, y=None, **fit_params): """Fit label encoder and retur...
Transform labels to normalized encoding. Parameters ---------- y : array-like of shape [n_samples] Target values. Returns ------- y : array-like of shape [n_samples] def transform(self, y): """Transform labels to normalized encoding. Parame...
Transform labels back to original encoding. Parameters ---------- y : numpy array of shape [n_samples] Target values. Returns ------- y : numpy array of shape [n_samples] def inverse_transform(self, y): """Transform labels back to original encoding....
Transform features per specified math function. :param y: :return: def transform(self, y): """ Transform features per specified math function. :param y: :return: """ if self.transform_type == 'log': return np.log(y) elif self.transform...
Fit Unary Math Operator :param y: :return: def fit(self, X, y=None, **fit_params): """ Fit Unary Math Operator :param y: :return: """ if self.transform_type not in self.valid_transforms: warnings.warn("Invalid transform type.", stacklevel=...
Transform features per specified math function. :param y: :return: def transform(self, y): """ Transform features per specified math function. :param y: :return: """ if isinstance(y, pd.DataFrame): x = y.ix[:,0] y = y.ix[:,1] ...
:type feature_names: list :type tree: sklearn.tree.tree.BaseDecisionTree :param tree: sklearn.tree.tree :param feature_names: :return: def serialize_tree(tree, feature_names, outfile): """ :type feature_names: list :type tree: sklearn.tree.tree.BaseDecisionTree ...
:type transformer: sklearn.tree.tree.BaseDecisionTree :type path: str :type model_name: str :type serialize_node: bool :param transformer: :param path: :param model_name: :return: def serialize_to_bundle(self, transformer, path, model_name, serialize_node=True): ...
Used with sqrt kernel :param words: :param transformer: :return: def sent2vec(self, words, transformer): """ Used with sqrt kernel :param words: :param transformer: :return: """ sent_vec = np.zeros(transformer.vector_size) numw = 0...
:param transformer: Random Forest Regressor or Classifier :param path: Root path where to serialize the model :param model: Name of the model to be serialized :type transformer: sklearn.ensemble.forest.BaseForest :type path: str :type model: str :return: None def seriali...
Generates the model.json given a list of attributes, which are a tuple comprised of: - name - value Type is figured out automatically, but we should consider specifying it explicitly. Note: this only supports doubles and tensors that are vectors/lists of doubles. :param t...
:attributes_map: Map of attributes names. For example StandardScaler has `mean_` but is serialized as `mean` :param transformer: Scikit or Pandas transformer :param node: bundle.ml node json file :param model: bundle.ml model json file :return: Transformer def deserialize_single_input_o...
Wait until `what` return True Args: what (Callable[bool]): Call `wait()` again and again until it returns True times (int): Maximum times of trials before giving up Returns: True if success, False if times threshold reached def wait_until(what, times=-1): """Wait until `what` retu...
Reboot all usb devices. Note: If PDU_CONTROLLER_TYPE is not valid, usb devices is not rebooted. def _init_devices(self): """Reboot all usb devices. Note: If PDU_CONTROLLER_TYPE is not valid, usb devices is not rebooted. """ if not settings.PDU_CONTROLLE...
Restart harness backend service. Please start the harness controller before running the cases, otherwise, nothing happens def _init_harness(self): """Restart harness backend service. Please start the harness controller before running the cases, otherwise, nothing happens """ s...
Initialize the DUT. DUT will be restarted. and openthread will started. def _init_dut(self): """Initialize the DUT. DUT will be restarted. and openthread will started. """ if self.auto_dut: self.dut = None return dut_port = settings.DUT_DEVICE[...
Open harness web page. Open a quiet chrome which: 1. disables extensions, 2. ignore certificate errors and 3. always allow notifications. def _init_browser(self): """Open harness web page. Open a quiet chrome which: 1. disables extensions, 2. ignore cer...
Prepare to run test case. Start harness service, init golden devices, reset DUT and open browser. def setUp(self): """Prepare to run test case. Start harness service, init golden devices, reset DUT and open browser. """ if self.__class__ is HarnessCase: return ...
Clean up after each case. Stop harness service, close browser and close DUT. def tearDown(self): """Clean up after each case. Stop harness service, close browser and close DUT. """ if self.__class__ is HarnessCase: return logger.info('Tearing down') ...
Do sniffer settings and general settings def _setup_page(self): """Do sniffer settings and general settings """ if not self.started: self.started = time.time() if time.time() - self.started > 5*len(settings.GOLDEN_DEVICES): self._browser.refresh() re...
Select the test case. def _select_case(self, role, case): """Select the test case. """ # select the case elem = Select(self._browser.find_element_by_id('select-dut')) elem.select_by_value(str(role)) time.sleep(1) checkbox = None wait_until(lambda: self._...
Collect test result. Generate PDF, excel and pcap file def _collect_result(self): """Collect test result. Generate PDF, excel and pcap file """ # generate pdf self._browser.find_element_by_class_name('save-pdf').click() time.sleep(1) try: di...
Wait for dialogs and handle them until done. def _wait_dialog(self): """Wait for dialogs and handle them until done. """ logger.debug('waiting for dialog') done = False error = False logger.info("self timeout %d",self.timeout) while not done and self.timeout: ...
Handle a dialog. Returns: bool True if no more dialogs expected, False if more dialogs needed, and None if not handled def _handle_dialog(self, dialog, title): """Handle a dialog. Returns: bool True if no more dialogs expected, ...
List devices in settings file and print versions def list_devices(names=None, continue_from=None, **kwargs): """List devices in settings file and print versions""" if not names: names = [device for device, _type in settings.GOLDEN_DEVICES if _type == 'OpenThread'] if continue_from: contin...
Discover all test cases and skip those passed Args: pattern (str): Pattern to match case modules, refer python's unittest documentation for more details skip (str): types cases to skip def discover(names=None, pattern=['*.py'], skip='efp', dry_run=False, blacklist=None, name...
Find the `expected` line within `times` trials. Args: expected str: the expected string times int: number of trials def _expect(self, expected, times=50): """Find the `expected` line within `times` trials. Args: expected str: the expected string...
Read exactly one line from the device Returns: None on no data def _readline(self): """Read exactly one line from the device Returns: None on no data """ logging.info('%s: reading line', self.port) if len(self._lines) > 1: return sel...
Send exactly one line to the device Args: line str: data send to device def _sendline(self, line): """Send exactly one line to the device Args: line str: data send to device """ logging.info('%s: sending line', self.port) # clear buffer ...
send specific command to reference unit over serial port Args: cmd: OpenThread CLI string Returns: Done: successfully send the command to reference unit and parse it Value: successfully retrieve the desired value from reference unit Error: some errors oc...
get specific type of IPv6 address configured on thread device Args: addressType: the specific type of IPv6 address link local: link local unicast IPv6 address that's within one-hop scope global: global unicast IPv6 address rloc: mesh local unicast IPv6 address f...
set router upgrade threshold Args: iThreshold: the number of active routers on the Thread network partition below which a REED may decide to become a Router. Returns: True: successful to set the ROUTER_UPGRADE_THRESHOLD False: fail to set ROU...
set ROUTER_SELECTION_JITTER parameter for REED to upgrade to Router Args: iRouterJitter: a random period prior to request Router ID for REED Returns: True: successful to set the ROUTER_SELECTION_JITTER False: fail to set ROUTER_SELECTION_JITTER def __setRouterSelec...
set address filter mode Returns: True: successful to set address filter mode. False: fail to set address filter mode. def __setAddressfilterMode(self, mode): """set address filter mode Returns: True: successful to set address filter mode. False:...
start OpenThread stack Returns: True: successful to start OpenThread stack and thread interface up False: fail to start OpenThread stack def __startOpenThread(self): """start OpenThread stack Returns: True: successful to start OpenThread stack and thread in...
stop OpenThread stack Returns: True: successful to stop OpenThread stack and thread interface down False: fail to stop OpenThread stack def __stopOpenThread(self): """stop OpenThread stack Returns: True: successful to stop OpenThread stack and thread interf...
mapping Rloc16 to router id Args: xRloc16: hex rloc16 short address Returns: actual router id allocated by leader def __convertRlocToRouterId(self, xRloc16): """mapping Rloc16 to router id Args: xRloc16: hex rloc16 short address Returns: ...
convert IPv6 prefix string to IPv6 dotted-quad format for example: 2001000000000000 -> 2001:: Args: strIp6Prefix: IPv6 address string Returns: IPv6 address dotted-quad format def __convertIp6PrefixStringToIp6Address(self, strIp6Prefix): """convert...
convert a long hex integer to string remove '0x' and 'L' return string Args: iValue: long integer in hex format Returns: string of this long integer without "0x" and "L" def __convertLongToString(self, iValue): """convert a long hex integer to string ...
read logs during the commissioning process Args: durationInSeconds: time duration for reading commissioning logs Returns: Commissioning logs def __readCommissioningLogs(self, durationInSeconds): """read logs during the commissioning process Args: d...
convert channelsArray to bitmask format Args: channelsArray: channel array (i.e. [21, 22]) Returns: bitmask format corresponding to a given channel array def __convertChannelMask(self, channelsArray): """convert channelsArray to bitmask format Args: ...
set the Key switch guard time Args: iKeySwitchGuardTime: key switch guard time Returns: True: successful to set key switch guard time False: fail to set key switch guard time def __setKeySwitchGuardTime(self, iKeySwitchGuardTime): """ set the Key switch gua...
close current serial port connection def closeConnection(self): """close current serial port connection""" print '%s call closeConnection' % self.port try: if self.handle: self.handle.close() self.handle = None except Exception, e: ...
initialize the serial port with baudrate, timeout parameters def intialize(self): """initialize the serial port with baudrate, timeout parameters""" print '%s call intialize' % self.port try: self.deviceConnected = False # init serial port self._connect() ...
set Thread Network name Args: networkName: the networkname string to be set Returns: True: successful to set the Thread Networkname False: fail to set the Thread Networkname def setNetworkName(self, networkName='GRL'): """set Thread Network name Ar...
set channel of Thread device operates on. Args: channel: (0 - 10: Reserved) (11 - 26: 2.4GHz channels) (27 - 65535: Reserved) Returns: True: successful to set the channel False: fail to set the channel de...
get one specific type of MAC address currently OpenThread only supports Random MAC address Args: bType: indicate which kind of MAC address is required Returns: specific type of MAC address def getMAC(self, bType=MacType.RandomMac): """get one specific type o...
get rloc16 short address def getRloc16(self): """get rloc16 short address""" print '%s call getRloc16' % self.port rloc16 = self.__sendCommand('rloc16')[0] return int(rloc16, 16)
get current partition id of Thread Network Partition from LeaderData Returns: The Thread network Partition Id def getNetworkFragmentID(self): """get current partition id of Thread Network Partition from LeaderData Returns: The Thread network Partition Id """ ...
get Thread device's parent extended address and rloc16 short address Returns: The extended address of parent in hex format def getParentAddress(self): """get Thread device's parent extended address and rloc16 short address Returns: The extended address of parent in hex...
power down the Thread device def powerDown(self): """power down the Thread device""" print '%s call powerDown' % self.port self._sendline('reset') self.isPowerDown = True
power up the Thread device def powerUp(self): """power up the Thread device""" print '%s call powerUp' % self.port if not self.handle: self._connect() self.isPowerDown = False if not self.__isOpenThreadRunning(): self.__startOpenThread()
reset and rejoin to Thread Network without any timeout Returns: True: successful to reset and rejoin the Thread Network False: fail to reset and rejoin the Thread Network def reboot(self): """reset and rejoin to Thread Network without any timeout Returns: T...
send ICMPv6 echo request with a given length to a unicast destination address Args: destination: the unicast destination address of ICMPv6 echo request length: the size of ICMPv6 echo request payload def ping(self, destination, length=20): """ send ICMPv6 echo reque...
factory reset def reset(self): """factory reset""" print '%s call reset' % self.port try: self._sendline('factoryreset') self._read() except Exception, e: ModuleHelper.WriteIntoDebugLogger("reset() Error: " + str(e))
get data polling rate for sleepy end device def getPollingRate(self): """get data polling rate for sleepy end device""" print '%s call getPollingRate' % self.port sPollingRate = self.__sendCommand('pollperiod')[0] try: iPollingRate = int(sPollingRate)/1000 fPolli...
set custom LinkQualityIn for all receiving messages from the specified EUIadr Args: EUIadr: a given extended address LinkQuality: a given custom link quality link quality/link margin mapping table 3: 21 - 255 (dB) ...
set custom LinkQualityIn for all receiving messages from the any address Args: LinkQuality: a given custom link quality link quality/link margin mapping table 3: 21 - 255 (dB) 2: 11 - 20 (dB) 1: 3 - ...
remove the configured prefix on a border router Args: prefixEntry: a on-mesh prefix entry Returns: True: successful to remove the prefix entry from border router False: fail to remove the prefix entry from border router def removeRouterPrefix(self, prefixEntry): ...
reset and join back Thread Network with a given timeout delay Args: timeout: a timeout interval before rejoin Thread Network Returns: True: successful to reset and rejoin Thread Network False: fail to reset and rejoin the Thread Network def resetAndRejoin(self, tim...
set networkid timeout for Thread device Args: iNwkIDTimeOut: a given NETWORK_ID_TIMEOUT Returns: True: successful to set NETWORK_ID_TIMEOUT False: fail to set NETWORK_ID_TIMEOUT def setNetworkIDTimeout(self, iNwkIDTimeOut): """set networkid timeout for Thre...
set whether the Thread device requires the full network data or only requires the stable network data Args: eDataRequirement: is true if requiring the full network data Returns: True: successful to set the network requirement def setNetworkDataRequirement(self, eDat...
configure border router with a given external route prefix entry Args: P_Prefix: IPv6 prefix for the route P_Stable: is true if the external route prefix is stable network data R_Preference: a two-bit signed integer indicating Router preference 1: h...
get neighboring routers information Returns: neighboring routers' extended address def getNeighbouringRouters(self): """get neighboring routers information Returns: neighboring routers' extended address """ print '%s call getNeighbouringRouters' % self....
get all children information Returns: children's extended address def getChildrenInfo(self): """get all children information Returns: children's extended address """ print '%s call getChildrenInfo' % self.port try: childrenInfoAll = ...