Python typing.Hashable() Examples

The following are 30 code examples of typing.Hashable(). 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: scheduling.py    From bot with MIT License 6 votes vote down vote up
def schedule_task(self, task_id: t.Hashable, task_data: t.Any) -> None:
        """
        Schedules a task.

        `task_data` is passed to the `Scheduler._scheduled_task()` coroutine.
        """
        log.trace(f"{self.cog_name}: scheduling task #{task_id}...")

        if task_id in self._scheduled_tasks:
            log.debug(
                f"{self.cog_name}: did not schedule task #{task_id}; task was already scheduled."
            )
            return

        task = asyncio.create_task(self._scheduled_task(task_data))
        task.add_done_callback(partial(self._task_done_callback, task_id))

        self._scheduled_tasks[task_id] = task
        log.debug(f"{self.cog_name}: scheduled task #{task_id} {id(task)}.") 
Example #2
Source File: MarketSupply.py    From ParadoxTrading with MIT License 6 votes vote down vote up
def addMarketEvent(
            self, _symbol: typing.Hashable, _data: DataStruct
    ) -> ReturnMarket:
        """
        add new tick data into market register, and add event

        :param _symbol:
        :param _data:
        :return:
        """
        for k in self.symbol_dict[_symbol]:
            # add event for each strategy if necessary
            for strategy in self.register_dict[k].strategy_set:
                self.engine.addEvent(MarketEvent(k, strategy, _symbol, _data))
        logging.debug('Data({}) {}'.format(_symbol, _data.toDict()))
        return ReturnMarket(_symbol, _data) 
Example #3
Source File: mongo_wrapper.py    From edgePy with MIT License 6 votes vote down vote up
def find_as_list(
        self,
        database: str,
        collection: str,
        query: Dict[Hashable, Any] = None,
        projection: Dict[Hashable, Any] = None,
    ) -> Iterable:
        """
        Do a find operation on a mongo collection, but return the data as a list

        Args:
            database: db name
            collection: collection name
            query: a dictionary providing the criteria for the find command
            projection: a dictionary that gives the projection - the fields to return.

        Returns:
            a list representation of the returned data.

        """
        cursor = self.find_as_cursor(
            database=database, collection=collection, query=query, projection=projection
        )
        return [c for c in cursor] 
Example #4
Source File: package_source.py    From mixology with MIT License 6 votes vote down vote up
def incompatibilities_for(
        self, package, version
    ):  # type: (Hashable, Any) -> List[Incompatibility]
        """
        Returns the incompatibilities of a given package and version
        """
        dependencies = self.dependencies_for(package, version)
        package_constraint = Constraint(package, Range(version, version, True, True))

        incompatibilities = []
        for dependency in dependencies:
            constraint = self.convert_dependency(dependency)

            if not isinstance(constraint, Constraint):
                constraint = Constraint(package, constraint)

            incompatibility = Incompatibility(
                [Term(package_constraint, True), Term(constraint, False)],
                cause=DependencyCause(),
            )
            incompatibilities.append(incompatibility)

        return incompatibilities 
Example #5
Source File: DGEList.py    From edgePy with MIT License 6 votes vote down vote up
def _sample_group_dict(groups_list: List[str], samples: np.array):
        """
        Converts data in the form ['group1', 'group1', 'group2', 'group2']
        to the form  {'group1': ['sample1', 'sample2'], 'group2': ['sample3', 'sample4'}

        Args:
            groups_list: group names in a list, in the same order as samples.

        Returns:
            dictionary containing the sample types, each with a list of samples.

        """
        d: Dict[Hashable, Any] = {}
        log.info(samples)
        for idx, group in enumerate(groups_list):
            if group not in d:
                d[group] = []
            d[group].append(samples[idx])
        return d 
Example #6
Source File: partial_solution.py    From mixology with MIT License 6 votes vote down vote up
def decide(self, package, version):  # type: (Hashable, Any) -> None
        """
        Adds an assignment of package as a decision
        and increments the decision level.
        """
        # When we make a new decision after backtracking, count an additional
        # attempted solution. If we backtrack multiple times in a row, though, we
        # only want to count one, since we haven't actually started attempting a
        # new solution.
        if self._backtracking:
            self._attempted_solutions += 1

        self._backtracking = False
        self._decisions[package] = version

        self._assign(
            Assignment.decision(
                package, version, self.decision_level, len(self._assignments)
            )
        ) 
Example #7
Source File: rollout.py    From imitation with MIT License 6 votes vote down vote up
def finish_trajectory(self, key: Hashable = None) -> types.TrajectoryWithRew:
        """Complete the trajectory labelled with `key`.

        Args:
            key: key uniquely identifying which in-progress trajectory to remove.

        Returns:
            traj: list of completed trajectories popped from
                `self.partial_trajectories`.
        """
        part_dicts = self.partial_trajectories[key]
        del self.partial_trajectories[key]
        out_dict_unstacked = collections.defaultdict(list)
        for part_dict in part_dicts:
            for key, array in part_dict.items():
                out_dict_unstacked[key].append(array)
        out_dict_stacked = {
            key: np.stack(arr_list, axis=0)
            for key, arr_list in out_dict_unstacked.items()
        }
        traj = types.TrajectoryWithRew(**out_dict_stacked)
        assert traj.rews.shape[0] == traj.acts.shape[0] == traj.obs.shape[0] - 1
        return traj 
Example #8
Source File: uniform_graph_device.py    From Cirq with Apache License 2.0 6 votes vote down vote up
def uniform_undirected_graph_device(
        edges: Iterable[Iterable[ops.Qid]],
        edge_label: Optional[UndirectedGraphDeviceEdge] = None
) -> UndirectedGraphDevice:
    """An undirected graph device all of whose edges are the same.

    Args:
        edges: The edges.
        edge_label: The label to apply to all edges. Defaults to None.
    """

    labelled_edges: Dict[Iterable[Hashable], Any] = {
        frozenset(edge): edge_label for edge in edges
    }
    device_graph = UndirectedHypergraph(labelled_edges=labelled_edges)
    return UndirectedGraphDevice(device_graph=device_graph) 
Example #9
Source File: simulation_results.py    From pyblp with MIT License 6 votes vote down vote up
def __init__(
            self, simulation: 'Simulation', data_override: Dict[str, Array], delta: Array, costs: Array,
            start_time: float, end_time: float, iteration_stats: Dict[Hashable, SolverStats]) -> None:
        """Structure simulation results."""
        self.simulation = simulation
        self.product_data = update_matrices(
            simulation.product_data,
            {k: (v, v.dtype) for k, v in data_override.items()}
        )
        self.delta = delta
        self.costs = costs
        self.computation_time = end_time - start_time
        self.fp_converged = np.array(
            [iteration_stats[t].converged for t in simulation.unique_market_ids], dtype=np.bool
        )
        self.fp_iterations = np.array(
            [iteration_stats[t].iterations for t in simulation.unique_market_ids], dtype=np.int
        )
        self.contraction_evaluations = np.array(
            [iteration_stats[t].evaluations for t in simulation.unique_market_ids], dtype=np.int
        )
        self._data_override = data_override 
Example #10
Source File: identity.py    From geofront with GNU Affero General Public License v3.0 6 votes vote down vote up
def __init__(self,
                 team_type: Type['Team'],
                 identifier: Union[Hashable, str, int],  # workaround mypy bug
                 access_token=None) -> None:
        if not isinstance(team_type, type):
            raise TypeError('team_type must be a type, not ' + repr(team_type))
        from .team import Team  # noqa: F811
        if not issubclass(team_type, Team):
            raise TypeError('team_type must be a subclass of {0.__module__}.'
                            '{0.__qualname__}'.format(Team))
        elif not callable(getattr(identifier, '__hash__')):
            raise TypeError('identifier must be hashable, not ' +
                            repr(identifier))
        self.team_type = cast(Type[Team], team_type)
        self.identifier = identifier  # type: Union[Hashable, str, int]
        self.access_token = access_token 
Example #11
Source File: scheduling.py    From bot with MIT License 6 votes vote down vote up
def cancel_task(self, task_id: t.Hashable, ignore_missing: bool = False) -> None:
        """
        Unschedule the task identified by `task_id`.

        If `ignore_missing` is True, a warning will not be sent if a task isn't found.
        """
        log.trace(f"{self.cog_name}: cancelling task #{task_id}...")
        task = self._scheduled_tasks.get(task_id)

        if not task:
            if not ignore_missing:
                log.warning(f"{self.cog_name}: failed to unschedule {task_id} (no task found).")
            return

        del self._scheduled_tasks[task_id]
        task.cancel()

        log.debug(f"{self.cog_name}: unscheduled task #{task_id} {id(task)}.") 
Example #12
Source File: scheduling.py    From bot with MIT License 5 votes vote down vote up
def __init__(self):
        # Keep track of the child cog's name so the logs are clear.
        self.cog_name = self.__class__.__name__

        self._scheduled_tasks: t.Dict[t.Hashable, asyncio.Task] = {} 
Example #13
Source File: bootstrapped_results.py    From pyblp with MIT License 5 votes vote down vote up
def __init__(
            self, problem_results: ProblemResults, bootstrapped_sigma: Array, bootstrapped_pi: Array,
            bootstrapped_rho: Array, bootstrapped_beta: Array, bootstrapped_gamma: Array, bootstrapped_prices: Array,
            bootstrapped_shares: Array, bootstrapped_delta: Array, start_time: float, end_time: float, draws: int,
            iteration_stats: Mapping[Hashable, SolverStats]) -> None:
        """Structure bootstrapped problem results."""
        super().__init__(
            problem_results.problem, problem_results._parameters, problem_results._moments, problem_results._iteration,
            problem_results._fp_type
        )
        self.problem_results = problem_results
        self.bootstrapped_sigma = bootstrapped_sigma
        self.bootstrapped_pi = bootstrapped_pi
        self.bootstrapped_rho = bootstrapped_rho
        self.bootstrapped_beta = bootstrapped_beta
        self.bootstrapped_gamma = bootstrapped_gamma
        self.bootstrapped_prices = bootstrapped_prices
        self.bootstrapped_shares = bootstrapped_shares
        self.bootstrapped_delta = bootstrapped_delta
        self.computation_time = end_time - start_time
        self.draws = draws
        unique_market_ids = problem_results.problem.unique_market_ids
        self.fp_converged = np.array(
            [[iteration_stats[(d, t)].converged for d in range(self.draws)] for t in unique_market_ids], dtype=np.bool
        )
        self.fp_iterations = np.array(
            [[iteration_stats[(d, t)].iterations for d in range(self.draws)] for t in unique_market_ids], dtype=np.int
        )
        self.contraction_evaluations = np.array(
            [[iteration_stats[(d, t)].evaluations for d in range(self.draws)] for t in unique_market_ids], dtype=np.int
        ) 
Example #14
Source File: problem_results.py    From pyblp with MIT License 5 votes vote down vote up
def _compute_demand_realization(self, data_override: Dict[str, Array], delta: Array) -> Tuple[Array, List[Error]]:
        """Compute a realization of the Jacobian of xi with respect to theta market-by-market. If necessary, revert
        problematic elements to their estimated values.
        """
        errors: List[Error] = []

        # check if the Jacobian does not need to be computed
        xi_jacobian = np.full((self.problem.N, self._parameters.P), np.nan, options.dtype)
        if self._parameters.P == 0:
            return xi_jacobian, errors

        def market_factory(s: Hashable) -> Tuple[ResultsMarket]:
            """Build a market with the data realization along with arguments used to compute the Jacobian."""
            market_s = ResultsMarket(
                self.problem, s, self._parameters, self.sigma, self.pi, self.rho, self.beta, delta=delta,
                data_override=data_override
            )
            return market_s,

        # compute the Jacobian market-by-market
        generator = generate_items(
            self.problem.unique_market_ids, market_factory,
            ResultsMarket.safely_compute_xi_by_theta_jacobian_realization
        )
        for t, (xi_jacobian_t, errors_t) in generator:
            xi_jacobian[self.problem._product_market_indices[t]] = xi_jacobian_t
            errors.extend(errors_t)

        # replace invalid elements
        bad_jacobian_index = ~np.isfinite(xi_jacobian)
        if np.any(bad_jacobian_index):
            xi_jacobian[bad_jacobian_index] = self.xi_by_theta_jacobian[bad_jacobian_index]
            errors.append(exceptions.XiByThetaJacobianReversionError(bad_jacobian_index))

        return xi_jacobian, errors 
Example #15
Source File: moments.py    From pyblp with MIT License 5 votes vote down vote up
def __init__(self, economy_moments: EconomyMoments, t: Hashable) -> None:
        """Select only those micro moment instances that will be computed for this market."""
        super().__init__([m for m in economy_moments.micro_moments if m.market_ids is None or t in m.market_ids]) 
Example #16
Source File: moments.py    From pyblp with MIT License 5 votes vote down vote up
def __init__(self, economy: 'Economy', micro_moments: Sequence[Moment]) -> None:
        """Validate and store information about a sequence of micro moment instances in the context of an economy."""

        # validate the moments
        if not isinstance(micro_moments, collections.abc.Sequence):
            raise TypeError("micro_moments must be a sequence of micro moment instances.")
        for moment in micro_moments:
            if not isinstance(moment, Moment):
                raise TypeError("micro_moments must consist only of micro moment instances.")
            try:
                moment._validate(economy)
            except Exception as exception:
                raise ValueError(f"The micro moment '{moment}' is invalid.") from exception

        # store basic moment information
        super().__init__(micro_moments)

        # identify moment indices that are relevant in each market along with the associated observed micro values
        self.market_indices: Dict[Hashable, Array] = {}
        self.market_values: Dict[Hashable, Array] = {}
        for t in economy.unique_market_ids:
            indices = []
            values = []
            for m, moment in enumerate(self.micro_moments):
                market_ids_m = economy.unique_market_ids if moment.market_ids is None else moment.market_ids
                if t in market_ids_m:
                    indices.append(m)
                    values.append(moment.values if moment.values.size == 1 else moment.values[market_ids_m == t])

            self.market_indices[t] = np.array(indices, np.int)
            self.market_values[t] = np.array(values, options.dtype).flatten()

        # count the number of markets associated with moments
        self.market_counts = np.zeros(self.MM, np.int)
        self.pairwise_market_counts = np.zeros((self.MM, self.MM), np.int)
        for m, moment_m in enumerate(self.micro_moments):
            market_ids_m = set(economy.unique_market_ids if moment_m.market_ids is None else moment_m.market_ids)
            self.market_counts[m] = len(market_ids_m)
            for n, moment_n in enumerate(self.micro_moments):
                market_ids_n = set(economy.unique_market_ids if moment_n.market_ids is None else moment_n.market_ids)
                self.pairwise_market_counts[m, n] = len(market_ids_m & market_ids_n) 
Example #17
Source File: problem_results.py    From pyblp with MIT License 5 votes vote down vote up
def _compute_supply_realization(
            self, data_override: Dict[str, Array], delta: Array, tilde_costs: Array, xi_jacobian: Array) -> (
            Tuple[Array, List[Error]]):
        """Compute a realization of the Jacobian of omega with respect to theta market-by-market. If necessary, revert
        problematic elements to their estimated values.
        """
        errors: List[Error] = []

        def market_factory(s: Hashable) -> Tuple[ResultsMarket, Array, Array]:
            """Build a market with the data realization along with arguments used to compute the Jacobians."""
            market_s = ResultsMarket(
                self.problem, s, self._parameters, self.sigma, self.pi, self.rho, self.beta, delta=delta,
                data_override=data_override
            )
            tilde_costs_s = tilde_costs[self.problem._product_market_indices[s]]
            xi_jacobian_s = xi_jacobian[self.problem._product_market_indices[s]]
            return market_s, tilde_costs_s, xi_jacobian_s

        # compute the Jacobian market-by-market
        omega_jacobian = np.full((self.problem.N, self._parameters.P), np.nan, options.dtype)
        generator = generate_items(
            self.problem.unique_market_ids, market_factory,
            ResultsMarket.safely_compute_omega_by_theta_jacobian_realization
        )
        for t, (omega_jacobian_t, errors_t) in generator:
            omega_jacobian[self.problem._product_market_indices[t]] = omega_jacobian_t
            errors.extend(errors_t)

        # the Jacobian should be zero for any clipped marginal costs
        omega_jacobian[self.clipped_costs.flat] = 0

        # replace invalid elements
        bad_jacobian_index = ~np.isfinite(omega_jacobian)
        if np.any(bad_jacobian_index):
            omega_jacobian[bad_jacobian_index] = self.omega_by_theta_jacobian[bad_jacobian_index]
            errors.append(exceptions.OmegaByThetaJacobianReversionError(bad_jacobian_index))

        return omega_jacobian, errors 
Example #18
Source File: intensity_table.py    From starfish with MIT License 5 votes vote down vote up
def _build_xarray_coords(
            spot_attributes: SpotAttributes,
            round_values: Sequence[int],
            channel_values: Sequence[int],
    ) -> Dict[Hashable, np.ndarray]:
        """build coordinates for intensity-table"""
        coordinates = {
            k: (Features.AXIS, spot_attributes.data[k].values)
            for k in spot_attributes.data}
        coordinates.update({
            Features.AXIS: np.arange(len(spot_attributes.data)),
            Axes.ROUND.value: np.array(round_values),
            Axes.CH.value: np.array(channel_values),
        })
        return coordinates 
Example #19
Source File: _spot_finding_results.py    From starfish with MIT License 5 votes vote down vote up
def get_physical_coord_ranges(self) -> Mapping[Hashable, xr.DataArray]:
        """
        Returns the physical coordinate ranges the SpotResults cover. Needed
        information for calculating the physical coordinate values of decoded spots.
        """
        return self.physical_coord_ranges 
Example #20
Source File: package_source.py    From mixology with MIT License 5 votes vote down vote up
def _versions_for(
        self, package, constraint=None
    ):  # type: (Hashable, Any) -> List[Hashable]
        if package not in self._packages:
            return []

        versions = []
        for version in self._packages[package].keys():
            if not constraint or constraint.allows_any(
                Range(version, version, True, True)
            ):
                versions.append(version)

        return sorted(versions, reverse=True) 
Example #21
Source File: _spot_finding_results.py    From starfish with MIT License 5 votes vote down vote up
def __init__(
            self,
            imagestack_coords,
            log: Log,
            spot_attributes_list: Optional[
                Sequence[Tuple[PerImageSliceSpotResults, Mapping[Axes, int]]]] = None,
    ):
        """
        Construct a SpotFindingResults instance

        Parameters
        -----------
        imagestack_coords : xr.CoordinateArray
            The physical coordinate ranges of the ImageStack spots were found in
        log : Log
            The provenance log information from the ImageStack spots were found in.
        spot_attributes_list : Optional[
        Sequence[Tuple[PerImageSliceSpotResults, Mapping[Axes, int]]]]
            If spots were found using ImageStack.transform() the result is a list of
            tuples (PerImageSliceSpotResults, indices).  Indices should be a mapping from axes to
            axis value.  Instantiating SpotFindingResults with this list will convert the
            information to a dictionary.
        """
        spot_attributes_list = spot_attributes_list or []
        self._results: MutableMapping[Tuple, PerImageSliceSpotResults] = {
            tuple(indices[i] for i in AXES_ORDER): spots
            for spots, indices in spot_attributes_list
        }
        self.physical_coord_ranges: Mapping[Hashable, xr.DataArray] = {
            Axes.X.value: imagestack_coords[Coordinates.X.value],
            Axes.Y.value: imagestack_coords[Coordinates.Y.value],
            Axes.ZPLANE.value: imagestack_coords[Coordinates.Z.value]}
        self._log: Log = log 
Example #22
Source File: interface.py    From review-heatmap with GNU Affero General Public License v3.0 5 votes vote down vote up
def __delitem__(self, key: Hashable) -> None:
        del self.data[key] 
Example #23
Source File: interface.py    From review-heatmap with GNU Affero General Public License v3.0 5 votes vote down vote up
def __setitem__(self, key: Hashable, value: Any) -> None:
        self.data[key] = value 
Example #24
Source File: query.py    From ezdxf with MIT License 5 votes vote down vote up
def groupby(self, dxfattrib: str = '', key: Callable[['DXFEntity'], Hashable] = None) \
            -> Dict[Hashable, List['DXFEntity']]:
        """
        Returns a dict of entity lists, where entities are grouped by a DXF attribute or a key function.

        Args:
            dxfattrib: grouping DXF attribute as string like ``'layer'``
            key: key function, which accepts a DXFEntity as argument, returns grouping key of this entity or None for
                 ignore this object. Reason for ignoring: a queried DXF attribute is not supported by this entity

        """
        return groupby(self.entities, dxfattrib, key) 
Example #25
Source File: interface.py    From review-heatmap with GNU Affero General Public License v3.0 5 votes vote down vote up
def __getitem__(self, key: Hashable) -> Any:
        if key in self.data:
            return self.data[key]
        if hasattr(self.__class__, "__missing__"):
            return self.__class__.__missing__(self, key)  # type: ignore
        raise KeyError(key) 
Example #26
Source File: initialization.py    From Cirq with Apache License 2.0 5 votes vote down vote up
def get_center(graph: nx.Graph) -> Hashable:
    centralities = nx.betweenness_centrality(graph)
    return max(centralities, key=centralities.get) 
Example #27
Source File: base.py    From review-heatmap with GNU Affero General Public License v3.0 5 votes vote down vote up
def __setitem__(self, key: Hashable, value: Any) -> None:
        if not self._loaded:
            raise ConfigNotLoadedError()
        super().__setitem__(key, value)
        if self._atomic:
            self.save()
        else:
            self._dirty = True

    # Fill out ConfigInterface abstract methods and properties 
Example #28
Source File: base.py    From review-heatmap with GNU Affero General Public License v3.0 5 votes vote down vote up
def __getitem__(self, key: Hashable) -> Any:
        if not self._loaded:
            raise ConfigNotLoadedError()
        return super().__getitem__(key) 
Example #29
Source File: cbits.py    From quantumflow with Apache License 2.0 5 votes vote down vote up
def __init__(self, register: 'Register', key: Hashable) -> None:
        self.register = register
        self.key = key 
Example #30
Source File: cbits.py    From quantumflow with Apache License 2.0 5 votes vote down vote up
def __getitem__(self, key: Hashable) -> 'Addr':
        return Addr(self, key)