Python typing.Tuple() Examples
The following are 30
code examples of typing.Tuple().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
typing
, or try the search function
.
Example #1
Source File: file_utils.py From cmrc2019 with Creative Commons Attribution Share Alike 4.0 International | 9 votes |
def filename_to_url(filename: str, cache_dir: Union[str, Path] = None) -> Tuple[str, str]: """ Return the url and etag (which may be ``None``) stored for `filename`. Raise ``FileNotFoundError`` if `filename` or its stored metadata do not exist. """ if cache_dir is None: cache_dir = PYTORCH_PRETRAINED_BERT_CACHE if isinstance(cache_dir, Path): cache_dir = str(cache_dir) cache_path = os.path.join(cache_dir, filename) if not os.path.exists(cache_path): raise FileNotFoundError("file {} not found".format(cache_path)) meta_path = cache_path + '.json' if not os.path.exists(meta_path): raise FileNotFoundError("file {} not found".format(meta_path)) with open(meta_path) as meta_file: metadata = json.load(meta_file) url = metadata['url'] etag = metadata['etag'] return url, etag
Example #2
Source File: black_box.py From OpenFermion-Cirq with Apache License 2.0 | 6 votes |
def noise_bounds(self, cost: float, confidence: Optional[float]=None ) -> Tuple[float, float]: """Exact or approximate bounds on noise in the objective function. Returns a tuple (a, b) such that when `evaluate_with_cost` is called with the given cost and returns an approximate function value y, the true function value lies in the interval [y + a, y + b]. Thus, it should be the case that a <= 0 <= b. This function takes an optional `confidence` parameter which is a real number strictly between 0 and 1 that gives the confidence level in the bound. This is used for situations in which exact bounds on the noise cannot be guaranteed. The value can be interpreted as the probability that a repeated call to `evaluate_with_cost` with the same cost will return a value within the bounds. """ return -numpy.inf, numpy.inf
Example #3
Source File: shamir.py From python-shamir-mnemonic with MIT License | 6 votes |
def _precompute_exp_log() -> Tuple[List[int], List[int]]: exp = [0 for i in range(255)] log = [0 for i in range(256)] poly = 1 for i in range(255): exp[i] = poly log[poly] = i # Multiply poly by the polynomial x + 1. poly = (poly << 1) ^ poly # Reduce poly by x^8 + x^4 + x^3 + x + 1. if poly & 0x100: poly ^= 0x11B return exp, log
Example #4
Source File: terraformize_terraform_wrapper.py From terraformize with GNU Lesser General Public License v3.0 | 6 votes |
def apply(self, variables: Optional[dict] = None, parallelism: int = 10) -> Tuple[str, str, str]: """ Will run a terraform apply on a workspace & will pass all variables to the terraform apply as terraform variables Arguments: :param variables: the variables to pass to the terraform apply command :param parallelism: the number of parallel resource operations Returns: :return return_code: the return code of the terraform apply :return stdout: the stdout stream of the terraform apply :return stderr: the stderr stream of the terraform apply """ if variables is None: variables = {} return_code, stdout, stderr = self.tf.apply(no_color=IsFlagged, var=variables, skip_plan=True, parallelism=parallelism) return return_code, stdout, stderr
Example #5
Source File: terraformize_terraform_wrapper.py From terraformize with GNU Lesser General Public License v3.0 | 6 votes |
def destroy(self, variables: Optional[dict] = None, parallelism: int = 10) -> Tuple[str, str, str]: """ Arguments: :param variables: the variables to pass to the terraform destroy command :param parallelism: the number of parallel resource operations Will run a terraform destroy on a workspace will pass all variables to the terraform destroy as terraform variables, not deleting the workspace as one might want to keep historical data or have multiple modules under the same workspace name Arguments: Returns: :return return_code: the return code of the terraform destroy :return stdout: the stdout stream of the terraform destroy :return stderr: the stderr stream of the terraform destroy """ return_code, stdout, stderr = self.tf.destroy(no_color=IsFlagged, var=variables, auto_approve=True, parallelism=parallelism) return return_code, stdout, stderr
Example #6
Source File: domain.py From everyclass-server with Mozilla Public License 2.0 | 6 votes |
def semester_calculate(current_semester: str, semester_list: List[str]) -> List[Tuple[str, bool]]: """生成一个列表,每个元素是一个二元组,分别为学期字符串和是否为当前学期的布尔值""" available_semesters = [] for each_semester in semester_list: if current_semester == each_semester: available_semesters.append((each_semester, True)) else: available_semesters.append((each_semester, False)) return available_semesters
Example #7
Source File: domain.py From everyclass-server with Mozilla Public License 2.0 | 6 votes |
def get_semester_date(date: datetime.date) -> Tuple[str, int, int]: """获取日期对应的学期、所属周次及星期(0表示周日,1表示周一...) >>> get_semester_date(datetime.date(2020, 2, 22)) ('2019-2020-1', 26, 6) >>> get_semester_date(datetime.date(2020, 2, 23)) ('2019-2020-2', 1, 0) """ config = get_config() semesters = list(config.AVAILABLE_SEMESTERS.items()) semesters.sort(key=lambda x: x[0], reverse=True) for sem in semesters: sem_start_date = datetime.date(*sem[1]["start"]) if date >= sem_start_date: days_delta = (date - sem_start_date).days return "-".join([str(x) for x in sem[0]]), days_delta // 7 + 1, days_delta % 7 raise ValueError("no applicable semester")
Example #8
Source File: views.py From everyclass-server with Mozilla Public License 2.0 | 6 votes |
def _empty_column_check(cards: dict) -> Tuple[bool, bool, bool, bool]: """检查是否周末和晚上有课,返回三个布尔值""" with tracer.trace('_empty_column_check'): # 空闲周末判断,考虑到大多数人周末都是没有课程的 empty_sat = True for cls_time in range(1, 7): if (6, cls_time) in cards: empty_sat = False empty_sun = True for cls_time in range(1, 7): if (7, cls_time) in cards: empty_sun = False # 空闲课程判断,考虑到大多数人11-12节都是没有课程的 empty_6 = True for cls_day in range(1, 8): if (cls_day, 6) in cards: empty_6 = False empty_5 = True for cls_day in range(1, 8): if (cls_day, 5) in cards: empty_5 = False return empty_5, empty_6, empty_sat, empty_sun
Example #9
Source File: helpers.py From hydrus with MIT License | 6 votes |
def get_link_props_for_multiple_objects(path: str, object_list: List[Dict[str, Any]] ) -> Tuple[List[Dict[str, Any]], bool]: """ Get link_props of multiple objects. :param path: Path of the collection or non-collection class. :param object_list: List of objects being inserted. :return: List of link properties processed with the help of get_link_props. """ link_prop_list = list() for object_ in object_list: link_props, type_check = get_link_props(path, object_) if type_check is True: link_prop_list.append(link_props) else: return [], False return link_prop_list, True
Example #10
Source File: helpers.py From hydrus with MIT License | 6 votes |
def add_pagination_iri_mappings(template: str, template_mapping: List[IriTemplateMapping] ) -> Tuple[str, List[IriTemplateMapping]]: """Add various pagination related to variable to the IRI template and also adds mappings for them. :param template: IriTemplate string. :param template_mapping: List of template mappings. :return: Final IriTemplate string and related list of mappings. """ paginate_variables = ["pageIndex", "limit", "offset"] for i in range(len(paginate_variables)): # If final variable then do not add space and comma and add the final parentheses if i == len(paginate_variables) - 1: template += "{})".format(paginate_variables[i]) else: template += "{}, ".format(paginate_variables[i]) mapping = IriTemplateMapping(variable=paginate_variables[i], prop=paginate_variables[i]) template_mapping.append(mapping) return template, template_mapping
Example #11
Source File: crud_helpers.py From hydrus with MIT License | 6 votes |
def calculate_page_limit_and_offset(paginate: bool, page_size: int, page: int, result_length: int, offset: int, limit: int) -> Tuple[int, int]: """Calculate page limit and offset for pagination. :param paginate: Showing whether pagination is enable/disable. :param page_size: Number maximum elements showed in a page. :param page: page number. :param result_length: Length of the list containing desired elements. :param offset: offset value. :param limit: page limit. :return: page limit and offset. """ if limit is not None: page_size = limit if paginate is True: if offset is None: offset = (page - 1) * page_size limit = page_size else: offset = 0 limit = result_length return limit, offset
Example #12
Source File: result.py From OpenFermion-Cirq with Apache License 2.0 | 6 votes |
def __init__(self, optimal_value: float, optimal_parameters: numpy.ndarray, num_evaluations: Optional[int]=None, cost_spent: Optional[float]=None, function_values: Optional[List[Tuple[ float, Optional[float], Optional[numpy.ndarray] ]]]=None, wait_times: Optional[List[float]]=None, time: Optional[int]=None, seed: Optional[int]=None, status: Optional[int]=None, message: Optional[str]=None) -> None: self.optimal_value = optimal_value self.optimal_parameters = optimal_parameters self.num_evaluations = num_evaluations self.cost_spent = cost_spent self.function_values = function_values self.wait_times = wait_times self.time = time self.seed = seed self.status = status self.message = message
Example #13
Source File: objective.py From OpenFermion-Cirq with Apache License 2.0 | 6 votes |
def noise_bounds(self, cost: float, confidence: Optional[float]=None ) -> Tuple[float, float]: """Exact or approximate bounds on noise. Returns a tuple (a, b) such that when `noise` is called with the given cost, the returned value lies between a and b. It should be the case that a <= 0 <= b. This function takes an optional `confidence` parameter which is a real number strictly between 0 and 1 that gives the probability of the bounds being correct. This is used for situations in which exact bounds on the noise cannot be guaranteed. """ return -numpy.inf, numpy.inf
Example #14
Source File: helpers.py From quart with MIT License | 6 votes |
def find_package(name: str) -> Tuple[Optional[Path], Path]: """Finds packages install prefix (or None) and it's containing Folder """ module = name.split(".")[0] loader = pkgutil.get_loader(module) if name == "__main__" or loader is None: package_path = Path.cwd() else: if hasattr(loader, "get_filename"): filename = loader.get_filename(module) # type: ignore else: __import__(name) filename = sys.modules[name].__file__ package_path = Path(filename).resolve().parent if hasattr(loader, "is_package"): is_package = loader.is_package(module) # type: ignore if is_package: package_path = Path(package_path).resolve().parent sys_prefix = Path(sys.prefix).resolve() try: package_path.relative_to(sys_prefix) except ValueError: return None, package_path else: return sys_prefix, package_path
Example #15
Source File: black_box.py From OpenFermion-Cirq with Apache License 2.0 | 6 votes |
def __init__(self, save_x_vals: bool=False, **kwargs) -> None: """ Args: save_x_vals: Whether to save all points (x values) that the black box was queried at. Setting this to True will cause the black box to consume a lot more memory. This does not affect whether the function values (y values) are saved (they are saved no matter what). """ self.function_values = [] \ # type: List[Tuple[float, Optional[float], Optional[numpy.ndarray]]] self.cost_spent = 0.0 self.wait_times = [] # type: List[float] self._save_x_vals = save_x_vals self._time_of_last_query = None # type: Optional[float] super().__init__(**kwargs)
Example #16
Source File: swap_network_trotter_hubbard.py From OpenFermion-Cirq with Apache License 2.0 | 5 votes |
def param_bounds(self) -> Optional[Sequence[Tuple[float, float]]]: """Bounds on the parameters.""" bounds = [] for param in self.params(): s = 1.0 if param.letter == 'V' else 2.0 bounds.append((-s, s)) return bounds
Example #17
Source File: signals.py From quart with MIT License | 5 votes |
def send(self, *sender: Any, **kwargs: Any) -> List[Tuple[Callable, Any]]: coroutines = super().send(*sender, **kwargs) result: List[Tuple[Callable, Any]] = [] for handler, coroutine in coroutines: result.append((handler, await coroutine)) return result
Example #18
Source File: test_utils.py From QCElemental with BSD 3-Clause "New" or "Revised" License | 5 votes |
def doc_fixture(): class Nest(BaseModel): """A nested model""" n: float = 56 class X(BaseModel): """A Pydantic model made up of many, many different combinations of ways of mapping types in Pydantic""" x: int y: str = Field(...) n: Nest n2: Nest = Field(Nest(), description="A detailed description") z: float = 5 z2: float = None z3: Optional[float] z4: Optional[float] = Field(5, description="Some number I just made up") z5: Optional[Union[float, int]] z6: Optional[List[int]] l: List[int] l2: List[Union[int, str]] t: Tuple[str, int] t2: Tuple[List[int]] t3: Tuple[Any] d: Dict[str, Any] dlu: Dict[Union[int, str], List[Union[int, str, float]]] = Field(..., description="this is complicated") dlu2: Dict[Any, List[Union[int, str, float]]] dlu3: Dict[str, Any] si: int = Field(..., description="A level of constraint", gt=0) sf: float = Field(None, description="Optional Constrained Number", le=100.3) yield X
Example #19
Source File: low_rank.py From OpenFermion-Cirq with Apache License 2.0 | 5 votes |
def step_qubit_permutation(self, qubits: Sequence[cirq.Qid], control_qubit: Optional[cirq.Qid]=None ) -> Tuple[Sequence[cirq.Qid], Optional[cirq.Qid]]: # A Trotter step reverses the qubit ordering when the number of # eigenvalues is odd if len(self.eigenvalues) & 1: return qubits[::-1], None else: return qubits, None
Example #20
Source File: trotter_algorithm.py From OpenFermion-Cirq with Apache License 2.0 | 5 votes |
def step_qubit_permutation(self, qubits: Sequence[cirq.Qid], control_qubit: Optional[cirq.Qid]=None ) -> Tuple[Sequence[cirq.Qid], Optional[cirq.Qid]]: """The qubit permutation induced by a single Trotter step. Returns: A tuple whose first element is the new list of system qubits and second element is the new control qubit """ # Default: identity permutation return qubits, control_qubit
Example #21
Source File: simulate_trotter_test.py From OpenFermion-Cirq with Apache License 2.0 | 5 votes |
def produce_simulation_test_parameters( hamiltonian: Hamiltonian, time: float, seed: Optional[int]=None ) -> Tuple[numpy.ndarray, numpy.ndarray]: """Produce objects for testing Hamiltonian simulation. Produces a random initial state and evolves it under the given Hamiltonian for the specified amount of time. Returns the initial state and final state. Args: hamiltonian: The Hamiltonian to evolve under. time: The time to evolve for seed: An RNG seed. """ n_qubits = openfermion.count_qubits(hamiltonian) # Construct a random initial state initial_state = openfermion.haar_random_vector(2**n_qubits, seed) # Simulate exact evolution hamiltonian_sparse = openfermion.get_sparse_operator(hamiltonian) exact_state = scipy.sparse.linalg.expm_multiply( -1j * time * hamiltonian_sparse, initial_state) # Make sure the time is not too small assert fidelity(exact_state, initial_state) < .95 return initial_state, exact_state # Produce test parameters
Example #22
Source File: split_operator.py From OpenFermion-Cirq with Apache License 2.0 | 5 votes |
def step_qubit_permutation(self, qubits: Sequence[cirq.Qid], control_qubit: Optional[cirq.Qid]=None ) -> Tuple[Sequence[cirq.Qid], Optional[cirq.Qid]]: # A Trotter step reverses the qubit ordering return qubits[::-1], control_qubit
Example #23
Source File: swap_network_trotter.py From OpenFermion-Cirq with Apache License 2.0 | 5 votes |
def param_bounds(self) -> Optional[Sequence[Tuple[float, float]]]: """Bounds on the parameters.""" bounds = [] for param in self.params(): if param.letter == 'U' or param.letter == 'V': bounds.append((-1.0, 1.0)) elif param.letter == 'T' or param.letter == 'W': bounds.append((-2.0, 2.0)) return bounds
Example #24
Source File: split_operator_trotter.py From OpenFermion-Cirq with Apache License 2.0 | 5 votes |
def param_bounds(self) -> Optional[Sequence[Tuple[float, float]]]: """Bounds on the parameters.""" return [(-1.0, 1.0)] * len(list(self.params()))
Example #25
Source File: low_rank.py From OpenFermion-Cirq with Apache License 2.0 | 5 votes |
def param_bounds(self) -> Optional[Sequence[Tuple[float, float]]]: """Bounds on the parameters.""" return [(-1.0, 1.0)] * len(list(self.params()))
Example #26
Source File: molecular_example_odd_qubits.py From OpenFermion-Cirq with Apache License 2.0 | 5 votes |
def make_h3_2_5() -> Tuple[RestrictedHartreeFockObjective, of.MolecularData, np. ndarray, np.ndarray, np.ndarray]: # load the molecule from moelcular data h3_2_5_path = os.path.join( hfvqe.__path__[0], 'molecular_data/hydrogen_chains/h_3_p_sto-3g/bond_distance_2.5') molfile = os.path.join(h3_2_5_path, 'H3_plus_sto-3g_singlet_linear_r-2.5.hdf5') molecule = of.MolecularData(filename=molfile) molecule.load() S = np.load(os.path.join(h3_2_5_path, 'overlap.npy')) Hcore = np.load(os.path.join(h3_2_5_path, 'h_core.npy')) TEI = np.load(os.path.join(h3_2_5_path, 'tei.npy')) _, X = sp.linalg.eigh(Hcore, S) obi = of.general_basis_change(Hcore, X, (1, 0)) tbi = np.einsum('psqr', of.general_basis_change(TEI, X, (1, 0, 1, 0))) molecular_hamiltonian = generate_hamiltonian(obi, tbi, molecule.nuclear_repulsion) rhf_objective = RestrictedHartreeFockObjective(molecular_hamiltonian, molecule.n_electrons) scipy_result = rhf_minimization(rhf_objective) return rhf_objective, molecule, scipy_result.x, obi, tbi
Example #27
Source File: variational_black_box.py From OpenFermion-Cirq with Apache License 2.0 | 5 votes |
def noise_bounds(self, cost: float, confidence: Optional[float]=None ) -> Tuple[float, float]: """Exact or approximate bounds on noise in the objective function.""" return self.objective.noise_bounds(cost, confidence)
Example #28
Source File: ansatz.py From OpenFermion-Cirq with Apache License 2.0 | 5 votes |
def param_bounds(self) -> Optional[Sequence[Tuple[float, float]]]: """Optional bounds on the parameters. Returns a list of tuples of the form (low, high), where low and high are lower and upper bounds on a parameter. The order of the tuples corresponds to the order of the parameters as yielded by the `params` method. """ return None
Example #29
Source File: util.py From OpenFermion-Cirq with Apache License 2.0 | 5 votes |
def generate_fswap_unitaries(swap_pairs: List[List[Tuple]], dimension: int): swap_unitaries = [] for swap_tuples in swap_pairs: generator = np.zeros((dimension, dimension), dtype=np.complex128) for i, j in swap_tuples: generator[i, i] = -1 generator[j, j] = -1 generator[i, j] = 1 generator[j, i] = 1 swap_unitaries.append(expm(-1j * np.pi * generator / 2)) return swap_unitaries
Example #30
Source File: molecular_example.py From OpenFermion-Cirq with Apache License 2.0 | 5 votes |
def make_h6_1_3() -> Tuple[RestrictedHartreeFockObjective, of.MolecularData, np.ndarray, np.ndarray, np.ndarray]: # load the molecule from moelcular data import openfermioncirq.experiments.hfvqe as hfvqe h6_1_3_path = os.path.join( hfvqe.__path__[0], 'molecular_data/hydrogen_chains/h_6_sto-3g/bond_distance_1.3') molfile = os.path.join(h6_1_3_path, 'H6_sto-3g_singlet_linear_r-1.3.hdf5') molecule = of.MolecularData(filename=molfile) molecule.load() S = np.load(os.path.join(h6_1_3_path, 'overlap.npy')) Hcore = np.load(os.path.join(h6_1_3_path, 'h_core.npy')) TEI = np.load(os.path.join(h6_1_3_path, 'tei.npy')) _, X = sp.linalg.eigh(Hcore, S) obi = of.general_basis_change(Hcore, X, (1, 0)) tbi = np.einsum('psqr', of.general_basis_change(TEI, X, (1, 0, 1, 0))) molecular_hamiltonian = generate_hamiltonian(obi, tbi, molecule.nuclear_repulsion) rhf_objective = RestrictedHartreeFockObjective(molecular_hamiltonian, molecule.n_electrons) scipy_result = rhf_minimization(rhf_objective) return rhf_objective, molecule, scipy_result.x, obi, tbi