Python dataclasses.astuple() Examples
The following are 21
code examples of dataclasses.astuple().
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
dataclasses
, or try the search function
.
Example #1
Source File: simulation_model.py From Mastering-Object-Oriented-Python-Second-Edition with MIT License | 6 votes |
def __iter__(self) -> Iterator[Tuple]: """Yield statistical samples.""" x, y = self.table.payout blackjack_payout = x / y for count in range(self.samples): self.player.reset() while self.player.stake > 0 and self.player.rounds > 0: self.player.rounds -= 1 outcome = random.random() if outcome < 0.579: self.player.stake -= 1 elif 0.579 <= outcome < 0.883: self.player.stake += 1 elif 0.883 <= outcome < 0.943: # a "push" pass else: # 0.943 <= outcome self.player.stake += blackjack_payout yield astuple(self.table) + astuple(self.player)
Example #2
Source File: ch13_ex2.py From Mastering-Object-Oriented-Python-Second-Edition with MIT License | 6 votes |
def hands(h: int, c: int) -> Tuple[Dict[str, Any], int]: if h == 0 or c == 0: return jsonify( status="Bad Request", error=[f"hands={h!r}, dominoes={c!r} is invalid"] ), HTTPStatus.BAD_REQUEST if app.env == "development": random.seed(2) b = Boneyard(limit=6) try: hand_list = b.deal(c, h) except ValueError as ex: return jsonify(status="Bad Request", error=ex.args), HTTPStatus.BAD_REQUEST app.logger.info("Send %r", hand_list) return jsonify( status="OK", dominoes=[[astuple(d) for d in hand] for hand in hand_list] ), HTTPStatus.OK
Example #3
Source File: tables.py From Pyslvs-UI with GNU Affero General Public License v3.0 | 5 votes |
def edit_point(self, row: int, arg: PointArgs) -> None: """Edit a point.""" for i, e in enumerate((f'Point{row}',) + astuple(arg) + (f"({arg.x}, {arg.y})",)): item = QTableWidgetItem(str(e)) item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) if i == 3: item.setIcon(color_icon(e)) self.setItem(row, i, item)
Example #4
Source File: update-version.py From transformer with MIT License | 5 votes |
def increment_version(v: Version, incr: Increment) -> Version: values = list(dataclasses.astuple(v)) values[incr.value] += 1 for i in range(incr.value + 1, max(Increment).value + 1): values[i] = 0 return Version(*values)
Example #5
Source File: style_transfer.py From style_transfer with MIT License | 5 votes |
def eval_sc_grad(self, pool, roll, content_layers, style_layers, dd_layers, layer_weights, content_weight, style_weight, dd_weight, tile_size): """Evaluates the summed style and content gradients.""" loss = 0 grad = np.zeros_like(self.img) img_size = np.array(self.img.shape[-2:]) ntiles = (img_size - 1) // tile_size + 1 tile_size = img_size // ntiles for y in range(ntiles[0]): for x in range(ntiles[1]): xy = np.array([y, x]) start = xy * tile_size end = start + tile_size if y == ntiles[0] - 1: end[0] = img_size[0] if x == ntiles[1] - 1: end[1] = img_size[1] tile = self.img[:, start[0]:end[0], start[1]:end[1]] pool.ensure_healthy() pool.request( SCGradRequest((start, end), SharedNDArray.copy(tile), roll, start, content_layers, style_layers, dd_layers, layer_weights, content_weight, style_weight, dd_weight)) pool.reset_next_worker() for _ in range(np.prod(ntiles)): (start, end), loss_tile, grad_tile = astuple(pool.resp_q.get()) loss += loss_tile grad[:, start[0]:end[0], start[1]:end[1]] = grad_tile.array grad_tile.unlink() return loss, grad
Example #6
Source File: style_transfer.py From style_transfer with MIT License | 5 votes |
def eval_features_once(self, pool, layers, tile_size=512): """Computes the set of feature maps for an image.""" img_size = np.array(self.img.shape[-2:]) ntiles = (img_size - 1) // tile_size + 1 tile_size = img_size // ntiles if np.prod(ntiles) > 1: print('Using %dx%d tiles of size %dx%d.' % (ntiles[1], ntiles[0], tile_size[1], tile_size[0])) features = {} for layer in layers: scale, channels = self.layer_info(layer) shape = (channels,) + tuple(np.int32(np.ceil(img_size / scale))) features[layer] = np.zeros(shape, dtype=np.float32) for y in range(ntiles[0]): for x in range(ntiles[1]): xy = np.array([y, x]) start = xy * tile_size end = start + tile_size if y == ntiles[0] - 1: end[0] = img_size[0] if x == ntiles[1] - 1: end[1] = img_size[1] tile = self.img[:, start[0]:end[0], start[1]:end[1]] pool.ensure_healthy() pool.request(FeatureMapRequest(start, SharedNDArray.copy(tile), layers)) pool.reset_next_worker() for _ in range(np.prod(ntiles)): start, feats_tile = astuple(pool.resp_q.get()) for layer, feat in feats_tile.items(): scale, _ = self.layer_info(layer) start_f = start // scale end_f = start_f + np.array(feat.array.shape[-2:]) features[layer][:, start_f[0]:end_f[0], start_f[1]:end_f[1]] = feat.array feat.unlink() return features
Example #7
Source File: scan_container_images.py From cc-utils with Apache License 2.0 | 5 votes |
def _clamav_report(self): result = '<p><div>Virus Scanning Results:</div>' return result + tabulate.tabulate( map(lambda dc: dataclasses.astuple(dc), self._clamav_results), headers=MalwareScanResult.headers(), tablefmt='html', )
Example #8
Source File: ch13_ex2.py From Mastering-Object-Oriented-Python-Second-Edition with MIT License | 5 votes |
def dominoes(n: str) -> Tuple[Dict[str, Any], int]: try: hand_size = int(n) except ValueError: abort(HTTPStatus.BAD_REQUEST) if app.env == "development": random.seed(2) b = Boneyard(limit=6) hand_0 = b.deal(hand_size)[0] app.logger.info("Send %r", hand_0) return jsonify(status="OK", dominoes=[astuple(d) for d in hand_0]), HTTPStatus.OK
Example #9
Source File: flows.py From spins-b with GNU General Public License v3.0 | 5 votes |
def __eq__(self, other: "Flow") -> bool: """Checks if two dataclasses are equal to which other. We need to implement equality operator separately to handle NumPy arrays, which require calling `.all()` to indicate equality. Args: other: Flow to compare to. Returns: `True` only if `self` and `other` are the same type and their values are equal. Raises: NotImplemented: If the flow types are different between `self` and `other`. """ if self is other: return True if self.__class__ != other.__class__: raise NotImplemented( "Cannot compare flow types, got {} and {}".format(self, other)) for val1, val2 in zip(dataclasses.astuple(self), dataclasses.astuple(other)): if val1 is val2: equal = True elif isinstance(val1, np.ndarray) and isinstance(val2, np.ndarray): equal = (val1.shape == val2.shape) and (val1 == val2).all() else: equal = val1 == val2 if not equal: return False return True
Example #10
Source File: util.py From starfish with MIT License | 5 votes |
def render_coordinates_to_rows( tile_to_physical_coordinates: Mapping[ TileIdentifier, Mapping[Coordinates, CoordinateValue]], ) -> Sequence[Mapping[str, str]]: results: MutableSequence[Mapping[str, str]] = list() for tile_identifier, physical_coordinates in tile_to_physical_coordinates.items(): rowdata: MutableMapping[str, str] = dict() for tile_coordinate_name, tile_coordinate_value in zip( TILE_COORDINATE_NAMES, dataclasses.astuple(tile_identifier) ): rowdata[tile_coordinate_name] = str(tile_coordinate_value) for coordinate_name in list(Coordinates): coordinate_value = physical_coordinates.get(coordinate_name, None) if coordinate_value is None and coordinate_name == Coordinates.Z: # Z coordinates may be legitimately missing continue if isinstance(coordinate_value, tuple): rowdata[f'{coordinate_name}_min'] = str(coordinate_value[0]) rowdata[f'{coordinate_name}_max'] = str(coordinate_value[1]) else: rowdata[f'{coordinate_name}_min'] = str(coordinate_value) results.append(rowdata) return results
Example #11
Source File: tables.py From Pyslvs-UI with GNU Affero General Public License v3.0 | 5 votes |
def edit_link(self, row: int, arg: LinkArgs): """Edit a link.""" for i, e in enumerate(astuple(arg)): item = QTableWidgetItem(e) item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) if i == 1: item.setIcon(color_icon(e)) self.setItem(row, i, item)
Example #12
Source File: simulator.py From whynot with MIT License | 5 votes |
def simulate(initial_state, config, intervention=None, seed=None): """Simulate a run of the Lotka volterra model. Parameters ---------- initial_state: whynot.lotka_volterra.State config: whynot.lotka_volterra.Config Base parameters for the simulator run intervention: whynot.lotka_volterra.Intervention (Optional) Parameters specifying a change in dynamics seed: int Unused since the simulator is deterministic. Returns ------- run: whynot.dynamics.Run Simulator rollout """ # pylint: disable-msg=unused-argument t_eval = np.arange( config.start_time, config.end_time + config.delta_t, config.delta_t ) solution = odeint( dynamics, y0=dataclasses.astuple(initial_state), t=t_eval, args=(config, intervention), rtol=1e-4, atol=1e-4, ) states = [initial_state] + [State(*state) for state in solution[1:]] return wn.dynamics.Run(states=states, times=t_eval)
Example #13
Source File: main_base.py From Pyslvs-UI with GNU Affero General Public License v3.0 | 5 votes |
def copy(self): """Make a copy of preference data.""" return Preferences(*astuple(self))
Example #14
Source File: device_funcs.py From espnet with Apache License 2.0 | 5 votes |
def to_device(data, device=None, dtype=None, non_blocking=False, copy=False): """Change the device of object recursively""" if isinstance(data, dict): return { k: to_device(v, device, dtype, non_blocking, copy) for k, v in data.items() } elif dataclasses.is_dataclass(data) and not isinstance(data, type): return type(data)( *[ to_device(v, device, dtype, non_blocking, copy) for v in dataclasses.astuple(data) ] ) # maybe namedtuple. I don't know the correct way to judge namedtuple. elif isinstance(data, tuple) and type(data) is not tuple: return type(data)( *[to_device(o, device, dtype, non_blocking, copy) for o in data] ) elif isinstance(data, (list, tuple)): return type(data)(to_device(v, device, dtype, non_blocking, copy) for v in data) elif isinstance(data, np.ndarray): return to_device(torch.from_numpy(data), device, dtype, non_blocking, copy) elif isinstance(data, torch.Tensor): return data.to(device, dtype, non_blocking, copy) else: return data
Example #15
Source File: test_rva.py From eyeD3 with GNU General Public License v3.0 | 5 votes |
def test_default_v23(): f = RelVolAdjFrameV23() assert f.id == b"RVAD" f.adjustments = RelVolAdjFrameV23.VolumeAdjustments() f.render() f2 = RelVolAdjFrameV23() f2.parse(f.data, f.header) assert f.adjustments == f2.adjustments assert set(dataclasses.astuple(f.adjustments)) == {0}
Example #16
Source File: core.py From eyeD3 with GNU General Public License v3.0 | 5 votes |
def id3Encode(self): return "\t".join([(o if o else "") for o in dataclasses.astuple(self)])
Example #17
Source File: simulator.py From whynot with MIT License | 5 votes |
def simulate(initial_state, config, intervention=None, seed=None): """Run a simulation of the world2 dynamics from the given initial state. Parameters ---------- initial_state: whynot.simulators.world2.State State object to initialize the simulation config: whynot.simulators.world2.Config Configuration object to determine coefficients of the dynamics. intervention: whynot.simulators.world2.Intervention (Optional) Specify what, if any, intervention to perform during execution. seed: int (Optional) The simulator is deterministic, and the seed parameter is ignored. Returns ------- run: whynot.dynamics.Run Rollout sequence of states and measurement times produced by the simulator. """ # Simulator is deterministic, so seed is ignored # pylint: disable-msg=unused-argument t_eval = np.arange( config.start_time, config.end_time + config.delta_t, config.delta_t ) solution = odeint( dynamics, y0=dataclasses.astuple(initial_state), t=t_eval, args=(config, intervention), rtol=config.rtol, atol=config.atol, ) states = [initial_state] + [State(*state) for state in solution[1:]] return wn.dynamics.Run(states=states, times=t_eval)
Example #18
Source File: simulator.py From whynot with MIT License | 5 votes |
def simulate(initial_state, config, intervention=None, seed=None): """Simulate a run of the Chen et al. model opioid epidemic model. Parameters ---------- initial_state: whynot.simulator.opioid.State Initial state of the dynamics config: whynot.simulator.opioid.Config Config object to determine simulation dynamics. intervention: whynot.simulator.opioid.Intervention (Optional) Intervention object to determine what, if any, intervention to perform during the rollout of the dynamics. seed: int The simulator is deterministic, so the seed parameter is ignored. Returns ------- run: whynot.dynamics.Run Run object produced by running simulate for the opioid simulator """ # pylint: disable-msg=unused-argument # pylint:disable-msg=no-member t_eval = np.arange( config.start_time, config.end_time + config.delta_t, config.delta_t ) solution = odeint( dynamics, y0=dataclasses.astuple(initial_state), t=t_eval, args=(config, intervention), rtol=1e-4, atol=1e-4, ) states = [initial_state] + [State(*state) for state in solution[1:]] return wn.dynamics.Run(states=states, times=t_eval)
Example #19
Source File: simulator.py From whynot with MIT License | 5 votes |
def simulate(initial_state, config, intervention=None, seed=None): """Simulate a run of the Zika simulator model. The simulation starts at initial_state at time 0, and evolves the state using dynamics whose parameters are specified in config. Parameters ---------- initial_state: `whynot.simulators.zika.State` Initial State object, which is used as x_{t_0} for the simulator. config: `whynot.simulators.zika.Config` Config object that encapsulates the parameters that define the dynamics. intervention: `whynot.simulators.zika.Intervention` Intervention object that specifies what, if any, intervention to perform. seed: int Seed to set internal randomness. The simulator is deterministic, so the seed parameter is ignored. Returns ------- run: `whynot.dynamics.Run` Rollout of the model. """ # Simulator is deterministic, so seed is ignored # pylint: disable-msg=unused-argument t_eval = np.arange( config.start_time, config.end_time + config.delta_t, config.delta_t ) solution = odeint( dynamics, y0=dataclasses.astuple(initial_state), t=t_eval, args=(config, intervention), rtol=config.rtol, atol=config.atol, ) states = [initial_state] + [State(*state) for state in solution[1:]] return wn.dynamics.Run(states=states, times=t_eval)
Example #20
Source File: simulator.py From whynot with MIT License | 5 votes |
def simulate(initial_state, config, intervention=None, seed=None): """Simulate a run of the Adams HIV simulator model. The simulation starts at initial_state at time 0, and evolves the state using dynamics whose parameters are specified in config. Parameters ---------- initial_state: `whynot.simulators.hiv.State` Initial State object, which is used as x_{t_0} for the simulator. config: `whynot.simulators.hiv.Config` Config object that encapsulates the parameters that define the dynamics. intervention: `whynot.simulators.hiv.Intervention` Intervention object that specifies what, if any, intervention to perform. seed: int Seed to set internal randomness. The simulator is deterministic, so the seed parameter is ignored. Returns ------- run: `whynot.dynamics.Run` Rollout of the model. """ # Simulator is deterministic, so seed is ignored # pylint: disable-msg=unused-argument t_eval = np.arange( config.start_time, config.end_time + config.delta_t, config.delta_t ) solution = odeint( dynamics, y0=dataclasses.astuple(initial_state), t=t_eval, args=(config, intervention), rtol=config.rtol, atol=config.atol, ) states = [initial_state] + [State(*state) for state in solution[1:]] return wn.dynamics.Run(states=states, times=t_eval)
Example #21
Source File: causal_graphs.py From whynot with MIT License | 4 votes |
def dataclass_to_box(dataclass, trace, name_suffix=None, skip_args=None): """Convert a dataclass object to a traceable box. Parameters ---------- dataclass: instance of dataclasses.dataclass Either a whynot State or a Config object trace: trace_stack context manager Every box is created within the context of a trace name_suffix: str (Optional) Suffix to append to every field name of the dataclass skip_args: list (Optional) List of arguments/dataclass field names to skip tracing. Returns ------- box: instance of dataclasses.dataclass The same input object with fields replaced by boxes to allow for dependency tracing. nodes: dict Dictionary mapping a root TracerNode to the corresponding Box. The name of the TracerNode is the fieldname and the optional suffix. """ # Wrap each input argument in a "box" with an associated start node to allow tracing flattened = dataclasses.astuple(dataclass) names = [field.name for field in dataclasses.fields(dataclass)] suffix = f"_{name_suffix}" if name_suffix else "" replacements, node_map = {}, {} for name, value in zip(names, flattened): if skip_args and name in skip_args: # Don't wrap this argument in a box replacements[name] = value elif hasattr(value, "get_boxable"): # The value itself isn't traceble, but it exports # methods that allow it to be traced. boxable = value.get_boxable() boxable = check_and_cast_args(boxable) node = TracerNode.new_root(boxable, name + suffix) box = new_box(boxable, trace, node) value.set_boxable(box) replacements[name] = value node_map[node] = box else: # Try to wrap the value in a box, casting as possible for dependency tracing value = check_and_cast_args(value) node = TracerNode.new_root(value, name + suffix) box = new_box(value, trace, node) replacements[name] = box node_map[node] = box # Generate a new dataclass, replacing each value with the corresponding box dataclass = dataclasses.replace(dataclass, **replacements) return dataclass, node_map