language stringclasses 1 value | repo stringclasses 346 values | path stringlengths 6 201 | class_span dict | source stringlengths 21 2.38M | target stringlengths 1 96 |
|---|---|---|---|---|---|
python | tensorflow__tensorflow | tensorflow/python/saved_model/tests/variable_wrapper_test.py | {
"start": 1283,
"end": 2155
} | class ____(base.Trackable):
_should_act_as_resource_variable = True
def __init__(self, value):
self.value = variables.Variable(value)
@property
def _shared_name(self):
return self.value._shared_name
def _serialize_to_tensors(self):
return self.value._serialize_to_tensors()
def _restore_from_tensors(self, restored_tensors):
return self.value._restore_from_tensors(restored_tensors)
def _export_to_saved_model_graph(
self, object_map, tensor_map, options, **kwargs
):
resource_list = self.value._export_to_saved_model_graph( # pylint:disable=protected-access
object_map, tensor_map, options, **kwargs
)
object_map[self] = VariableWrapper(object_map[self.value])
return resource_list
def _write_object_proto(self, proto, options):
return self.value._write_object_proto(proto, options)
| VariableWrapper |
python | wandb__wandb | wandb/vendor/pygments/lexers/rust.py | {
"start": 447,
"end": 7691
} | class ____(RegexLexer):
"""
Lexer for the Rust programming language (version 1.10).
.. versionadded:: 1.6
"""
name = 'Rust'
filenames = ['*.rs', '*.rs.in']
aliases = ['rust']
mimetypes = ['text/rust']
keyword_types = (
words(('u8', 'u16', 'u32', 'u64', 'i8', 'i16', 'i32', 'i64',
'usize', 'isize', 'f32', 'f64', 'str', 'bool'),
suffix=r'\b'),
Keyword.Type)
builtin_types = (words((
# Reexported core operators
'Copy', 'Send', 'Sized', 'Sync',
'Drop', 'Fn', 'FnMut', 'FnOnce',
# Reexported types and traits
'Box',
'ToOwned',
'Clone',
'PartialEq', 'PartialOrd', 'Eq', 'Ord',
'AsRef', 'AsMut', 'Into', 'From',
'Default',
'Iterator', 'Extend', 'IntoIterator',
'DoubleEndedIterator', 'ExactSizeIterator',
'Option',
'Some', 'None',
'Result',
'Ok', 'Err',
'SliceConcatExt',
'String', 'ToString',
'Vec'), suffix=r'\b'),
Name.Builtin)
tokens = {
'root': [
# rust allows a file to start with a shebang, but if the first line
# starts with #![ then it’s not a shebang but a crate attribute.
(r'#![^[\r\n].*$', Comment.Preproc),
default('base'),
],
'base': [
# Whitespace and Comments
(r'\n', Whitespace),
(r'\s+', Whitespace),
(r'//!.*?\n', String.Doc),
(r'///(\n|[^/].*?\n)', String.Doc),
(r'//(.*?)\n', Comment.Single),
(r'/\*\*(\n|[^/*])', String.Doc, 'doccomment'),
(r'/\*!', String.Doc, 'doccomment'),
(r'/\*', Comment.Multiline, 'comment'),
# Macro parameters
(r"""\$([a-zA-Z_]\w*|\(,?|\),?|,?)""", Comment.Preproc),
# Keywords
(words((
'as', 'box', 'const', 'crate', 'else', 'extern',
'for', 'if', 'impl', 'in', 'loop', 'match', 'move',
'mut', 'pub', 'ref', 'return', 'static', 'super',
'trait', 'unsafe', 'use', 'where', 'while'), suffix=r'\b'),
Keyword),
(words(('abstract', 'alignof', 'become', 'do', 'final', 'macro',
'offsetof', 'override', 'priv', 'proc', 'pure', 'sizeof',
'typeof', 'unsized', 'virtual', 'yield'), suffix=r'\b'),
Keyword.Reserved),
(r'(true|false)\b', Keyword.Constant),
(r'mod\b', Keyword, 'modname'),
(r'let\b', Keyword.Declaration),
(r'fn\b', Keyword, 'funcname'),
(r'(struct|enum|type|union)\b', Keyword, 'typename'),
(r'(default)(\s+)(type|fn)\b', bygroups(Keyword, Text, Keyword)),
keyword_types,
(r'self\b', Name.Builtin.Pseudo),
# Prelude (taken from Rust’s src/libstd/prelude.rs)
builtin_types,
# Path seperators, so types don't catch them.
(r'::\b', Text),
# Types in positions.
(r'(?::|->)', Text, 'typename'),
# Labels
(r'(break|continue)(\s*)(\'[A-Za-z_]\w*)?',
bygroups(Keyword, Text.Whitespace, Name.Label)),
# Character Literal
(r"""'(\\['"\\nrt]|\\x[0-7][0-9a-fA-F]|\\0"""
r"""|\\u\{[0-9a-fA-F]{1,6}\}|.)'""",
String.Char),
(r"""b'(\\['"\\nrt]|\\x[0-9a-fA-F]{2}|\\0"""
r"""|\\u\{[0-9a-fA-F]{1,6}\}|.)'""",
String.Char),
# Binary Literal
(r'0b[01_]+', Number.Bin, 'number_lit'),
# Octal Literal
(r'0o[0-7_]+', Number.Oct, 'number_lit'),
# Hexadecimal Literal
(r'0[xX][0-9a-fA-F_]+', Number.Hex, 'number_lit'),
# Decimal Literal
(r'[0-9][0-9_]*(\.[0-9_]+[eE][+\-]?[0-9_]+|'
r'\.[0-9_]*(?!\.)|[eE][+\-]?[0-9_]+)', Number.Float,
'number_lit'),
(r'[0-9][0-9_]*', Number.Integer, 'number_lit'),
# String Literal
(r'b"', String, 'bytestring'),
(r'"', String, 'string'),
(r'b?r(#*)".*?"\1', String),
# Lifetime
(r"""'static""", Name.Builtin),
(r"""'[a-zA-Z_]\w*""", Name.Attribute),
# Operators and Punctuation
(r'[{}()\[\],.;]', Punctuation),
(r'[+\-*/%&|<>^!~@=:?]', Operator),
# Identifier
(r'[a-zA-Z_]\w*', Name),
# Attributes
(r'#!?\[', Comment.Preproc, 'attribute['),
# Macros
(r'([A-Za-z_]\w*)(!)(\s*)([A-Za-z_]\w*)?(\s*)(\{)',
bygroups(Comment.Preproc, Punctuation, Whitespace, Name,
Whitespace, Punctuation), 'macro{'),
(r'([A-Za-z_]\w*)(!)(\s*)([A-Za-z_]\w*)?(\()',
bygroups(Comment.Preproc, Punctuation, Whitespace, Name,
Punctuation), 'macro('),
],
'comment': [
(r'[^*/]+', Comment.Multiline),
(r'/\*', Comment.Multiline, '#push'),
(r'\*/', Comment.Multiline, '#pop'),
(r'[*/]', Comment.Multiline),
],
'doccomment': [
(r'[^*/]+', String.Doc),
(r'/\*', String.Doc, '#push'),
(r'\*/', String.Doc, '#pop'),
(r'[*/]', String.Doc),
],
'modname': [
(r'\s+', Text),
(r'[a-zA-Z_]\w*', Name.Namespace, '#pop'),
default('#pop'),
],
'funcname': [
(r'\s+', Text),
(r'[a-zA-Z_]\w*', Name.Function, '#pop'),
default('#pop'),
],
'typename': [
(r'\s+', Text),
(r'&', Keyword.Pseudo),
builtin_types,
keyword_types,
(r'[a-zA-Z_]\w*', Name.Class, '#pop'),
default('#pop'),
],
'number_lit': [
(r'[ui](8|16|32|64|size)', Keyword, '#pop'),
(r'f(32|64)', Keyword, '#pop'),
default('#pop'),
],
'string': [
(r'"', String, '#pop'),
(r"""\\['"\\nrt]|\\x[0-7][0-9a-fA-F]|\\0"""
r"""|\\u\{[0-9a-fA-F]{1,6}\}""", String.Escape),
(r'[^\\"]+', String),
(r'\\', String),
],
'bytestring': [
(r"""\\x[89a-fA-F][0-9a-fA-F]""", String.Escape),
include('string'),
],
'macro{': [
(r'\{', Operator, '#push'),
(r'\}', Operator, '#pop'),
],
'macro(': [
(r'\(', Operator, '#push'),
(r'\)', Operator, '#pop'),
],
'attribute_common': [
(r'"', String, 'string'),
(r'\[', Comment.Preproc, 'attribute['),
(r'\(', Comment.Preproc, 'attribute('),
],
'attribute[': [
include('attribute_common'),
(r'\];?', Comment.Preproc, '#pop'),
(r'[^"\]]+', Comment.Preproc),
],
'attribute(': [
include('attribute_common'),
(r'\);?', Comment.Preproc, '#pop'),
(r'[^")]+', Comment.Preproc),
],
}
| RustLexer |
python | ray-project__ray | python/ray/serve/tests/test_config_files/logging_config_test.py | {
"start": 1530,
"end": 1750
} | class ____:
def __call__(self):
logger.debug("this_is_debug_info")
log_file = logger.handlers[1].target.baseFilename
return {"log_file": log_file}
model2 = ModelWithConfig.bind()
| ModelWithConfig |
python | pypa__setuptools | setuptools/tests/test_windows_wrappers.py | {
"start": 6658,
"end": 7868
} | class ____(WrapperTester):
"""
Testing the GUI Version
-----------------------
"""
script_name = 'bar-script.pyw'
wrapper_source = win_launcher_exe('gui')
wrapper_name = 'bar.exe'
script_tmpl = textwrap.dedent(
"""
#!%(python_exe)s
import sys
f = open(sys.argv[1], 'wb')
bytes_written = f.write(repr(sys.argv[2]).encode('utf-8'))
f.close()
"""
).strip()
def test_basic(self, tmpdir):
"""Test the GUI version with the simple script, bar-script.py"""
self.create_script(tmpdir)
cmd = [
str(tmpdir / 'bar.exe'),
str(tmpdir / 'test_output.txt'),
'Test Argument',
]
proc = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
encoding="utf-8",
)
stdout, stderr = proc.communicate()
assert not stdout
assert not stderr
with (tmpdir / 'test_output.txt').open('rb') as f_out:
actual = f_out.read().decode('ascii')
assert actual == repr('Test Argument')
| TestGUI |
python | networkx__networkx | networkx/algorithms/centrality/tests/test_betweenness_centrality_subset.py | {
"start": 39,
"end": 5733
} | class ____:
def test_K5(self):
"""Betweenness Centrality Subset: K5"""
G = nx.complete_graph(5)
b = nx.betweenness_centrality_subset(
G, sources=[0], targets=[1, 3], weight=None
)
b_answer = {0: 0.0, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0}
for n in sorted(G):
assert b[n] == pytest.approx(b_answer[n], abs=1e-7)
def test_P5_directed(self):
"""Betweenness Centrality Subset: P5 directed"""
G = nx.DiGraph()
nx.add_path(G, range(5))
b_answer = {0: 0, 1: 1, 2: 1, 3: 0, 4: 0, 5: 0}
b = nx.betweenness_centrality_subset(G, sources=[0], targets=[3], weight=None)
for n in sorted(G):
assert b[n] == pytest.approx(b_answer[n], abs=1e-7)
def test_P5(self):
"""Betweenness Centrality Subset: P5"""
G = nx.Graph()
nx.add_path(G, range(5))
b_answer = {0: 0, 1: 0.5, 2: 0.5, 3: 0, 4: 0, 5: 0}
b = nx.betweenness_centrality_subset(G, sources=[0], targets=[3], weight=None)
for n in sorted(G):
assert b[n] == pytest.approx(b_answer[n], abs=1e-7)
def test_P5_multiple_target(self):
"""Betweenness Centrality Subset: P5 multiple target"""
G = nx.Graph()
nx.add_path(G, range(5))
b_answer = {0: 0, 1: 1, 2: 1, 3: 0.5, 4: 0, 5: 0}
b = nx.betweenness_centrality_subset(
G, sources=[0], targets=[3, 4], weight=None
)
for n in sorted(G):
assert b[n] == pytest.approx(b_answer[n], abs=1e-7)
def test_box(self):
"""Betweenness Centrality Subset: box"""
G = nx.Graph()
G.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 3)])
b_answer = {0: 0, 1: 0.25, 2: 0.25, 3: 0}
b = nx.betweenness_centrality_subset(G, sources=[0], targets=[3], weight=None)
for n in sorted(G):
assert b[n] == pytest.approx(b_answer[n], abs=1e-7)
def test_box_and_path(self):
"""Betweenness Centrality Subset: box and path"""
G = nx.Graph()
G.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 3), (3, 4), (4, 5)])
b_answer = {0: 0, 1: 0.5, 2: 0.5, 3: 0.5, 4: 0, 5: 0}
b = nx.betweenness_centrality_subset(
G, sources=[0], targets=[3, 4], weight=None
)
for n in sorted(G):
assert b[n] == pytest.approx(b_answer[n], abs=1e-7)
def test_box_and_path2(self):
"""Betweenness Centrality Subset: box and path multiple target"""
G = nx.Graph()
G.add_edges_from([(0, 1), (1, 2), (2, 3), (1, 20), (20, 3), (3, 4)])
b_answer = {0: 0, 1: 1.0, 2: 0.5, 20: 0.5, 3: 0.5, 4: 0}
b = nx.betweenness_centrality_subset(
G, sources=[0], targets=[3, 4], weight=None
)
for n in sorted(G):
assert b[n] == pytest.approx(b_answer[n], abs=1e-7)
def test_diamond_multi_path(self):
"""Betweenness Centrality Subset: Diamond Multi Path"""
G = nx.Graph()
G.add_edges_from(
[
(1, 2),
(1, 3),
(1, 4),
(1, 5),
(1, 10),
(10, 11),
(11, 12),
(12, 9),
(2, 6),
(3, 6),
(4, 6),
(5, 7),
(7, 8),
(6, 8),
(8, 9),
]
)
b = nx.betweenness_centrality_subset(G, sources=[1], targets=[9], weight=None)
expected_b = {
1: 0,
2: 1.0 / 10,
3: 1.0 / 10,
4: 1.0 / 10,
5: 1.0 / 10,
6: 3.0 / 10,
7: 1.0 / 10,
8: 4.0 / 10,
9: 0,
10: 1.0 / 10,
11: 1.0 / 10,
12: 1.0 / 10,
}
for n in sorted(G):
assert b[n] == pytest.approx(expected_b[n], abs=1e-7)
def test_normalized_p2(self):
"""
Betweenness Centrality Subset: Normalized P2
if n <= 2: no normalization, betweenness centrality should be 0 for all nodes.
"""
G = nx.Graph()
nx.add_path(G, range(2))
b_answer = {0: 0, 1: 0.0}
b = nx.betweenness_centrality_subset(
G, sources=[0], targets=[1], normalized=True, weight=None
)
for n in sorted(G):
assert b[n] == pytest.approx(b_answer[n], abs=1e-7)
def test_normalized_P5_directed(self):
"""Betweenness Centrality Subset: Normalized Directed P5"""
G = nx.DiGraph()
nx.add_path(G, range(5))
b_answer = {0: 0, 1: 1.0 / 12.0, 2: 1.0 / 12.0, 3: 0, 4: 0, 5: 0}
b = nx.betweenness_centrality_subset(
G, sources=[0], targets=[3], normalized=True, weight=None
)
for n in sorted(G):
assert b[n] == pytest.approx(b_answer[n], abs=1e-7)
def test_weighted_graph(self):
"""Betweenness Centrality Subset: Weighted Graph"""
G = nx.DiGraph()
G.add_edge(0, 1, weight=3)
G.add_edge(0, 2, weight=2)
G.add_edge(0, 3, weight=6)
G.add_edge(0, 4, weight=4)
G.add_edge(1, 3, weight=5)
G.add_edge(1, 5, weight=5)
G.add_edge(2, 4, weight=1)
G.add_edge(3, 4, weight=2)
G.add_edge(3, 5, weight=1)
G.add_edge(4, 5, weight=4)
b_answer = {0: 0.0, 1: 0.0, 2: 0.5, 3: 0.5, 4: 0.5, 5: 0.0}
b = nx.betweenness_centrality_subset(
G, sources=[0], targets=[5], normalized=False, weight="weight"
)
for n in sorted(G):
assert b[n] == pytest.approx(b_answer[n], abs=1e-7)
| TestSubsetBetweennessCentrality |
python | qdrant__qdrant-client | qdrant_client/grpc/snapshots_service_pb2_grpc.py | {
"start": 6252,
"end": 10406
} | class ____(object):
"""Missing associated documentation comment in .proto file."""
@staticmethod
def Create(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None):
return grpc.experimental.unary_unary(request, target, '/qdrant.Snapshots/Create',
snapshots__service__pb2.CreateSnapshotRequest.SerializeToString,
snapshots__service__pb2.CreateSnapshotResponse.FromString,
options, channel_credentials,
insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
@staticmethod
def List(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None):
return grpc.experimental.unary_unary(request, target, '/qdrant.Snapshots/List',
snapshots__service__pb2.ListSnapshotsRequest.SerializeToString,
snapshots__service__pb2.ListSnapshotsResponse.FromString,
options, channel_credentials,
insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
@staticmethod
def Delete(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None):
return grpc.experimental.unary_unary(request, target, '/qdrant.Snapshots/Delete',
snapshots__service__pb2.DeleteSnapshotRequest.SerializeToString,
snapshots__service__pb2.DeleteSnapshotResponse.FromString,
options, channel_credentials,
insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
@staticmethod
def CreateFull(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None):
return grpc.experimental.unary_unary(request, target, '/qdrant.Snapshots/CreateFull',
snapshots__service__pb2.CreateFullSnapshotRequest.SerializeToString,
snapshots__service__pb2.CreateSnapshotResponse.FromString,
options, channel_credentials,
insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
@staticmethod
def ListFull(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None):
return grpc.experimental.unary_unary(request, target, '/qdrant.Snapshots/ListFull',
snapshots__service__pb2.ListFullSnapshotsRequest.SerializeToString,
snapshots__service__pb2.ListSnapshotsResponse.FromString,
options, channel_credentials,
insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
@staticmethod
def DeleteFull(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None):
return grpc.experimental.unary_unary(request, target, '/qdrant.Snapshots/DeleteFull',
snapshots__service__pb2.DeleteFullSnapshotRequest.SerializeToString,
snapshots__service__pb2.DeleteSnapshotResponse.FromString,
options, channel_credentials,
insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
| Snapshots |
python | astral-sh__uv | scripts/benchmark/src/benchmark/tools.py | {
"start": 4928,
"end": 10766
} | class ____(Suite):
def __init__(self, *, path: str | None = None) -> Command | None:
"""Initialize a uv benchmark."""
self.name = path or "uv"
self.path = path or os.path.join(
os.path.dirname(
os.path.dirname(
os.path.dirname(
os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
)
)
),
"target",
"release",
"uv",
)
def install_cold(self, *, cwd: str) -> Command | None:
bin_dir = os.path.join(cwd, "bin")
tool_dir = os.path.join(cwd, "tool")
cache_dir = os.path.join(cwd, ".cache")
return Command(
name=f"{self.name} ({Benchmark.INSTALL_COLD.value})",
prepare=f"rm -rf {bin_dir} && rm -rf {tool_dir} && rm -rf {cache_dir}",
command=[
f"XDG_BIN_HOME={bin_dir}",
f"UV_TOOL_DIR={tool_dir}",
self.path,
"tool",
"install",
"--cache-dir",
cache_dir,
"--",
TOOL,
],
)
def install_warm(self, *, cwd: str) -> Command | None:
bin_dir = os.path.join(cwd, "bin")
tool_dir = os.path.join(cwd, "tool")
cache_dir = os.path.join(cwd, ".cache")
return Command(
name=f"{self.name} ({Benchmark.INSTALL_WARM.value})",
prepare=f"rm -rf {bin_dir} && rm -rf {tool_dir}",
command=[
f"XDG_BIN_HOME={bin_dir}",
f"UV_TOOL_DIR={tool_dir}",
self.path,
"tool",
"install",
"--cache-dir",
cache_dir,
"--",
TOOL,
],
)
def run(self, *, cwd: str) -> Command | None:
bin_dir = os.path.join(cwd, "bin")
tool_dir = os.path.join(cwd, "tool")
cache_dir = os.path.join(cwd, ".cache")
return Command(
name=f"{self.name} ({Benchmark.RUN.value})",
prepare="",
command=[
f"XDG_BIN_HOME={bin_dir}",
f"UV_TOOL_DIR={tool_dir}",
self.path,
"tool",
"run",
"--cache-dir",
cache_dir,
"--",
TOOL,
"--version",
],
)
def main():
"""Run the benchmark."""
parser = argparse.ArgumentParser(
description="Benchmark uv against other packaging tools."
)
parser.add_argument(
"--verbose", "-v", action="store_true", help="Print verbose output."
)
parser.add_argument("--json", action="store_true", help="Export results to JSON.")
parser.add_argument(
"--warmup",
type=int,
help="The number of warmup runs to perform.",
default=3,
)
parser.add_argument(
"--min-runs",
type=int,
help="The minimum number of runs to perform.",
default=10,
)
parser.add_argument(
"--runs",
type=int,
help="The number of runs to perform.",
)
parser.add_argument(
"--benchmark",
"-b",
type=str,
help="The benchmark(s) to run.",
choices=[benchmark.value for benchmark in Benchmark],
action="append",
)
parser.add_argument(
"--pipx",
help="Whether to benchmark `pipx`.",
action="store_true",
)
parser.add_argument(
"--uv",
help="Whether to benchmark uv (assumes a uv binary exists at `./target/release/uv`).",
action="store_true",
)
parser.add_argument(
"--pipx-path",
type=str,
help="Path(s) to the `pipx` binary to benchmark.",
action="append",
)
parser.add_argument(
"--uv-path",
type=str,
help="Path(s) to the uv binary to benchmark.",
action="append",
)
args = parser.parse_args()
logging.basicConfig(
level=logging.INFO if args.verbose else logging.WARN,
format="%(asctime)s %(levelname)s %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
verbose = args.verbose
json = args.json
warmup = args.warmup
min_runs = args.min_runs
runs = args.runs
# Determine the tools to benchmark, based on the user-provided arguments.
suites = []
if args.pipx:
suites.append(Pipx())
if args.uv:
suites.append(Uv())
for path in args.pipx_path or []:
suites.append(Pipx(path=path))
for path in args.uv_path or []:
suites.append(Uv(path=path))
# If no tools were specified, benchmark all tools.
if not suites:
suites = [
Pipx(),
Uv(),
]
# Determine the benchmarks to run, based on user input.
benchmarks = (
[Benchmark(benchmark) for benchmark in args.benchmark]
if args.benchmark is not None
else list(Benchmark)
)
with tempfile.TemporaryDirectory() as cwd:
for benchmark in benchmarks:
# Generate the benchmark command for each tool.
commands = [
command
for suite in suites
if (command := suite.command(benchmark, cwd=tempfile.mkdtemp(dir=cwd)))
]
if commands:
hyperfine = Hyperfine(
name=str(benchmark.value),
commands=commands,
warmup=warmup,
min_runs=min_runs,
runs=runs,
verbose=verbose,
json=json,
)
hyperfine.run()
if __name__ == "__main__":
main()
| Uv |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-web/llama_index/readers/web/zyte_web/base.py | {
"start": 311,
"end": 5728
} | class ____(BasePydanticReader):
"""
Load text from URLs using `Zyte api`.
Args:
api_key: Zyte API key.
mode: Determines how the text is extracted for the page content.
It can take one of the following values: 'html', 'html-text', 'article'
n_conn: It is the maximum number of concurrent requests to use.
**download_kwargs: Any additional download arguments to pass for download.
See: https://docs.zyte.com/zyte-api/usage/reference.html
Example:
.. code-block:: python
from llama_index.readers.web import ZyteWebReader
reader = ZyteWebReader(
api_key="ZYTE_API_KEY",
)
docs = reader.load_data(
urls=["<url-1>", "<url-2>"],
)
Zyte-API reference:
https://www.zyte.com/zyte-api/
"""
client_async: Optional[object] = Field(None)
api_key: str
mode: str
n_conn: int
download_kwargs: Optional[dict]
continue_on_failure: bool
def __init__(
self,
api_key: str,
mode: Literal["article", "html", "html-text"] = "article",
n_conn: int = 15,
download_kwargs: Optional[Dict[str, Any]] = None,
continue_on_failure: bool = True,
) -> None:
"""Initialize with file path."""
super().__init__(
api_key=api_key,
mode=mode,
n_conn=n_conn,
download_kwargs=download_kwargs,
continue_on_failure=continue_on_failure,
)
try:
from zyte_api import AsyncZyteAPI
from zyte_api.utils import USER_AGENT as PYTHON_ZYTE_API_USER_AGENT
except ImportError:
raise ImportError(
"zyte-api package not found, please install it with "
"`pip install zyte-api`"
)
if mode not in ("article", "html", "html-text"):
raise ValueError(
f"Unrecognized mode '{mode}'. Expected one of "
f"'article', 'html', 'html-text'."
)
user_agent = f"llama-index-zyte-api/{PYTHON_ZYTE_API_USER_AGENT}"
self.client_async = AsyncZyteAPI(
api_key=api_key, user_agent=user_agent, n_conn=n_conn
)
@classmethod
def class_name(cls) -> str:
return "ZyteWebReader"
def _zyte_html_option(self) -> str:
if self.download_kwargs and "browserHtml" in self.download_kwargs:
return "browserHtml"
return "httpResponseBody"
def _get_article(self, page: Dict) -> str:
headline = page["article"].get("headline", "")
article_body = page["article"].get("articleBody", "")
return headline + "\n\n" + article_body
def _zyte_request_params(self, url: str) -> dict:
request_params: Dict[str, Any] = {"url": url}
if self.mode == "article":
request_params.update({"article": True})
if self.mode in ("html", "html-text"):
request_params.update({self._zyte_html_option(): True})
if self.download_kwargs:
request_params.update(self.download_kwargs)
return request_params
async def fetch_items(self, urls) -> List:
results = []
queries = [self._zyte_request_params(url) for url in urls]
async with self.client_async.session() as session:
for i, future in enumerate(session.iter(queries)):
try:
result = await future
results.append(result)
except Exception as e:
url = queries[i]["url"]
if self.continue_on_failure:
logger.warning(
f"Error {e} while fetching url {url}, "
f"skipping because continue_on_failure is True"
)
continue
else:
logger.exception(
f"Error fetching {url} and aborting, use "
f"continue_on_failure=True to continue loading "
f"urls after encountering an error."
)
raise
return results
def _get_content(self, response: Dict) -> str:
if self.mode == "html-text":
try:
from html2text import html2text
except ImportError:
raise ImportError(
"html2text package not found, please install it with "
"`pip install html2text`"
)
if self.mode in ("html", "html-text"):
content = response[self._zyte_html_option()]
if self._zyte_html_option() == "httpResponseBody":
content = b64decode(content).decode()
if self.mode == "html-text":
content = html2text(content)
elif self.mode == "article":
content = self._get_article(response)
return content
def load_data(self, urls) -> List[Document]:
docs = []
responses = asyncio.run(self.fetch_items(urls))
for response in responses:
content = self._get_content(response)
doc = Document(text=content, metadata={"url": response["url"]})
docs.append(doc)
return docs
| ZyteWebReader |
python | astropy__astropy | astropy/utils/masked/core.py | {
"start": 18261,
"end": 20210
} | class ____:
"""
Flat iterator object to iterate over Masked Arrays.
A `~astropy.utils.masked.MaskedIterator` iterator is returned by ``m.flat``
for any masked array ``m``. It allows iterating over the array as if it
were a 1-D array, either in a for-loop or by calling its `next` method.
Iteration is done in C-contiguous style, with the last index varying the
fastest. The iterator can also be indexed using basic slicing or
advanced indexing.
Notes
-----
The design of `~astropy.utils.masked.MaskedIterator` follows that of
`~numpy.ma.core.MaskedIterator`. It is not exported by the
`~astropy.utils.masked` module. Instead of instantiating directly,
use the ``flat`` method in the masked array instance.
"""
def __init__(self, m):
self._masked = m
self._dataiter = m.unmasked.flat
self._maskiter = m.mask.flat
def __iter__(self):
return self
def __getitem__(self, index):
out = self._dataiter.__getitem__(index)
mask = self._maskiter.__getitem__(index)
# For single elements, ndarray.flat.__getitem__ returns scalars; these
# need a new view as a Masked array.
if not isinstance(out, np.ndarray):
out = out[...]
mask = mask[...]
return self._masked.from_unmasked(out, mask, copy=False)
def __setitem__(self, index, value):
if value is np.ma.masked or value is np.ma.nomask:
mask = value is np.ma.masked
else:
unmasked, mask = get_data_and_mask(value)
self._dataiter[index] = unmasked
self._maskiter[index] = mask
def __next__(self):
"""
Return the next value, or raise StopIteration.
"""
out = next(self._dataiter)[...]
mask = next(self._maskiter)[...]
return self._masked.from_unmasked(out, mask, copy=False)
next = __next__
| MaskedIterator |
python | kamyu104__LeetCode-Solutions | Python/the-number-of-ways-to-make-the-sum.py | {
"start": 4710,
"end": 5086
} | class ____(object):
def numberOfWays(self, n):
"""
:type n: int
:rtype: int
"""
MOD = 10**9+7
dp = [0]*(n+1)
dp[0] = 1
for i in (1, 2, 6):
for j in xrange(i, n+1):
dp[j] += dp[j-i]
return reduce(lambda x, y: (x+dp[n-4*y])%MOD, (i for i in xrange(min(n//4, 2)+1)), 0)
| Solution4 |
python | getsentry__sentry | src/sentry/sentry_apps/components.py | {
"start": 744,
"end": 4146
} | class ____:
component: SentryAppComponent | RpcSentryAppComponent
install: SentryAppInstallation | RpcSentryAppInstallation
project_slug: str | None = None
values: list[Mapping[str, Any]] = dataclasses.field(default_factory=list)
def run(self) -> None:
if self.component.type == "issue-link":
self._prepare_issue_link()
elif self.component.type == "stacktrace-link":
self._prepare_stacktrace_link()
elif self.component.type == "alert-rule-action":
self._prepare_alert_rule_action()
def _prepare_stacktrace_link(self) -> None:
schema = self.component.app_schema
uri = schema.get("uri")
urlparts = list(urlparse(force_str(self.install.sentry_app.webhook_url)))
urlparts[2] = str(uri)
query = {"installationId": self.install.uuid}
if self.project_slug:
query["projectSlug"] = self.project_slug
urlparts[4] = urlencode(query)
schema.update({"url": urlunparse(urlparts)})
def _prepare_issue_link(self) -> None:
schema = dict(**self.component.app_schema)
link = schema.get("link", {})
create = schema.get("create", {})
for field in link.get("required_fields", []):
self._prepare_field(field)
for field in link.get("optional_fields", []):
self._prepare_field(field)
for field in create.get("required_fields", []):
self._prepare_field(field)
for field in create.get("optional_fields", []):
self._prepare_field(field)
def _prepare_alert_rule_action(self) -> None:
schema = dict(**self.component.app_schema)
settings = schema.get("settings", {})
for field in settings.get("required_fields", []):
self._prepare_field(field)
for field in settings.get("optional_fields", []):
self._prepare_field(field)
def _prepare_field(self, field: MutableMapping[str, Any]) -> None:
if "depends_on" in field:
dependant_data_list = list(
filter(lambda val: val["name"] in field.get("depends_on", {}), self.values)
)
if len(dependant_data_list) != len(field.get("depends_on", {})):
field.update({"choices": []})
return
dependant_data = json.dumps({x["name"]: x["value"] for x in dependant_data_list})
self._get_select_choices(field, dependant_data)
return
self._get_select_choices(field)
def _get_select_choices(
self, field: MutableMapping[str, Any], dependant_data: str | None = None
) -> None:
if "options" in field:
field.update({"choices": field["options"]})
return
if "uri" in field:
if not field.get("skip_load_on_open"):
field.update(self._request(field["uri"], dependent_data=dependant_data))
def _request(self, uri: str, dependent_data: str | None = None) -> Any:
install = self.install
if isinstance(install, SentryAppInstallation):
install = serialize_sentry_app_installation(install, install.sentry_app)
return SelectRequester(
install=install,
project_slug=self.project_slug,
uri=uri,
dependent_data=dependent_data,
).run()
| SentryAppComponentPreparer |
python | EpistasisLab__tpot | tpot/search_spaces/nodes/estimator_node_gradual.py | {
"start": 1864,
"end": 6628
} | class ____(SklearnIndividual):
"""
Note that ConfigurationSpace does not support None as a parameter. Instead, use the special string "<NONE>". TPOT will automatically replace instances of this string with the Python None.
Parameters
----------
method : type
The class of the estimator to be used
space : ConfigurationSpace|dict
The hyperparameter space to be used. If a dict is passed, hyperparameters are fixed and not learned.
"""
def __init__(self, method: type,
space: ConfigurationSpace|dict, #TODO If a dict is passed, hyperparameters are fixed and not learned. Is this confusing? Should we make a second node type?
hyperparameter_parser: callable = None,
rng=None) -> None:
super().__init__()
self.method = method
self.space = space
if hyperparameter_parser is None:
self.hyperparameter_parser = default_hyperparameter_parser
else:
self.hyperparameter_parser = hyperparameter_parser
if isinstance(space, dict):
self.hyperparameters = space
else:
rng = np.random.default_rng(rng)
self.space.seed(rng.integers(0, 2**32))
self.hyperparameters = dict(self.space.sample_configuration())
def mutate(self, rng=None):
if isinstance(self.space, dict):
return False
self.hyperparameters = gradual_hyperparameter_update(params=self.hyperparameters, configspace=self.space, rng=rng)
return True
def crossover(self, other, rng=None):
if isinstance(self.space, dict):
return False
rng = np.random.default_rng(rng)
if self.method != other.method:
return False
#loop through hyperparameters, randomly swap items in self.hyperparameters with items in other.hyperparameters
for hyperparameter in self.space:
if rng.choice([True, False]):
if hyperparameter in other.hyperparameters:
self.hyperparameters[hyperparameter] = other.hyperparameters[hyperparameter]
return True
@final #this method should not be overridden, instead override hyperparameter_parser
def export_pipeline(self, **kwargs):
return self.method(**self.hyperparameter_parser(self.hyperparameters))
def unique_id(self):
#return a dictionary of the method and the hyperparameters
method_str = self.method.__name__
params = list(self.hyperparameters.keys())
params = sorted(params)
id_str = f"{method_str}({', '.join([f'{param}={self.hyperparameters[param]}' for param in params])})"
return id_str
def gradual_hyperparameter_update(params:dict, configspace:ConfigurationSpace, rng=None):
rng = np.random.default_rng(rng)
configspace.seed(rng.integers(0, 2**32))
new_params = dict(configspace.sample_configuration())
for param in list(new_params.keys()):
#if parameter is float, multiply by normal distribution
if param not in params:
continue
try:
if issubclass(type(configspace[param]), ConfigSpace.hyperparameters.hyperparameter.FloatHyperparameter):
if configspace[param].log:
new_params[param] = params[param] * rng.lognormal(0, 1)
else:
new_params[param] = params[param] + rng.normal(0, .1)* (configspace[param].upper-configspace[param].lower)
# if check if above or below min and cap
if new_params[param] < configspace[param].lower:
new_params[param] = configspace[param].lower
elif new_params[param] > configspace[param].upper:
new_params[param] = configspace[param].upper
#if parameter is integer, add normal distribution
elif issubclass(type(configspace[param]), ConfigSpace.hyperparameters.hyperparameter.IntegerHyperparameter):
new_params[param] = params[param] * rng.normal(0, 1)
# if check if above or below min and cap
if new_params[param] < configspace[param].lower:
new_params[param] = configspace[param].lower
elif new_params[param] > configspace[param].upper:
new_params[param] = configspace[param].upper
new_params[param] = int(new_params[param])
# TODO : add support for categorical hyperparameters
else:
new_params[param] = params[param]
except:
pass
return new_params
| EstimatorNodeIndividual_gradual |
python | doocs__leetcode | solution/0000-0099/0020.Valid Parentheses/Solution.py | {
"start": 0,
"end": 284
} | class ____:
def isValid(self, s: str) -> bool:
stk = []
d = {'()', '[]', '{}'}
for c in s:
if c in '({[':
stk.append(c)
elif not stk or stk.pop() + c not in d:
return False
return not stk
| Solution |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/distributions/util_test.py | {
"start": 22716,
"end": 24318
} | class ____(test.TestCase):
@test_util.run_deprecated_v1
def testNonEmptyConstantTensor(self):
x = array_ops.zeros((2, 3, 4))
value = du.prefer_static_value(x)
self.assertIsInstance(value, np.ndarray)
self.assertAllEqual(np.zeros((2, 3, 4)), value)
@test_util.run_deprecated_v1
def testEmptyConstantTensor(self):
x = constant_op.constant([])
value = du.prefer_static_value(x)
self.assertIsInstance(value, np.ndarray)
self.assertAllEqual(np.array([]), value)
@test_util.run_deprecated_v1
def testScalarTensor(self):
x = constant_op.constant(1.)
value = du.prefer_static_value(x)
self.assertIsInstance(value, np.ndarray)
self.assertAllEqual(np.array(1.), value)
@test_util.run_deprecated_v1
def testDynamicValueEndsUpBeingNonEmpty(self):
x = array_ops.placeholder(np.float64, shape=None)
value = du.prefer_static_value(x)
with self.cached_session():
self.assertAllEqual(np.zeros((2, 3)),
value.eval(feed_dict={x: np.zeros((2, 3))}))
@test_util.run_deprecated_v1
def testDynamicValueEndsUpBeingEmpty(self):
x = array_ops.placeholder(np.int32, shape=None)
value = du.prefer_static_value(x)
with self.cached_session():
self.assertAllEqual(np.array([]), value.eval(feed_dict={x: []}))
@test_util.run_deprecated_v1
def testDynamicValueEndsUpBeingScalar(self):
x = array_ops.placeholder(np.int32, shape=None)
value = du.prefer_static_value(x)
with self.cached_session():
self.assertAllEqual(np.array(1), value.eval(feed_dict={x: 1}))
| PreferStaticValueTest |
python | nedbat__coveragepy | tests/test_oddball.py | {
"start": 18174,
"end": 22186
} | class ____(CoverageTest):
"""Tests that we work properly with `sys.gettrace()`."""
def test_round_trip_in_untraced_function(self) -> None:
# https://github.com/coveragepy/coveragepy/issues/575
self.make_file("main.py", """import sample""")
self.make_file(
"sample.py",
"""\
from swap import swap_it
def doit():
print(3)
swap_it()
print(5)
def doit_soon():
print(7)
doit()
print(9)
print(10)
doit_soon()
print(12)
""",
)
self.make_file(
"swap.py",
"""\
import sys
def swap_it():
sys.settrace(sys.gettrace())
""",
)
# Use --source=sample to prevent measurement of swap.py.
cov = coverage.Coverage(source=["sample"])
self.start_import_stop(cov, "main")
assert self.stdout() == "10\n7\n3\n5\n9\n12\n"
_, statements, missing, _ = cov.analysis("sample.py")
assert statements == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
assert missing == []
def test_setting_new_trace_function(self) -> None:
# https://github.com/coveragepy/coveragepy/issues/436
if testenv.SETTRACE_CORE or not env.PYBEHAVIOR.branch_right_left:
missing = "5-7, 13-14"
else:
missing = "5-7"
self.check_coverage(
"""\
import os.path
import sys
def tracer(frame, event, arg):
filename = os.path.basename(frame.f_code.co_filename) # 5
print(f"{event}: {filename} @ {frame.f_lineno}") # 6
return tracer # 7
def begin():
sys.settrace(tracer)
def collect():
t = sys.gettrace() # 13
assert t is tracer, t # 14
def test_unsets_trace() -> None:
begin()
collect()
old = sys.gettrace()
test_unsets_trace()
sys.settrace(old)
a = 21
b = 22
""",
lines=[1, 2, 4, 5, 6, 7, 9, 10, 12, 13, 14, 16, 17, 18, 20, 21, 22, 23, 24],
missing=missing,
)
assert self.last_module_name is not None
out = self.stdout().replace(self.last_module_name, "coverage_test")
expected = (
"call: coverage_test.py @ 12\n"
+ "line: coverage_test.py @ 13\n"
+ "line: coverage_test.py @ 14\n"
+ "return: coverage_test.py @ 14\n"
)
assert expected == out
@pytest.mark.skipif(env.METACOV, reason="Can't set trace functions during meta-coverage")
def test_atexit_gettrace(self) -> None:
# This is not a test of coverage at all, but of our understanding
# of this edge-case behavior in various Pythons.
self.make_file(
"atexit_gettrace.py",
"""\
import atexit, sys
def trace_function(frame, event, arg):
return trace_function
sys.settrace(trace_function)
def show_trace_function():
tfn = sys.gettrace()
if tfn is not None:
tfn = tfn.__name__
print(tfn)
atexit.register(show_trace_function)
# This will show what the trace function is at the end of the program.
""",
)
status, out = self.run_command_status("python atexit_gettrace.py")
assert status == 0
if env.PYPY:
# PyPy clears the trace function before atexit runs.
assert out == "None\n"
else:
# Other Pythons leave the trace function in place.
assert out == "trace_function\n"
| GettraceTest |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/ruff/RUF049.py | {
"start": 272,
"end": 326
} | class ____(IntFlag): ...
@dataclass(
frozen=True
)
| E |
python | xlwings__xlwings | xlwings/constants.py | {
"start": 53686,
"end": 54169
} | class ____:
xlHundredMillions = -8 # from enum XlDisplayUnit
xlHundredThousands = -5 # from enum XlDisplayUnit
xlHundreds = -2 # from enum XlDisplayUnit
xlMillionMillions = -10 # from enum XlDisplayUnit
xlMillions = -6 # from enum XlDisplayUnit
xlTenMillions = -7 # from enum XlDisplayUnit
xlTenThousands = -4 # from enum XlDisplayUnit
xlThousandMillions = -9 # from enum XlDisplayUnit
xlThousands = -3 # from enum XlDisplayUnit
| DisplayUnit |
python | scikit-learn__scikit-learn | sklearn/ensemble/_hist_gradient_boosting/gradient_boosting.py | {
"start": 58912,
"end": 76018
} | class ____(RegressorMixin, BaseHistGradientBoosting):
"""Histogram-based Gradient Boosting Regression Tree.
This estimator is much faster than
:class:`GradientBoostingRegressor<sklearn.ensemble.GradientBoostingRegressor>`
for big datasets (n_samples >= 10 000).
This estimator has native support for missing values (NaNs). During
training, the tree grower learns at each split point whether samples
with missing values should go to the left or right child, based on the
potential gain. When predicting, samples with missing values are
assigned to the left or right child consequently. If no missing values
were encountered for a given feature during training, then samples with
missing values are mapped to whichever child has the most samples.
See :ref:`sphx_glr_auto_examples_ensemble_plot_hgbt_regression.py` for a
usecase example of this feature.
This implementation is inspired by
`LightGBM <https://github.com/Microsoft/LightGBM>`_.
Read more in the :ref:`User Guide <histogram_based_gradient_boosting>`.
.. versionadded:: 0.21
Parameters
----------
loss : {'squared_error', 'absolute_error', 'gamma', 'poisson', 'quantile'}, \
default='squared_error'
The loss function to use in the boosting process. Note that the
"squared error", "gamma" and "poisson" losses actually implement
"half least squares loss", "half gamma deviance" and "half poisson
deviance" to simplify the computation of the gradient. Furthermore,
"gamma" and "poisson" losses internally use a log-link, "gamma"
requires ``y > 0`` and "poisson" requires ``y >= 0``.
"quantile" uses the pinball loss.
.. versionchanged:: 0.23
Added option 'poisson'.
.. versionchanged:: 1.1
Added option 'quantile'.
.. versionchanged:: 1.3
Added option 'gamma'.
quantile : float, default=None
If loss is "quantile", this parameter specifies which quantile to be estimated
and must be between 0 and 1.
learning_rate : float, default=0.1
The learning rate, also known as *shrinkage*. This is used as a
multiplicative factor for the leaves values. Use ``1`` for no
shrinkage.
max_iter : int, default=100
The maximum number of iterations of the boosting process, i.e. the
maximum number of trees.
max_leaf_nodes : int or None, default=31
The maximum number of leaves for each tree. Must be strictly greater
than 1. If None, there is no maximum limit.
max_depth : int or None, default=None
The maximum depth of each tree. The depth of a tree is the number of
edges to go from the root to the deepest leaf.
Depth isn't constrained by default.
min_samples_leaf : int, default=20
The minimum number of samples per leaf. For small datasets with less
than a few hundred samples, it is recommended to lower this value
since only very shallow trees would be built.
l2_regularization : float, default=0
The L2 regularization parameter penalizing leaves with small hessians.
Use ``0`` for no regularization (default).
max_features : float, default=1.0
Proportion of randomly chosen features in each and every node split.
This is a form of regularization, smaller values make the trees weaker
learners and might prevent overfitting.
If interaction constraints from `interaction_cst` are present, only allowed
features are taken into account for the subsampling.
.. versionadded:: 1.4
max_bins : int, default=255
The maximum number of bins to use for non-missing values. Before
training, each feature of the input array `X` is binned into
integer-valued bins, which allows for a much faster training stage.
Features with a small number of unique values may use less than
``max_bins`` bins. In addition to the ``max_bins`` bins, one more bin
is always reserved for missing values. Must be no larger than 255.
categorical_features : array-like of {bool, int, str} of shape (n_features) \
or shape (n_categorical_features,), default='from_dtype'
Indicates the categorical features.
- None : no feature will be considered categorical.
- boolean array-like : boolean mask indicating categorical features.
- integer array-like : integer indices indicating categorical
features.
- str array-like: names of categorical features (assuming the training
data has feature names).
- `"from_dtype"`: dataframe columns with dtype "category" are
considered to be categorical features. The input must be an object
exposing a ``__dataframe__`` method such as pandas or polars
DataFrames to use this feature.
For each categorical feature, there must be at most `max_bins` unique
categories. Negative values for categorical features encoded as numeric
dtypes are treated as missing values. All categorical values are
converted to floating point numbers. This means that categorical values
of 1.0 and 1 are treated as the same category.
Read more in the :ref:`User Guide <categorical_support_gbdt>` and
:ref:`sphx_glr_auto_examples_ensemble_plot_gradient_boosting_categorical.py`.
.. versionadded:: 0.24
.. versionchanged:: 1.2
Added support for feature names.
.. versionchanged:: 1.4
Added `"from_dtype"` option.
.. versionchanged:: 1.6
The default value changed from `None` to `"from_dtype"`.
monotonic_cst : array-like of int of shape (n_features) or dict, default=None
Monotonic constraint to enforce on each feature are specified using the
following integer values:
- 1: monotonic increase
- 0: no constraint
- -1: monotonic decrease
If a dict with str keys, map feature to monotonic constraints by name.
If an array, the features are mapped to constraints by position. See
:ref:`monotonic_cst_features_names` for a usage example.
Read more in the :ref:`User Guide <monotonic_cst_gbdt>`.
.. versionadded:: 0.23
.. versionchanged:: 1.2
Accept dict of constraints with feature names as keys.
interaction_cst : {"pairwise", "no_interactions"} or sequence of lists/tuples/sets \
of int, default=None
Specify interaction constraints, the sets of features which can
interact with each other in child node splits.
Each item specifies the set of feature indices that are allowed
to interact with each other. If there are more features than
specified in these constraints, they are treated as if they were
specified as an additional set.
The strings "pairwise" and "no_interactions" are shorthands for
allowing only pairwise or no interactions, respectively.
For instance, with 5 features in total, `interaction_cst=[{0, 1}]`
is equivalent to `interaction_cst=[{0, 1}, {2, 3, 4}]`,
and specifies that each branch of a tree will either only split
on features 0 and 1 or only split on features 2, 3 and 4.
See :ref:`this example<ice-vs-pdp>` on how to use `interaction_cst`.
.. versionadded:: 1.2
warm_start : bool, default=False
When set to ``True``, reuse the solution of the previous call to fit
and add more estimators to the ensemble. For results to be valid, the
estimator should be re-trained on the same data only.
See :term:`the Glossary <warm_start>`.
early_stopping : 'auto' or bool, default='auto'
If 'auto', early stopping is enabled if the sample size is larger than
10000 or if `X_val` and `y_val` are passed to `fit`. If True, early stopping
is enabled, otherwise early stopping is disabled.
.. versionadded:: 0.23
scoring : str or callable or None, default='loss'
Scoring method to use for early stopping. Only used if `early_stopping`
is enabled. Options:
- str: see :ref:`scoring_string_names` for options.
- callable: a scorer callable object (e.g., function) with signature
``scorer(estimator, X, y)``. See :ref:`scoring_callable` for details.
- `None`: the :ref:`coefficient of determination <r2_score>`
(:math:`R^2`) is used.
- 'loss': early stopping is checked w.r.t the loss value.
validation_fraction : int or float or None, default=0.1
Proportion (or absolute size) of training data to set aside as
validation data for early stopping. If None, early stopping is done on
the training data.
The value is ignored if either early stopping is not performed, e.g.
`early_stopping=False`, or if `X_val` and `y_val` are passed to fit.
n_iter_no_change : int, default=10
Used to determine when to "early stop". The fitting process is
stopped when none of the last ``n_iter_no_change`` scores are better
than the ``n_iter_no_change - 1`` -th-to-last one, up to some
tolerance. Only used if early stopping is performed.
tol : float, default=1e-7
The absolute tolerance to use when comparing scores during early
stopping. The higher the tolerance, the more likely we are to early
stop: higher tolerance means that it will be harder for subsequent
iterations to be considered an improvement upon the reference score.
verbose : int, default=0
The verbosity level. If not zero, print some information about the
fitting process. ``1`` prints only summary info, ``2`` prints info per
iteration.
random_state : int, RandomState instance or None, default=None
Pseudo-random number generator to control the subsampling in the
binning process, and the train/validation data split if early stopping
is enabled.
Pass an int for reproducible output across multiple function calls.
See :term:`Glossary <random_state>`.
Attributes
----------
do_early_stopping_ : bool
Indicates whether early stopping is used during training.
n_iter_ : int
The number of iterations as selected by early stopping, depending on
the `early_stopping` parameter. Otherwise it corresponds to max_iter.
n_trees_per_iteration_ : int
The number of tree that are built at each iteration. For regressors,
this is always 1.
train_score_ : ndarray, shape (n_iter_+1,)
The scores at each iteration on the training data. The first entry
is the score of the ensemble before the first iteration. Scores are
computed according to the ``scoring`` parameter. If ``scoring`` is
not 'loss', scores are computed on a subset of at most 10 000
samples. Empty if no early stopping.
validation_score_ : ndarray, shape (n_iter_+1,)
The scores at each iteration on the held-out validation data. The
first entry is the score of the ensemble before the first iteration.
Scores are computed according to the ``scoring`` parameter. Empty if
no early stopping or if ``validation_fraction`` is None.
is_categorical_ : ndarray, shape (n_features, ) or None
Boolean mask for the categorical features. ``None`` if there are no
categorical features.
n_features_in_ : int
Number of features seen during :term:`fit`.
.. versionadded:: 0.24
feature_names_in_ : ndarray of shape (`n_features_in_`,)
Names of features seen during :term:`fit`. Defined only when `X`
has feature names that are all strings.
.. versionadded:: 1.0
See Also
--------
GradientBoostingRegressor : Exact gradient boosting method that does not
scale as good on datasets with a large number of samples.
sklearn.tree.DecisionTreeRegressor : A decision tree regressor.
RandomForestRegressor : A meta-estimator that fits a number of decision
tree regressors on various sub-samples of the dataset and uses
averaging to improve the statistical performance and control
over-fitting.
AdaBoostRegressor : A meta-estimator that begins by fitting a regressor
on the original dataset and then fits additional copies of the
regressor on the same dataset but where the weights of instances are
adjusted according to the error of the current prediction. As such,
subsequent regressors focus more on difficult cases.
Examples
--------
>>> from sklearn.ensemble import HistGradientBoostingRegressor
>>> from sklearn.datasets import load_diabetes
>>> X, y = load_diabetes(return_X_y=True)
>>> est = HistGradientBoostingRegressor().fit(X, y)
>>> est.score(X, y)
0.92...
"""
_parameter_constraints: dict = {
**BaseHistGradientBoosting._parameter_constraints,
"loss": [
StrOptions(
{
"squared_error",
"absolute_error",
"poisson",
"gamma",
"quantile",
}
),
BaseLoss,
],
"quantile": [Interval(Real, 0, 1, closed="both"), None],
}
def __init__(
self,
loss="squared_error",
*,
quantile=None,
learning_rate=0.1,
max_iter=100,
max_leaf_nodes=31,
max_depth=None,
min_samples_leaf=20,
l2_regularization=0.0,
max_features=1.0,
max_bins=255,
categorical_features="from_dtype",
monotonic_cst=None,
interaction_cst=None,
warm_start=False,
early_stopping="auto",
scoring="loss",
validation_fraction=0.1,
n_iter_no_change=10,
tol=1e-7,
verbose=0,
random_state=None,
):
super().__init__(
loss=loss,
learning_rate=learning_rate,
max_iter=max_iter,
max_leaf_nodes=max_leaf_nodes,
max_depth=max_depth,
min_samples_leaf=min_samples_leaf,
l2_regularization=l2_regularization,
max_features=max_features,
max_bins=max_bins,
monotonic_cst=monotonic_cst,
interaction_cst=interaction_cst,
categorical_features=categorical_features,
early_stopping=early_stopping,
warm_start=warm_start,
scoring=scoring,
validation_fraction=validation_fraction,
n_iter_no_change=n_iter_no_change,
tol=tol,
verbose=verbose,
random_state=random_state,
)
self.quantile = quantile
def predict(self, X):
"""Predict values for X.
Parameters
----------
X : array-like, shape (n_samples, n_features)
The input samples.
Returns
-------
y : ndarray, shape (n_samples,)
The predicted values.
"""
check_is_fitted(self)
# Return inverse link of raw predictions after converting
# shape (n_samples, 1) to (n_samples,)
return self._loss.link.inverse(self._raw_predict(X).ravel())
def staged_predict(self, X):
"""Predict regression target for each iteration.
This method allows monitoring (i.e. determine error on testing set)
after each stage.
.. versionadded:: 0.24
Parameters
----------
X : array-like of shape (n_samples, n_features)
The input samples.
Yields
------
y : generator of ndarray of shape (n_samples,)
The predicted values of the input samples, for each iteration.
"""
for raw_predictions in self._staged_raw_predict(X):
yield self._loss.link.inverse(raw_predictions.ravel())
def _encode_y(self, y):
# Just convert y to the expected dtype
self.n_trees_per_iteration_ = 1
y = y.astype(Y_DTYPE, copy=False)
if self.loss == "gamma":
# Ensure y > 0
if not np.all(y > 0):
raise ValueError("loss='gamma' requires strictly positive y.")
elif self.loss == "poisson":
# Ensure y >= 0 and sum(y) > 0
if not (np.all(y >= 0) and np.sum(y) > 0):
raise ValueError(
"loss='poisson' requires non-negative y and sum(y) > 0."
)
return y
def _encode_y_val(self, y=None):
return self._encode_y(y)
def _get_loss(self, sample_weight):
if self.loss == "quantile":
return _LOSSES[self.loss](
sample_weight=sample_weight, quantile=self.quantile
)
else:
return _LOSSES[self.loss](sample_weight=sample_weight)
| HistGradientBoostingRegressor |
python | huggingface__transformers | src/transformers/models/mobilebert/modeling_mobilebert.py | {
"start": 22487,
"end": 23353
} | class ____(PreTrainedModel):
config: MobileBertConfig
base_model_prefix = "mobilebert"
supports_gradient_checkpointing = True
_supports_flash_attn = True
_supports_sdpa = True
_supports_flex_attn = True
_supports_attention_backend = True
_can_record_outputs = {
"hidden_states": MobileBertLayer,
"attentions": MobileBertSelfAttention,
}
@torch.no_grad()
def _init_weights(self, module):
"""Initialize the weights"""
super()._init_weights(module)
if isinstance(module, NoNorm):
init.zeros_(module.bias)
init.ones_(module.weight)
elif isinstance(module, MobileBertLMPredictionHead):
init.zeros_(module.bias)
@dataclass
@auto_docstring(
custom_intro="""
Output type of [`MobileBertForPreTraining`].
"""
)
| MobileBertPreTrainedModel |
python | django__django | django/db/transaction.py | {
"start": 176,
"end": 3959
} | class ____(ProgrammingError):
"""Transaction management is used improperly."""
pass
def get_connection(using=None):
"""
Get a database connection by name, or the default database connection
if no name is provided. This is a private API.
"""
if using is None:
using = DEFAULT_DB_ALIAS
return connections[using]
def get_autocommit(using=None):
"""Get the autocommit status of the connection."""
return get_connection(using).get_autocommit()
def set_autocommit(autocommit, using=None):
"""Set the autocommit status of the connection."""
return get_connection(using).set_autocommit(autocommit)
def commit(using=None):
"""Commit a transaction."""
get_connection(using).commit()
def rollback(using=None):
"""Roll back a transaction."""
get_connection(using).rollback()
def savepoint(using=None):
"""
Create a savepoint (if supported and required by the backend) inside the
current transaction. Return an identifier for the savepoint that will be
used for the subsequent rollback or commit.
"""
return get_connection(using).savepoint()
def savepoint_rollback(sid, using=None):
"""
Roll back the most recent savepoint (if one exists). Do nothing if
savepoints are not supported.
"""
get_connection(using).savepoint_rollback(sid)
def savepoint_commit(sid, using=None):
"""
Commit the most recent savepoint (if one exists). Do nothing if
savepoints are not supported.
"""
get_connection(using).savepoint_commit(sid)
def clean_savepoints(using=None):
"""
Reset the counter used to generate unique savepoint ids in this thread.
"""
get_connection(using).clean_savepoints()
def get_rollback(using=None):
"""Get the "needs rollback" flag -- for *advanced use* only."""
return get_connection(using).get_rollback()
def set_rollback(rollback, using=None):
"""
Set or unset the "needs rollback" flag -- for *advanced use* only.
When `rollback` is `True`, trigger a rollback when exiting the innermost
enclosing atomic block that has `savepoint=True` (that's the default). Use
this to force a rollback without raising an exception.
When `rollback` is `False`, prevent such a rollback. Use this only after
rolling back to a known-good state! Otherwise, you break the atomic block
and data corruption may occur.
"""
return get_connection(using).set_rollback(rollback)
@contextmanager
def mark_for_rollback_on_error(using=None):
"""
Internal low-level utility to mark a transaction as "needs rollback" when
an exception is raised while not enforcing the enclosed block to be in a
transaction. This is needed by Model.save() and friends to avoid starting a
transaction when in autocommit mode and a single query is executed.
It's equivalent to:
connection = get_connection(using)
if connection.get_autocommit():
yield
else:
with transaction.atomic(using=using, savepoint=False):
yield
but it uses low-level utilities to avoid performance overhead.
"""
try:
yield
except Exception as exc:
connection = get_connection(using)
if connection.in_atomic_block:
connection.needs_rollback = True
connection.rollback_exc = exc
raise
def on_commit(func, using=None, robust=False):
"""
Register `func` to be called when the current transaction is committed.
If the current transaction is rolled back, `func` will not be called.
"""
get_connection(using).on_commit(func, robust)
#################################
# Decorators / context managers #
#################################
| TransactionManagementError |
python | pytorch__pytorch | test/dynamo/cpython/3_13/test_collections.py | {
"start": 84735,
"end": 99317
} | class ____(__TestCase):
def test_basics(self):
c = Counter('abcaba')
self.assertEqual(c, Counter({'a':3 , 'b': 2, 'c': 1}))
self.assertEqual(c, Counter(a=3, b=2, c=1))
self.assertIsInstance(c, dict)
self.assertIsInstance(c, Mapping)
self.assertTrue(issubclass(Counter, dict))
self.assertTrue(issubclass(Counter, Mapping))
self.assertEqual(len(c), 3)
self.assertEqual(sum(c.values()), 6)
self.assertEqual(list(c.values()), [3, 2, 1])
self.assertEqual(list(c.keys()), ['a', 'b', 'c'])
self.assertEqual(list(c), ['a', 'b', 'c'])
self.assertEqual(list(c.items()),
[('a', 3), ('b', 2), ('c', 1)])
self.assertEqual(c['b'], 2)
self.assertEqual(c['z'], 0)
self.assertEqual(c.__contains__('c'), True)
self.assertEqual(c.__contains__('z'), False)
self.assertEqual(c.get('b', 10), 2)
self.assertEqual(c.get('z', 10), 10)
self.assertEqual(c, dict(a=3, b=2, c=1))
self.assertEqual(repr(c), "Counter({'a': 3, 'b': 2, 'c': 1})")
self.assertEqual(c.most_common(), [('a', 3), ('b', 2), ('c', 1)])
for i in range(5):
self.assertEqual(c.most_common(i),
[('a', 3), ('b', 2), ('c', 1)][:i])
self.assertEqual(''.join(c.elements()), 'aaabbc')
c['a'] += 1 # increment an existing value
c['b'] -= 2 # sub existing value to zero
del c['c'] # remove an entry
del c['c'] # make sure that del doesn't raise KeyError
c['d'] -= 2 # sub from a missing value
c['e'] = -5 # directly assign a missing value
c['f'] += 4 # add to a missing value
self.assertEqual(c, dict(a=4, b=0, d=-2, e=-5, f=4))
self.assertEqual(''.join(c.elements()), 'aaaaffff')
self.assertEqual(c.pop('f'), 4)
self.assertNotIn('f', c)
for i in range(3):
elem, cnt = c.popitem()
self.assertNotIn(elem, c)
c.clear()
self.assertEqual(c, {})
self.assertEqual(repr(c), 'Counter()')
self.assertRaises(NotImplementedError, Counter.fromkeys, 'abc')
self.assertRaises(TypeError, hash, c)
c.update(dict(a=5, b=3))
c.update(c=1)
c.update(Counter('a' * 50 + 'b' * 30))
c.update() # test case with no args
c.__init__('a' * 500 + 'b' * 300)
c.__init__('cdc')
c.__init__()
self.assertEqual(c, dict(a=555, b=333, c=3, d=1))
self.assertEqual(c.setdefault('d', 5), 1)
self.assertEqual(c['d'], 1)
self.assertEqual(c.setdefault('e', 5), 5)
self.assertEqual(c['e'], 5)
def test_init(self):
self.assertEqual(list(Counter(self=42).items()), [('self', 42)])
self.assertEqual(list(Counter(iterable=42).items()), [('iterable', 42)])
self.assertEqual(list(Counter(iterable=None).items()), [('iterable', None)])
self.assertRaises(TypeError, Counter, 42)
self.assertRaises(TypeError, Counter, (), ())
self.assertRaises(TypeError, Counter.__init__)
def test_total(self):
c = Counter(a=10, b=5, c=0)
self.assertEqual(c.total(), 15)
def test_order_preservation(self):
# Input order dictates items() order
self.assertEqual(list(Counter('abracadabra').items()),
[('a', 5), ('b', 2), ('r', 2), ('c', 1), ('d', 1)])
# letters with same count: ^----------^ ^---------^
# Verify retention of order even when all counts are equal
self.assertEqual(list(Counter('xyzpdqqdpzyx').items()),
[('x', 2), ('y', 2), ('z', 2), ('p', 2), ('d', 2), ('q', 2)])
# Input order dictates elements() order
self.assertEqual(list(Counter('abracadabra simsalabim').elements()),
['a', 'a', 'a', 'a', 'a', 'a', 'a', 'b', 'b', 'b','r',
'r', 'c', 'd', ' ', 's', 's', 'i', 'i', 'm', 'm', 'l'])
# Math operations order first by the order encountered in the left
# operand and then by the order encountered in the right operand.
ps = 'aaabbcdddeefggghhijjjkkl'
qs = 'abbcccdeefffhkkllllmmnno'
order = {letter: i for i, letter in enumerate(dict.fromkeys(ps + qs))}
def correctly_ordered(seq):
'Return true if the letters occur in the expected order'
positions = [order[letter] for letter in seq]
return positions == sorted(positions)
p, q = Counter(ps), Counter(qs)
self.assertTrue(correctly_ordered(+p))
self.assertTrue(correctly_ordered(-p))
self.assertTrue(correctly_ordered(p + q))
self.assertTrue(correctly_ordered(p - q))
self.assertTrue(correctly_ordered(p | q))
self.assertTrue(correctly_ordered(p & q))
p, q = Counter(ps), Counter(qs)
p += q
self.assertTrue(correctly_ordered(p))
p, q = Counter(ps), Counter(qs)
p -= q
self.assertTrue(correctly_ordered(p))
p, q = Counter(ps), Counter(qs)
p |= q
self.assertTrue(correctly_ordered(p))
p, q = Counter(ps), Counter(qs)
p &= q
self.assertTrue(correctly_ordered(p))
p, q = Counter(ps), Counter(qs)
p.update(q)
self.assertTrue(correctly_ordered(p))
p, q = Counter(ps), Counter(qs)
p.subtract(q)
self.assertTrue(correctly_ordered(p))
def test_update(self):
c = Counter()
c.update(self=42)
self.assertEqual(list(c.items()), [('self', 42)])
c = Counter()
c.update(iterable=42)
self.assertEqual(list(c.items()), [('iterable', 42)])
c = Counter()
c.update(iterable=None)
self.assertEqual(list(c.items()), [('iterable', None)])
self.assertRaises(TypeError, Counter().update, 42)
self.assertRaises(TypeError, Counter().update, {}, {})
self.assertRaises(TypeError, Counter.update)
def test_copying(self):
# Check that counters are copyable, deepcopyable, picklable, and
#have a repr/eval round-trip
words = Counter('which witch had which witches wrist watch'.split())
def check(dup):
msg = "\ncopy: %s\nwords: %s" % (dup, words)
self.assertIsNot(dup, words, msg)
self.assertEqual(dup, words)
check(words.copy())
check(copy.copy(words))
check(copy.deepcopy(words))
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
with self.subTest(proto=proto):
check(pickle.loads(pickle.dumps(words, proto)))
check(eval(repr(words)))
update_test = Counter()
update_test.update(words)
check(update_test)
check(Counter(words))
def test_copy_subclass(self):
with torch._dynamo.error_on_graph_break(False):
class MyCounter(Counter):
pass
c = MyCounter('slartibartfast')
d = c.copy()
self.assertEqual(d, c)
self.assertEqual(len(d), len(c))
self.assertEqual(type(d), type(c))
def test_conversions(self):
# Convert to: set, list, dict
s = 'she sells sea shells by the sea shore'
self.assertEqual(sorted(Counter(s).elements()), sorted(s))
self.assertEqual(sorted(Counter(s)), sorted(set(s)))
self.assertEqual(dict(Counter(s)), dict(Counter(s).items()))
self.assertEqual(set(Counter(s)), set(s))
def test_invariant_for_the_in_operator(self):
c = Counter(a=10, b=-2, c=0)
for elem in c:
self.assertTrue(elem in c)
self.assertIn(elem, c)
def test_multiset_operations(self):
# Verify that adding a zero counter will strip zeros and negatives
c = Counter(a=10, b=-2, c=0) + Counter()
self.assertEqual(dict(c), dict(a=10))
elements = 'abcd'
for i in range(1000):
# test random pairs of multisets
p = Counter(dict((elem, randrange(-2,4)) for elem in elements))
p.update(e=1, f=-1, g=0)
q = Counter(dict((elem, randrange(-2,4)) for elem in elements))
q.update(h=1, i=-1, j=0)
for counterop, numberop in [
(Counter.__add__, lambda x, y: max(0, x+y)),
(Counter.__sub__, lambda x, y: max(0, x-y)),
(Counter.__or__, lambda x, y: max(0,x,y)),
(Counter.__and__, lambda x, y: max(0, min(x,y))),
]:
result = counterop(p, q)
for x in elements:
self.assertEqual(numberop(p[x], q[x]), result[x],
(counterop, x, p, q))
# verify that results exclude non-positive counts
self.assertTrue(x>0 for x in result.values())
elements = 'abcdef'
for i in range(100):
# verify that random multisets with no repeats are exactly like sets
p = Counter(dict((elem, randrange(0, 2)) for elem in elements))
q = Counter(dict((elem, randrange(0, 2)) for elem in elements))
for counterop, setop in [
(Counter.__sub__, set.__sub__),
(Counter.__or__, set.__or__),
(Counter.__and__, set.__and__),
]:
counter_result = counterop(p, q)
set_result = setop(set(p.elements()), set(q.elements()))
self.assertEqual(counter_result, dict.fromkeys(set_result, 1))
def test_inplace_operations(self):
elements = 'abcd'
for i in range(1000):
# test random pairs of multisets
p = Counter(dict((elem, randrange(-2,4)) for elem in elements))
p.update(e=1, f=-1, g=0)
q = Counter(dict((elem, randrange(-2,4)) for elem in elements))
q.update(h=1, i=-1, j=0)
for inplace_op, regular_op in [
(Counter.__iadd__, Counter.__add__),
(Counter.__isub__, Counter.__sub__),
(Counter.__ior__, Counter.__or__),
(Counter.__iand__, Counter.__and__),
]:
c = p.copy()
c_id = id(c)
regular_result = regular_op(c, q)
inplace_result = inplace_op(c, q)
self.assertEqual(inplace_result, regular_result)
self.assertEqual(id(inplace_result), c_id)
def test_subtract(self):
c = Counter(a=-5, b=0, c=5, d=10, e=15,g=40)
c.subtract(a=1, b=2, c=-3, d=10, e=20, f=30, h=-50)
self.assertEqual(c, Counter(a=-6, b=-2, c=8, d=0, e=-5, f=-30, g=40, h=50))
c = Counter(a=-5, b=0, c=5, d=10, e=15,g=40)
c.subtract(Counter(a=1, b=2, c=-3, d=10, e=20, f=30, h=-50))
self.assertEqual(c, Counter(a=-6, b=-2, c=8, d=0, e=-5, f=-30, g=40, h=50))
c = Counter('aaabbcd')
c.subtract('aaaabbcce')
self.assertEqual(c, Counter(a=-1, b=0, c=-1, d=1, e=-1))
c = Counter()
c.subtract(self=42)
self.assertEqual(list(c.items()), [('self', -42)])
c = Counter()
c.subtract(iterable=42)
self.assertEqual(list(c.items()), [('iterable', -42)])
self.assertRaises(TypeError, Counter().subtract, 42)
self.assertRaises(TypeError, Counter().subtract, {}, {})
self.assertRaises(TypeError, Counter.subtract)
def test_unary(self):
c = Counter(a=-5, b=0, c=5, d=10, e=15,g=40)
self.assertEqual(dict(+c), dict(c=5, d=10, e=15, g=40))
self.assertEqual(dict(-c), dict(a=5))
def test_repr_nonsortable(self):
c = Counter(a=2, b=None)
r = repr(c)
self.assertIn("'a': 2", r)
self.assertIn("'b': None", r)
def test_helper_function(self):
# two paths, one for real dicts and one for other mappings
elems = list('abracadabra')
d = dict()
_count_elements(d, elems)
self.assertEqual(d, {'a': 5, 'r': 2, 'b': 2, 'c': 1, 'd': 1})
m = OrderedDict()
_count_elements(m, elems)
self.assertEqual(m,
OrderedDict([('a', 5), ('b', 2), ('r', 2), ('c', 1), ('d', 1)]))
# test fidelity to the pure python version
c = CounterSubclassWithSetItem('abracadabra')
self.assertTrue(c.called)
self.assertEqual(dict(c), {'a': 5, 'b': 2, 'c': 1, 'd': 1, 'r':2 })
c = CounterSubclassWithGet('abracadabra')
self.assertTrue(c.called)
self.assertEqual(dict(c), {'a': 5, 'b': 2, 'c': 1, 'd': 1, 'r':2 })
def test_multiset_operations_equivalent_to_set_operations(self):
# When the multiplicities are all zero or one, multiset operations
# are guaranteed to be equivalent to the corresponding operations
# for regular sets.
s = list(product(('a', 'b', 'c'), range(2)))
powerset = chain.from_iterable(combinations(s, r) for r in range(len(s)+1))
counters = [Counter(dict(groups)) for groups in powerset]
for cp, cq in product(counters, repeat=2):
sp = set(cp.elements())
sq = set(cq.elements())
self.assertEqual(set(cp + cq), sp | sq)
self.assertEqual(set(cp - cq), sp - sq)
self.assertEqual(set(cp | cq), sp | sq)
self.assertEqual(set(cp & cq), sp & sq)
self.assertEqual(cp == cq, sp == sq)
self.assertEqual(cp != cq, sp != sq)
self.assertEqual(cp <= cq, sp <= sq)
self.assertEqual(cp >= cq, sp >= sq)
self.assertEqual(cp < cq, sp < sq)
self.assertEqual(cp > cq, sp > sq)
def test_eq(self):
self.assertEqual(Counter(a=3, b=2, c=0), Counter('ababa'))
self.assertNotEqual(Counter(a=3, b=2), Counter('babab'))
def test_le(self):
self.assertTrue(Counter(a=3, b=2, c=0) <= Counter('ababa'))
self.assertFalse(Counter(a=3, b=2) <= Counter('babab'))
def test_lt(self):
self.assertTrue(Counter(a=3, b=1, c=0) < Counter('ababa'))
self.assertFalse(Counter(a=3, b=2, c=0) < Counter('ababa'))
def test_ge(self):
self.assertTrue(Counter(a=2, b=1, c=0) >= Counter('aab'))
self.assertFalse(Counter(a=3, b=2, c=0) >= Counter('aabd'))
def test_gt(self):
self.assertTrue(Counter(a=3, b=2, c=0) > Counter('aab'))
self.assertFalse(Counter(a=2, b=1, c=0) > Counter('aab'))
if __name__ == "__main__":
run_tests()
| TestCounter |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/datafusion.py | {
"start": 5069,
"end": 7726
} | class ____(GoogleCloudBaseOperator):
"""
Deletes a single Date Fusion instance.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:CloudDataFusionDeleteInstanceOperator`
:param instance_name: The name of the instance to restart.
:param location: The Cloud Data Fusion location in which to handle the request.
:param project_id: The ID of the Google Cloud project that the instance belongs to.
:param api_version: The version of the api that will be requested for example 'v3'.
:param gcp_conn_id: The connection ID to use when fetching connection info.
:param impersonation_chain: Optional service account to impersonate using short-term
credentials, or chained list of accounts required to get the access_token
of the last account in the list, which will be impersonated in the request.
If set as a string, the account must grant the originating account
the Service Account Token Creator IAM role.
If set as a sequence, the identities from the list must grant
Service Account Token Creator IAM role to the directly preceding identity, with first
account from the list granting this role to the originating account (templated).
"""
template_fields: Sequence[str] = (
"instance_name",
"impersonation_chain",
)
def __init__(
self,
*,
instance_name: str,
location: str,
project_id: str = PROVIDE_PROJECT_ID,
api_version: str = "v1beta1",
gcp_conn_id: str = "google_cloud_default",
impersonation_chain: str | Sequence[str] | None = None,
**kwargs,
) -> None:
super().__init__(**kwargs)
self.instance_name = instance_name
self.location = location
self.project_id = project_id
self.api_version = api_version
self.gcp_conn_id = gcp_conn_id
self.impersonation_chain = impersonation_chain
def execute(self, context: Context) -> None:
hook = DataFusionHook(
gcp_conn_id=self.gcp_conn_id,
api_version=self.api_version,
impersonation_chain=self.impersonation_chain,
)
self.log.info("Deleting Data Fusion instance: %s", self.instance_name)
operation = hook.delete_instance(
instance_name=self.instance_name,
location=self.location,
project_id=self.project_id,
)
hook.wait_for_operation(operation)
self.log.info("Instance %s deleted successfully", self.instance_name)
| CloudDataFusionDeleteInstanceOperator |
python | pytorch__pytorch | torch/_subclasses/fake_tensor.py | {
"start": 43916,
"end": 44280
} | class ____:
"""
Entry type for the FakeTensor dispatch cache. It supports two types of outputs
1) tensor
2) tuple of tensors
is_output_tuple flag helps in differentiating the return type
"""
output_infos: tuple[_DispatchCacheEntryOutputInfo]
is_output_tuple: bool = False
@dataclass(frozen=True, slots=True)
| _DispatchCacheValidEntry |
python | keras-team__keras | keras/src/layers/preprocessing/hashing_test.py | {
"start": 504,
"end": 20549
} | class ____(testing.TestCase):
def test_config(self):
layer = layers.Hashing(
num_bins=8,
output_mode="int",
)
self.run_class_serialization_test(layer)
def test_correctness(self):
layer = layers.Hashing(num_bins=3)
inp = [["A"], ["B"], ["C"], ["D"], ["E"]]
output = layer(inp)
self.assertTrue(backend.is_tensor(output))
self.assertAllClose(output, np.array([[1], [0], [1], [1], [2]]))
layer = layers.Hashing(num_bins=3, mask_value="")
inp = [["A"], ["B"], [""], ["C"], ["D"]]
output = layer(inp)
self.assertTrue(backend.is_tensor(output))
self.assertAllClose(output, np.array([[1], [1], [0], [2], [2]]))
layer = layers.Hashing(num_bins=3, salt=[133, 137])
inp = [["A"], ["B"], ["C"], ["D"], ["E"]]
output = layer(inp)
self.assertTrue(backend.is_tensor(output))
self.assertAllClose(output, np.array([[1], [2], [1], [0], [2]]))
layer = layers.Hashing(num_bins=3, salt=133)
inp = [["A"], ["B"], ["C"], ["D"], ["E"]]
output = layer(inp)
self.assertTrue(backend.is_tensor(output))
self.assertAllClose(output, np.array([[0], [0], [2], [1], [0]]))
def test_tf_data_compatibility(self):
layer = layers.Hashing(num_bins=3)
inp = [["A"], ["B"], ["C"], ["D"], ["E"]]
ds = tf.data.Dataset.from_tensor_slices(inp).batch(5).map(layer)
output = next(iter(ds)).numpy()
self.assertAllClose(output, np.array([[1], [0], [1], [1], [2]]))
@parameterized.named_parameters(
("list", list),
("tuple", tuple),
("numpy", np.array),
("array_like", ArrayLike),
)
def test_tensor_like_inputs(self, data_fn):
input_data = data_fn([0, 1, 2, 3, 4])
expected_output = [1, 0, 1, 0, 2]
layer = layers.Hashing(num_bins=3)
output_data = layer(input_data)
self.assertAllEqual(output_data, expected_output)
def test_hash_single_bin(self):
layer = layers.Hashing(num_bins=1)
inp = np.asarray([["A"], ["B"], ["C"], ["D"], ["E"]])
output = layer(inp)
self.assertAllClose([[0], [0], [0], [0], [0]], output)
def test_hash_dense_input_farmhash(self):
layer = layers.Hashing(num_bins=2)
inp = np.asarray(
[["omar"], ["stringer"], ["marlo"], ["wire"], ["skywalker"]]
)
output = layer(inp)
# Assert equal for hashed output that should be true on all platforms.
self.assertAllClose([[0], [0], [1], [0], [0]], output)
def test_hash_dense_input_mask_value_farmhash(self):
empty_mask_layer = layers.Hashing(num_bins=3, mask_value="")
omar_mask_layer = layers.Hashing(num_bins=3, mask_value="omar")
inp = np.asarray(
[["omar"], ["stringer"], ["marlo"], ["wire"], ["skywalker"]]
)
empty_mask_output = empty_mask_layer(inp)
omar_mask_output = omar_mask_layer(inp)
# Outputs should be one more than test_hash_dense_input_farmhash (the
# zeroth bin is now reserved for masks).
self.assertAllClose([[1], [1], [2], [1], [1]], empty_mask_output)
# 'omar' should map to 0.
self.assertAllClose([[0], [1], [2], [1], [1]], omar_mask_output)
def test_hash_dense_list_input_farmhash(self):
layer = layers.Hashing(num_bins=2)
inp = [["omar"], ["stringer"], ["marlo"], ["wire"], ["skywalker"]]
output = layer(inp)
# Assert equal for hashed output that should be true on all platforms.
self.assertAllClose([[0], [0], [1], [0], [0]], output)
inp = ["omar", "stringer", "marlo", "wire", "skywalker"]
output = layer(inp)
# Assert equal for hashed output that should be true on all platforms.
self.assertAllClose([0, 0, 1, 0, 0], output)
def test_hash_dense_int_input_farmhash(self):
layer = layers.Hashing(num_bins=3)
inp = np.asarray([[0], [1], [2], [3], [4]])
output = layer(inp)
# Assert equal for hashed output that should be true on all platforms.
self.assertAllClose([[1], [0], [1], [0], [2]], output)
def test_hash_dense_input_siphash(self):
layer = layers.Hashing(num_bins=2, salt=[133, 137])
inp = np.asarray(
[["omar"], ["stringer"], ["marlo"], ["wire"], ["skywalker"]]
)
output = layer(inp)
# Assert equal for hashed output that should be true on all platforms.
# Note the result is different from FarmHash.
self.assertAllClose([[0], [1], [0], [1], [0]], output)
layer_2 = layers.Hashing(num_bins=2, salt=[211, 137])
output_2 = layer_2(inp)
# Note the result is different from (133, 137).
self.assertAllClose([[1], [0], [1], [0], [1]], output_2)
def test_hash_dense_int_input_siphash(self):
layer = layers.Hashing(num_bins=3, salt=[133, 137])
inp = np.asarray([[0], [1], [2], [3], [4]])
output = layer(inp)
# Assert equal for hashed output that should be true on all platforms.
self.assertAllClose([[1], [1], [2], [0], [1]], output)
@pytest.mark.skipif(
backend.backend() != "tensorflow", reason="Uses tf.SparseTensor."
)
def test_hash_sparse_input_farmhash(self):
layer = layers.Hashing(num_bins=2)
indices = [[0, 0], [1, 0], [1, 1], [2, 0], [2, 1]]
inp = tf.SparseTensor(
indices=indices,
values=["omar", "stringer", "marlo", "wire", "skywalker"],
dense_shape=[3, 2],
)
output = layer(inp)
self.assertAllClose(indices, output.indices)
self.assertAllClose([0, 0, 1, 0, 0], output.values)
@pytest.mark.skipif(
backend.backend() != "tensorflow", reason="Uses tf.SparseTensor."
)
def test_hash_sparse_input_mask_value_farmhash(self):
empty_mask_layer = layers.Hashing(num_bins=3, mask_value="")
omar_mask_layer = layers.Hashing(num_bins=3, mask_value="omar")
indices = [[0, 0], [1, 0], [1, 1], [2, 0], [2, 1]]
inp = tf.SparseTensor(
indices=indices,
values=["omar", "stringer", "marlo", "wire", "skywalker"],
dense_shape=[3, 2],
)
empty_mask_output = empty_mask_layer(inp)
omar_mask_output = omar_mask_layer(inp)
self.assertAllClose(indices, omar_mask_output.indices)
self.assertAllClose(indices, empty_mask_output.indices)
# Outputs should be one more than test_hash_sparse_input_farmhash (the
# zeroth bin is now reserved for masks).
self.assertAllClose([1, 1, 2, 1, 1], empty_mask_output.values)
# 'omar' should map to 0.
self.assertAllClose([0, 1, 2, 1, 1], omar_mask_output.values)
@pytest.mark.skipif(
backend.backend() != "tensorflow", reason="Uses tf.SparseTensor."
)
def test_hash_sparse_int_input_farmhash(self):
layer = layers.Hashing(num_bins=3)
indices = [[0, 0], [1, 0], [1, 1], [2, 0], [2, 1]]
inp = tf.SparseTensor(
indices=indices, values=[0, 1, 2, 3, 4], dense_shape=[3, 2]
)
output = layer(inp)
self.assertAllClose(indices, output.indices)
self.assertAllClose([1, 0, 1, 0, 2], output.values)
@pytest.mark.skipif(
backend.backend() != "tensorflow", reason="Uses tf.SparseTensor."
)
def test_hash_sparse_input_siphash(self):
layer = layers.Hashing(num_bins=2, salt=[133, 137])
indices = [[0, 0], [1, 0], [1, 1], [2, 0], [2, 1]]
inp = tf.SparseTensor(
indices=indices,
values=["omar", "stringer", "marlo", "wire", "skywalker"],
dense_shape=[3, 2],
)
output = layer(inp)
self.assertAllClose(output.indices, indices)
# The result should be same with test_hash_dense_input_siphash.
self.assertAllClose([0, 1, 0, 1, 0], output.values)
layer_2 = layers.Hashing(num_bins=2, salt=[211, 137])
output = layer_2(inp)
# The result should be same with test_hash_dense_input_siphash.
self.assertAllClose([1, 0, 1, 0, 1], output.values)
@pytest.mark.skipif(
backend.backend() != "tensorflow", reason="Uses tf.SparseTensor."
)
def test_hash_sparse_int_input_siphash(self):
layer = layers.Hashing(num_bins=3, salt=[133, 137])
indices = [[0, 0], [1, 0], [1, 1], [2, 0], [2, 1]]
inp = tf.SparseTensor(
indices=indices, values=[0, 1, 2, 3, 4], dense_shape=[3, 2]
)
output = layer(inp)
self.assertAllClose(indices, output.indices)
self.assertAllClose([1, 1, 2, 0, 1], output.values)
def test_invalid_inputs(self):
with self.assertRaisesRegex(ValueError, "cannot be `None`"):
_ = layers.Hashing(num_bins=None)
with self.assertRaisesRegex(ValueError, "cannot be `None`"):
_ = layers.Hashing(num_bins=-1)
with self.assertRaisesRegex(
ValueError, "can only be a tuple of size 2"
):
_ = layers.Hashing(num_bins=2, salt="string")
with self.assertRaisesRegex(
ValueError, "can only be a tuple of size 2"
):
_ = layers.Hashing(num_bins=2, salt=[1])
with self.assertRaisesRegex(
ValueError, "can only be a tuple of size 2"
):
_ = layers.Hashing(num_bins=1, salt=[133, 137, 177])
def test_one_hot_output(self):
input_array = np.array([0, 1, 2, 3, 4])
expected_output = [
[0.0, 1.0, 0.0],
[1.0, 0.0, 0.0],
[0.0, 1.0, 0.0],
[1.0, 0.0, 0.0],
[0.0, 0.0, 1.0],
]
expected_output_shape = [None, 3]
inputs = layers.Input(shape=(1,), dtype="int32")
layer = layers.Hashing(num_bins=3, output_mode="one_hot")
outputs = layer(inputs)
self.assertAllEqual(expected_output_shape, outputs.shape)
model = models.Model(inputs, outputs)
output_data = model(input_array)
self.assertAllClose(expected_output, output_data)
def test_multi_hot_output(self):
input_array = np.array([[0, 1, 2, 3, 4]])
expected_output = [[1.0, 1.0, 1.0]]
expected_output_shape = [None, 3]
inputs = layers.Input(shape=(None,), dtype="int32")
layer = layers.Hashing(num_bins=3, output_mode="multi_hot")
outputs = layer(inputs)
self.assertAllEqual(expected_output_shape, outputs.shape)
model = models.Model(inputs, outputs)
output_data = model(input_array)
self.assertAllClose(expected_output, output_data)
@parameterized.named_parameters(
(
"1d_input",
[0, 1, 2, 3, 4],
[2.0, 2.0, 1.0],
[3],
),
(
"2d_input",
[[0, 1, 2, 3, 4]],
[[2.0, 2.0, 1.0]],
[None, 3],
),
)
def test_count_output(self, input_value, expected_output, output_shape):
input_array = np.array(input_value)
if input_array.ndim == 1:
symbolic_sample_shape = ()
elif input_array.ndim == 2:
symbolic_sample_shape = (None,)
else:
raise TypeError("Unknown `symbolic_sample_shape`")
inputs = layers.Input(shape=symbolic_sample_shape, dtype="int32")
layer = layers.Hashing(num_bins=3, output_mode="count")
outputs = layer(inputs)
self.assertAllEqual(output_shape, outputs.shape)
output_data = layer(input_array)
self.assertAllEqual(expected_output, output_data)
@parameterized.named_parameters(
("int32", "int32"),
("int64", "int64"),
)
def test_int_output_dtype(self, dtype):
input_data = layers.Input(batch_size=16, shape=(4,), dtype="string")
layer = layers.Hashing(num_bins=3, output_mode="int", dtype=dtype)
output = layer(input_data)
self.assertEqual(output.dtype, dtype)
@parameterized.named_parameters(
("float32", "float32"),
("float64", "float64"),
)
def test_one_hot_output_dtype(self, dtype):
input_data = layers.Input(batch_size=16, shape=(1,), dtype="string")
layer = layers.Hashing(num_bins=3, output_mode="one_hot", dtype=dtype)
output = layer(input_data)
self.assertEqual(output.dtype, dtype)
def test_config_with_custom_name(self):
layer = layers.Hashing(num_bins=2, name="hashing")
config = layer.get_config()
layer_1 = layers.Hashing.from_config(config)
self.assertEqual(layer_1.name, layer.name)
@pytest.mark.skipif(
backend.backend() != "tensorflow", reason="Uses string dtype."
)
def test_saving(self):
input_data = np.array(
["omar", "stringer", "marlo", "wire", "skywalker"]
)
inputs = layers.Input(shape=(), dtype="string")
outputs = layers.Hashing(num_bins=100)(inputs)
model = models.Model(inputs=inputs, outputs=outputs)
original_output_data = model(input_data)
# Save the model to disk.
output_path = os.path.join(self.get_temp_dir(), "keras_model.keras")
model.save(output_path)
loaded_model = load_model(output_path)
# Ensure that the loaded model is unique (so that the save/load is real)
self.assertIsNot(model, loaded_model)
# Validate correctness of the new model.
new_output_data = loaded_model(input_data)
self.assertAllClose(new_output_data, original_output_data)
@parameterized.named_parameters(
(
"list_input",
[1, 2, 3],
[1, 1, 1],
),
(
"list_input_2d",
[[1], [2], [3]],
[[1], [1], [1]],
),
(
"list_input_2d_multiple",
[[1, 2], [2, 3], [3, 4]],
[[1, 1], [1, 1], [1, 1]],
),
(
"list_input_3d",
[[[1], [2]], [[2], [3]], [[3], [4]]],
[[[1], [1]], [[1], [1]], [[1], [1]]],
),
)
def test_hash_list_input(self, input_data, expected):
layer = layers.Hashing(num_bins=2)
out_data = layer(input_data)
self.assertAllEqual(
expected, backend.convert_to_numpy(out_data).tolist()
)
def test_hashing_invalid_num_bins(self):
# Test with `num_bins` set to None
with self.assertRaisesRegex(
ValueError,
"The `num_bins` for `Hashing` cannot be `None` or non-positive",
):
layers.Hashing(num_bins=None)
# Test with `num_bins` set to 0
with self.assertRaisesRegex(
ValueError,
"The `num_bins` for `Hashing` cannot be `None` or non-positive",
):
layers.Hashing(num_bins=0)
def test_hashing_invalid_output_mode(self):
# Test with an unsupported `output_mode`
with self.assertRaisesRegex(
ValueError,
"Invalid value for argument `output_mode`. Expected one of",
):
layers.Hashing(num_bins=3, output_mode="unsupported_mode")
def test_hashing_invalid_dtype_for_int_mode(self):
with self.assertRaisesRegex(
ValueError,
'When `output_mode="int"`, `dtype` should be an integer type,',
):
layers.Hashing(num_bins=3, output_mode="int", dtype="float32")
def test_hashing_sparse_with_int_mode(self):
# Test setting `sparse=True` with `output_mode='int'`
with self.assertRaisesRegex(
ValueError, "`sparse` may only be true if `output_mode` is"
):
layers.Hashing(num_bins=3, output_mode="int", sparse=True)
# TODO: support tf.RaggedTensor.
# def test_hash_ragged_string_input_farmhash(self):
# layer = layers.Hashing(num_bins=2)
# inp_data = tf.ragged.constant(
# [
# ["omar", "stringer", "marlo", "wire"],
# ["marlo", "skywalker", "wire"],
# ],
# dtype="string",
# )
# out_data = layer(inp_data)
# # Same hashed output as test_hash_sparse_input_farmhash
# expected_output = [[0, 0, 1, 0], [1, 0, 0]]
# self.assertAllEqual(expected_output, out_data)
# inp_t = layers.Input(shape=(None,), ragged=True, dtype="string")
# out_t = layer(inp_t)
# model = models.Model(inputs=inp_t, outputs=out_t)
# self.assertAllClose(out_data, model.predict(inp_data))
# TODO: support tf.RaggedTensor.
# def test_hash_ragged_input_mask_value(self):
# empty_mask_layer = layers.Hashing(num_bins=3, mask_value="")
# omar_mask_layer = layers.Hashing(num_bins=3, mask_value="omar")
# inp_data = tf.ragged.constant(
# [
# ["omar", "stringer", "marlo", "wire"],
# ["marlo", "skywalker", "wire"],
# ],
# dtype="string",
# )
# empty_mask_output = empty_mask_layer(inp_data)
# omar_mask_output = omar_mask_layer(inp_data)
# # Outputs should be one more than test_hash_ragged_string_input_farmhash
# # (the zeroth bin is now reserved for masks).
# expected_output = [[1, 1, 2, 1], [2, 1, 1]]
# self.assertAllClose(expected_output[0], empty_mask_output[1])
# self.assertAllClose(expected_output[1], empty_mask_output[2])
# # 'omar' should map to 0.
# expected_output = [[0, 1, 2, 1], [2, 1, 1]]
# self.assertAllClose(expected_output[0], omar_mask_output[0])
# self.assertAllClose(expected_output[1], omar_mask_output[1])
# TODO: support tf.RaggedTensor.
# def test_hash_ragged_int_input_farmhash(self):
# layer = layers.Hashing(num_bins=3)
# inp_data = tf.ragged.constant([[0, 1, 3, 4], [2, 1, 0]], dtype="int64")
# out_data = layer(inp_data)
# # Same hashed output as test_hash_sparse_input_farmhash
# expected_output = [[1, 0, 0, 2], [1, 0, 1]]
# self.assertAllEqual(expected_output[0], out_data[0])
# self.assertAllEqual(expected_output[1], out_data[1])
# inp_t = layers.Input(shape=(None,), ragged=True, dtype="int64")
# out_t = layer(inp_t)
# model = models.Model(inputs=inp_t, outputs=out_t)
# self.assertAllClose(out_data, model.predict(inp_data))
# TODO: support tf.RaggedTensor.
# def test_hash_ragged_string_input_siphash(self):
# layer = layers.Hashing(num_bins=2, salt=[133, 137])
# inp_data = tf.ragged.constant(
# [
# ["omar", "stringer", "marlo", "wire"],
# ["marlo", "skywalker", "wire"],
# ],
# dtype="string",
# )
# out_data = layer(inp_data)
# # Same hashed output as test_hash_dense_input_siphash
# expected_output = [[0, 1, 0, 1], [0, 0, 1]]
# self.assertAllEqual(expected_output, out_data)
# inp_t = layers.Input(shape=(None,), ragged=True, dtype="string")
# out_t = layer(inp_t)
# model = models.Model(inputs=inp_t, outputs=out_t)
# self.assertAllClose(out_data, model.predict(inp_data))
# layer_2 = layers.Hashing(num_bins=2, salt=[211, 137])
# out_data = layer_2(inp_data)
# expected_output = [[1, 0, 1, 0], [1, 1, 0]]
# self.assertAllEqual(expected_output, out_data)
# out_t = layer_2(inp_t)
# model = models.Model(inputs=inp_t, outputs=out_t)
# self.assertAllClose(out_data, model.predict(inp_data))
# TODO: support tf.RaggedTensor.
# def test_hash_ragged_int_input_siphash(self):
# layer = layers.Hashing(num_bins=3, salt=[133, 137])
# inp_data = tf.ragged.constant([[0, 1, 3, 4], [2, 1, 0]], dtype="int64")
# out_data = layer(inp_data)
# # Same hashed output as test_hash_sparse_input_farmhash
# expected_output = [[1, 1, 0, 1], [2, 1, 1]]
# self.assertAllEqual(expected_output, out_data)
# inp_t = layers.Input(shape=(None,), ragged=True, dtype="int64")
# out_t = layer(inp_t)
# model = models.Model(inputs=inp_t, outputs=out_t)
# self.assertAllClose(out_data, model.predict(inp_data))
| HashingTest |
python | django__django | tests/many_to_one/models.py | {
"start": 3334,
"end": 3445
} | class ____(models.Model):
is_public = models.BooleanField(default=False)
objects = SchoolManager()
| School |
python | django__django | django/forms/models.py | {
"start": 40476,
"end": 50090
} | class ____(BaseModelFormSet):
"""A formset for child objects related to a parent."""
def __init__(
self,
data=None,
files=None,
instance=None,
save_as_new=False,
prefix=None,
queryset=None,
**kwargs,
):
if instance is None:
self.instance = self.fk.remote_field.model()
else:
self.instance = instance
self.save_as_new = save_as_new
if queryset is None:
queryset = self.model._default_manager
if self.instance._is_pk_set():
qs = queryset.filter(**{self.fk.name: self.instance})
else:
qs = queryset.none()
self.unique_fields = {self.fk.name}
super().__init__(data, files, prefix=prefix, queryset=qs, **kwargs)
# Add the inline foreign key field to form._meta.fields if it's defined
# to make sure validation isn't skipped on that field.
if self.form._meta.fields and self.fk.name not in self.form._meta.fields:
self.form._meta.fields = list(self.form._meta.fields)
self.form._meta.fields.append(self.fk.name)
def initial_form_count(self):
if self.save_as_new:
return 0
return super().initial_form_count()
def _construct_form(self, i, **kwargs):
form = super()._construct_form(i, **kwargs)
if self.save_as_new:
mutable = getattr(form.data, "_mutable", None)
# Allow modifying an immutable QueryDict.
if mutable is not None:
form.data._mutable = True
# Remove the primary key from the form's data, we are only
# creating new instances
form.data[form.add_prefix(self._pk_field.name)] = None
# Remove the foreign key from the form's data
form.data[form.add_prefix(self.fk.name)] = None
if mutable is not None:
form.data._mutable = mutable
# Set the fk value here so that the form can do its validation.
fk_value = self.instance.pk
if self.fk.remote_field.field_name != self.fk.remote_field.model._meta.pk.name:
fk_value = getattr(self.instance, self.fk.remote_field.field_name)
fk_value = getattr(fk_value, "pk", fk_value)
setattr(form.instance, self.fk.attname, fk_value)
return form
@classmethod
def get_default_prefix(cls):
return cls.fk.remote_field.get_accessor_name(model=cls.model).replace("+", "")
def save_new(self, form, commit=True):
# Ensure the latest copy of the related instance is present on each
# form (it may have been saved after the formset was originally
# instantiated).
setattr(form.instance, self.fk.name, self.instance)
return super().save_new(form, commit=commit)
def add_fields(self, form, index):
super().add_fields(form, index)
if self._pk_field == self.fk:
name = self._pk_field.name
kwargs = {"pk_field": True}
else:
# The foreign key field might not be on the form, so we poke at the
# Model field to get the label, since we need that for error
# messages.
name = self.fk.name
kwargs = {
"label": getattr(
form.fields.get(name), "label", capfirst(self.fk.verbose_name)
)
}
# The InlineForeignKeyField assumes that the foreign key relation is
# based on the parent model's pk. If this isn't the case, set to_field
# to correctly resolve the initial form value.
if self.fk.remote_field.field_name != self.fk.remote_field.model._meta.pk.name:
kwargs["to_field"] = self.fk.remote_field.field_name
# If we're adding a new object, ignore a parent's auto-generated key
# as it will be regenerated on the save request.
if self.instance._state.adding:
if kwargs.get("to_field") is not None:
to_field = self.instance._meta.get_field(kwargs["to_field"])
else:
to_field = self.instance._meta.pk
if to_field.has_default() and (
# Don't ignore a parent's auto-generated key if it's not the
# parent model's pk and form data is provided.
to_field.attname == self.fk.remote_field.model._meta.pk.name
or not form.data
):
setattr(self.instance, to_field.attname, None)
form.fields[name] = InlineForeignKeyField(self.instance, **kwargs)
def get_unique_error_message(self, unique_check):
unique_check = [field for field in unique_check if field != self.fk.name]
return super().get_unique_error_message(unique_check)
def _get_foreign_key(parent_model, model, fk_name=None, can_fail=False):
"""
Find and return the ForeignKey from model to parent if there is one
(return None if can_fail is True and no such field exists). If fk_name is
provided, assume it is the name of the ForeignKey field. Unless can_fail is
True, raise an exception if there isn't a ForeignKey from model to
parent_model.
"""
# avoid circular import
from django.db.models import ForeignKey
opts = model._meta
if fk_name:
fks_to_parent = [f for f in opts.fields if f.name == fk_name]
if len(fks_to_parent) == 1:
fk = fks_to_parent[0]
all_parents = (*parent_model._meta.all_parents, parent_model)
if (
not isinstance(fk, ForeignKey)
or (
# ForeignKey to proxy models.
fk.remote_field.model._meta.proxy
and fk.remote_field.model._meta.proxy_for_model not in all_parents
)
or (
# ForeignKey to concrete models.
not fk.remote_field.model._meta.proxy
and fk.remote_field.model != parent_model
and fk.remote_field.model not in all_parents
)
):
raise ValueError(
"fk_name '%s' is not a ForeignKey to '%s'."
% (fk_name, parent_model._meta.label)
)
elif not fks_to_parent:
raise ValueError(
"'%s' has no field named '%s'." % (model._meta.label, fk_name)
)
else:
# Try to discover what the ForeignKey from model to parent_model is
all_parents = (*parent_model._meta.all_parents, parent_model)
fks_to_parent = [
f
for f in opts.fields
if isinstance(f, ForeignKey)
and (
f.remote_field.model == parent_model
or f.remote_field.model in all_parents
or (
f.remote_field.model._meta.proxy
and f.remote_field.model._meta.proxy_for_model in all_parents
)
)
]
if len(fks_to_parent) == 1:
fk = fks_to_parent[0]
elif not fks_to_parent:
if can_fail:
return
raise ValueError(
"'%s' has no ForeignKey to '%s'."
% (
model._meta.label,
parent_model._meta.label,
)
)
else:
raise ValueError(
"'%s' has more than one ForeignKey to '%s'. You must specify "
"a 'fk_name' attribute."
% (
model._meta.label,
parent_model._meta.label,
)
)
return fk
def inlineformset_factory(
parent_model,
model,
form=ModelForm,
formset=BaseInlineFormSet,
fk_name=None,
fields=None,
exclude=None,
extra=3,
can_order=False,
can_delete=True,
max_num=None,
formfield_callback=None,
widgets=None,
validate_max=False,
localized_fields=None,
labels=None,
help_texts=None,
error_messages=None,
min_num=None,
validate_min=False,
field_classes=None,
absolute_max=None,
can_delete_extra=True,
renderer=None,
edit_only=False,
):
"""
Return an ``InlineFormSet`` for the given kwargs.
``fk_name`` must be provided if ``model`` has more than one ``ForeignKey``
to ``parent_model``.
"""
fk = _get_foreign_key(parent_model, model, fk_name=fk_name)
# enforce a max_num=1 when the foreign key to the parent model is unique.
if fk.unique:
max_num = 1
kwargs = {
"form": form,
"formfield_callback": formfield_callback,
"formset": formset,
"extra": extra,
"can_delete": can_delete,
"can_order": can_order,
"fields": fields,
"exclude": exclude,
"min_num": min_num,
"max_num": max_num,
"widgets": widgets,
"validate_min": validate_min,
"validate_max": validate_max,
"localized_fields": localized_fields,
"labels": labels,
"help_texts": help_texts,
"error_messages": error_messages,
"field_classes": field_classes,
"absolute_max": absolute_max,
"can_delete_extra": can_delete_extra,
"renderer": renderer,
"edit_only": edit_only,
}
FormSet = modelformset_factory(model, **kwargs)
FormSet.fk = fk
return FormSet
# Fields #####################################################################
| BaseInlineFormSet |
python | django__django | django/template/smartif.py | {
"start": 265,
"end": 3754
} | class ____:
"""
Base class for operators and literals, mainly for debugging and for
throwing syntax errors.
"""
id = None # node/token type name
value = None # used by literals
first = second = None # used by tree nodes
def nud(self, parser):
# Null denotation - called in prefix context
raise parser.error_class(
"Not expecting '%s' in this position in if tag." % self.id
)
def led(self, left, parser):
# Left denotation - called in infix context
raise parser.error_class(
"Not expecting '%s' as infix operator in if tag." % self.id
)
def display(self):
"""
Return what to display in error messages for this node
"""
return self.id
def __repr__(self):
out = [str(x) for x in [self.id, self.first, self.second] if x is not None]
return "(" + " ".join(out) + ")"
def infix(bp, func):
"""
Create an infix operator, given a binding power and a function that
evaluates the node.
"""
class Operator(TokenBase):
lbp = bp
def led(self, left, parser):
self.first = left
self.second = parser.expression(bp)
return self
def eval(self, context):
try:
return func(context, self.first, self.second)
except Exception:
# Templates shouldn't throw exceptions when rendering. We are
# most likely to get exceptions for things like:
# {% if foo in bar %}
# where 'bar' does not support 'in', so default to False.
return False
return Operator
def prefix(bp, func):
"""
Create a prefix operator, given a binding power and a function that
evaluates the node.
"""
class Operator(TokenBase):
lbp = bp
def nud(self, parser):
self.first = parser.expression(bp)
self.second = None
return self
def eval(self, context):
try:
return func(context, self.first)
except Exception:
return False
return Operator
# Operator precedence follows Python.
# We defer variable evaluation to the lambda to ensure that terms are
# lazily evaluated using Python's boolean parsing logic.
OPERATORS = {
"or": infix(6, lambda context, x, y: x.eval(context) or y.eval(context)),
"and": infix(7, lambda context, x, y: x.eval(context) and y.eval(context)),
"not": prefix(8, lambda context, x: not x.eval(context)),
"in": infix(9, lambda context, x, y: x.eval(context) in y.eval(context)),
"not in": infix(9, lambda context, x, y: x.eval(context) not in y.eval(context)),
"is": infix(10, lambda context, x, y: x.eval(context) is y.eval(context)),
"is not": infix(10, lambda context, x, y: x.eval(context) is not y.eval(context)),
"==": infix(10, lambda context, x, y: x.eval(context) == y.eval(context)),
"!=": infix(10, lambda context, x, y: x.eval(context) != y.eval(context)),
">": infix(10, lambda context, x, y: x.eval(context) > y.eval(context)),
">=": infix(10, lambda context, x, y: x.eval(context) >= y.eval(context)),
"<": infix(10, lambda context, x, y: x.eval(context) < y.eval(context)),
"<=": infix(10, lambda context, x, y: x.eval(context) <= y.eval(context)),
}
# Assign 'id' to each:
for key, op in OPERATORS.items():
op.id = key
| TokenBase |
python | pyca__cryptography | src/cryptography/x509/extensions.py | {
"start": 32393,
"end": 33380
} | class ____(ExtensionType):
oid = ExtensionOID.TLS_FEATURE
def __init__(self, features: Iterable[TLSFeatureType]) -> None:
features = list(features)
if (
not all(isinstance(x, TLSFeatureType) for x in features)
or len(features) == 0
):
raise TypeError(
"features must be a list of elements from the TLSFeatureType "
"enum"
)
self._features = features
__len__, __iter__, __getitem__ = _make_sequence_methods("_features")
def __repr__(self) -> str:
return f"<TLSFeature(features={self._features})>"
def __eq__(self, other: object) -> bool:
if not isinstance(other, TLSFeature):
return NotImplemented
return self._features == other._features
def __hash__(self) -> int:
return hash(tuple(self._features))
def public_bytes(self) -> bytes:
return rust_x509.encode_extension_value(self)
| TLSFeature |
python | django__django | tests/admin_scripts/tests.py | {
"start": 95909,
"end": 96520
} | class ____(SimpleTestCase):
def test_program_name_from_argv(self):
"""
Program name is computed from the execute_from_command_line()'s argv
argument, not sys.argv.
"""
args = ["help", "shell"]
with captured_stdout() as out, captured_stderr() as err:
with mock.patch("sys.argv", [None] + args):
execute_from_command_line(["django-admin"] + args)
self.assertIn("usage: django-admin shell", out.getvalue())
self.assertEqual(err.getvalue(), "")
@override_settings(ROOT_URLCONF="admin_scripts.urls")
| ExecuteFromCommandLine |
python | pennersr__django-allauth | tests/apps/socialaccount/providers/salesforce/tests.py | {
"start": 248,
"end": 2247
} | class ____(OAuth2TestsMixin, TestCase):
provider_id = SalesforceProvider.id
def get_mocked_response(
self,
last_name="Penners",
first_name="Raymond",
name="Raymond Penners",
email="raymond.penners@gmail.com",
verified_email=True,
):
userinfo = USERINFO_RESPONSE.format(
org_id="00Dxx00000000000A0",
user_id="005xx000000aWwRQAU",
vip="https://test.salesforce.com",
nickname="test-ooi2xhmjteep",
first_name=first_name,
last_name=last_name,
my_domain="https://fun.cs46.my.salesforce.com",
content_domain="https://fun--c.cs46.content.force.com",
verified_email=repr(verified_email).lower(),
email=email,
active="true",
is_app_installed="true",
)
return MockedResponse(HTTPStatus.OK, userinfo)
def get_expected_to_str(self):
return "raymond.penners@gmail.com"
USERINFO_RESPONSE = """
{{
"sub": "{vip}/id/{org_id}/{user_id}",
"user_id": "{user_id}",
"organization_id": "{org_id}",
"preferred_username": "{nickname}@sample_-_dev_workspace.net",
"nickname": "{nickname}",
"name": "{first_name} {last_name}",
"email": "{email}",
"email_verified": {verified_email},
"given_name": "{first_name}",
"family_name": "{last_name}",
"zoneinfo": "America/Los_Angeles",
"photos": {{
"picture": "{content_domain}/profilephoto/005/F",
"thumbnail": "{content_domain}/profilephoto/005/T"
}},
"profile": "{my_domain}/{user_id}",
"picture": "{content_domain}/profilephoto/005/F",
"address": {{"country": "US"}},
"urls": {{"custom_domain": "{my_domain}"}},
"active": {active},
"user_type": "STANDARD",
"language": "en_US",
"locale": "en_US",
"utcOffset": -28800000,
"updated_at": "2017-10-05T20:39:02.000+0000",
"is_app_installed": {is_app_installed}
}}
"""
| SalesforceTests |
python | google__pytype | pytype/load_pytd.py | {
"start": 1927,
"end": 2033
} | class ____:
module_name: str
filename: str
ast: pytd.TypeDeclUnit
metadata: list[str]
| ResolvedModule |
python | sympy__sympy | sympy/physics/biomechanics/tests/test_musculotendon.py | {
"start": 3019,
"end": 9321
} | class ____:
@pytest.fixture(autouse=True)
def _musculotendon_rigid_tendon_fixture(self, musculotendon_concrete):
self.name = 'name'
self.N = ReferenceFrame('N')
self.q = dynamicsymbols('q')
self.origin = Point('pO')
self.insertion = Point('pI')
self.insertion.set_pos(self.origin, self.q*self.N.x)
self.pathway = LinearPathway(self.origin, self.insertion)
self.activation = FirstOrderActivationDeGroote2016(self.name)
self.e = self.activation.excitation
self.a = self.activation.activation
self.tau_a = self.activation.activation_time_constant
self.tau_d = self.activation.deactivation_time_constant
self.b = self.activation.smoothing_rate
self.formulation = MusculotendonFormulation.RIGID_TENDON
self.l_T_slack = Symbol('l_T_slack')
self.F_M_max = Symbol('F_M_max')
self.l_M_opt = Symbol('l_M_opt')
self.v_M_max = Symbol('v_M_max')
self.alpha_opt = Symbol('alpha_opt')
self.beta = Symbol('beta')
self.instance = musculotendon_concrete(
self.name,
self.pathway,
self.activation,
musculotendon_dynamics=self.formulation,
tendon_slack_length=self.l_T_slack,
peak_isometric_force=self.F_M_max,
optimal_fiber_length=self.l_M_opt,
maximal_fiber_velocity=self.v_M_max,
optimal_pennation_angle=self.alpha_opt,
fiber_damping_coefficient=self.beta,
)
self.da_expr = (
(1/(self.tau_a*(Rational(1, 2) + Rational(3, 2)*self.a)))
*(Rational(1, 2) + Rational(1, 2)*tanh(self.b*(self.e - self.a)))
+ ((Rational(1, 2) + Rational(3, 2)*self.a)/self.tau_d)
*(Rational(1, 2) - Rational(1, 2)*tanh(self.b*(self.e - self.a)))
)*(self.e - self.a)
def test_state_vars(self):
assert hasattr(self.instance, 'x')
assert hasattr(self.instance, 'state_vars')
assert self.instance.x == self.instance.state_vars
x_expected = Matrix([self.a])
assert self.instance.x == x_expected
assert self.instance.state_vars == x_expected
assert isinstance(self.instance.x, Matrix)
assert isinstance(self.instance.state_vars, Matrix)
assert self.instance.x.shape == (1, 1)
assert self.instance.state_vars.shape == (1, 1)
def test_input_vars(self):
assert hasattr(self.instance, 'r')
assert hasattr(self.instance, 'input_vars')
assert self.instance.r == self.instance.input_vars
r_expected = Matrix([self.e])
assert self.instance.r == r_expected
assert self.instance.input_vars == r_expected
assert isinstance(self.instance.r, Matrix)
assert isinstance(self.instance.input_vars, Matrix)
assert self.instance.r.shape == (1, 1)
assert self.instance.input_vars.shape == (1, 1)
def test_constants(self):
assert hasattr(self.instance, 'p')
assert hasattr(self.instance, 'constants')
assert self.instance.p == self.instance.constants
p_expected = Matrix(
[
self.l_T_slack,
self.F_M_max,
self.l_M_opt,
self.v_M_max,
self.alpha_opt,
self.beta,
self.tau_a,
self.tau_d,
self.b,
Symbol('c_0_fl_T_name'),
Symbol('c_1_fl_T_name'),
Symbol('c_2_fl_T_name'),
Symbol('c_3_fl_T_name'),
Symbol('c_0_fl_M_pas_name'),
Symbol('c_1_fl_M_pas_name'),
Symbol('c_0_fl_M_act_name'),
Symbol('c_1_fl_M_act_name'),
Symbol('c_2_fl_M_act_name'),
Symbol('c_3_fl_M_act_name'),
Symbol('c_4_fl_M_act_name'),
Symbol('c_5_fl_M_act_name'),
Symbol('c_6_fl_M_act_name'),
Symbol('c_7_fl_M_act_name'),
Symbol('c_8_fl_M_act_name'),
Symbol('c_9_fl_M_act_name'),
Symbol('c_10_fl_M_act_name'),
Symbol('c_11_fl_M_act_name'),
Symbol('c_0_fv_M_name'),
Symbol('c_1_fv_M_name'),
Symbol('c_2_fv_M_name'),
Symbol('c_3_fv_M_name'),
]
)
assert self.instance.p == p_expected
assert self.instance.constants == p_expected
assert isinstance(self.instance.p, Matrix)
assert isinstance(self.instance.constants, Matrix)
assert self.instance.p.shape == (31, 1)
assert self.instance.constants.shape == (31, 1)
def test_M(self):
assert hasattr(self.instance, 'M')
M_expected = Matrix([1])
assert self.instance.M == M_expected
assert isinstance(self.instance.M, Matrix)
assert self.instance.M.shape == (1, 1)
def test_F(self):
assert hasattr(self.instance, 'F')
F_expected = Matrix([self.da_expr])
assert self.instance.F == F_expected
assert isinstance(self.instance.F, Matrix)
assert self.instance.F.shape == (1, 1)
def test_rhs(self):
assert hasattr(self.instance, 'rhs')
rhs_expected = Matrix([self.da_expr])
rhs = self.instance.rhs()
assert isinstance(rhs, Matrix)
assert rhs.shape == (1, 1)
assert simplify(rhs - rhs_expected) == zeros(1)
@pytest.mark.parametrize(
'musculotendon_concrete, curve',
[
(
MusculotendonDeGroote2016,
CharacteristicCurveCollection(
tendon_force_length=TendonForceLengthDeGroote2016,
tendon_force_length_inverse=TendonForceLengthInverseDeGroote2016,
fiber_force_length_passive=FiberForceLengthPassiveDeGroote2016,
fiber_force_length_passive_inverse=FiberForceLengthPassiveInverseDeGroote2016,
fiber_force_length_active=FiberForceLengthActiveDeGroote2016,
fiber_force_velocity=FiberForceVelocityDeGroote2016,
fiber_force_velocity_inverse=FiberForceVelocityInverseDeGroote2016,
),
)
],
)
| TestMusculotendonRigidTendon |
python | huggingface__transformers | src/transformers/models/internvl/modular_internvl.py | {
"start": 24215,
"end": 26182
} | class ____(LlavaForConditionalGeneration):
def forward(**super_kwargs):
r"""
Example:
```python
>>> import torch
>>> from transformers import AutoProcessor, AutoModelForImageTextToText
>>> torch_device = "cuda"
>>> processor = AutoProcessor.from_pretrained("OpenGVLab/InternVL3-1B-hf")
>>> model = AutoModelForImageTextToText.from_pretrained(
... "OpenGVLab/InternVL3-1B-hf", dtype=torch.bfloat16, device_map=torch_device
... )
>>> messages = [
... {
... "role": "user",
... "content": [
... {
... "type": "image",
... "url": "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg",
... },
... {
... "type": "image",
... "url": "https://thumbs.dreamstime.com/b/golden-gate-bridge-san-francisco-purple-flowers-california-echium-candicans-36805947.jpg",
... },
... {"type": "text", "text": "These images depict two different landmarks. Can you identify them?"},
... ],
... },
... ]
>>> inputs = processor.apply_chat_template(messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt").to(torch_device)
>>> generate_ids = model.generate(**inputs, max_new_tokens=200)
>>> print(processor.decode(generate_ids[0, inputs["input_ids"].shape[1] :], skip_special_tokens=True))
The images depict the Statue of Liberty and the Golden Gate Bridge.
```"""
super().forward(**super_kwargs)
__all__ = [
"InternVLVisionPreTrainedModel",
"InternVLVisionModel",
"InternVLPreTrainedModel",
"InternVLModel",
"InternVLForConditionalGeneration",
]
| InternVLForConditionalGeneration |
python | astropy__astropy | astropy/coordinates/attributes.py | {
"start": 10190,
"end": 13491
} | class ____(Attribute):
"""
A frame attribute that is a quantity with specified units and shape
(optionally).
Can be `None`, which should be used for special cases in associated
frame transformations like "this quantity should be ignored" or similar.
Parameters
----------
default : number or `~astropy.units.Quantity` or None, optional
Default value for the attribute if the user does not supply one. If a
Quantity, it must be consistent with ``unit``, or if a value, ``unit``
cannot be None.
secondary_attribute : str, optional
Name of a secondary instance attribute which supplies the value if
``default is None`` and no value was supplied during initialization.
unit : unit-like or None, optional
Name of a unit that the input will be converted into. If None, no
unit-checking or conversion is performed
shape : tuple or None, optional
If given, specifies the shape the attribute must be
doc : str
Description of the frame attribute for help and documentation
"""
def __init__(
self, default=None, secondary_attribute="", unit=None, shape=None, **kwargs
):
if default is None and unit is None:
raise ValueError(
"Either a default quantity value must be provided, or a unit must "
"be provided to define a QuantityAttribute."
)
if default is not None and unit is None:
unit = default.unit
self.unit = unit
self.shape = shape
default = self.convert_input(default)[0]
super().__init__(default, secondary_attribute, **kwargs)
def convert_input(self, value):
"""
Checks that the input is a Quantity with the necessary units (or the
special value ``0``).
Parameters
----------
value : object
Input value to be converted.
Returns
-------
out, converted : correctly-typed object, boolean
Tuple consisting of the correctly-typed object and a boolean which
indicates if conversion was actually performed.
Raises
------
ValueError
If the input is not valid for this attribute.
"""
if value is None:
return None, False
if (
not hasattr(value, "unit")
and self.unit != u.dimensionless_unscaled
and np.any(value != 0)
):
raise TypeError(
"Tried to set a QuantityAttribute with "
"something that does not have a unit."
)
oldvalue = value
value = u.Quantity(oldvalue, self.unit, copy=COPY_IF_NEEDED)
if self.shape is not None and value.shape != self.shape:
if value.shape == () and oldvalue == 0:
# Allow a single 0 to fill whatever shape is needed.
value = np.broadcast_to(value, self.shape, subok=True)
else:
raise ValueError(
f'The provided value has shape "{value.shape}", but '
f'should have shape "{self.shape}"'
)
converted = oldvalue is not value
return value, converted
| QuantityAttribute |
python | vyperlang__vyper | vyper/ast/nodes.py | {
"start": 39184,
"end": 39259
} | class ____(Stmt):
__slots__ = ("target", "annotation", "value")
| AnnAssign |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 989741,
"end": 990186
} | class ____(sgqlc.types.Type):
"""Represents a count of the state of a status context."""
__schema__ = github_schema
__field_names__ = ("count", "state")
count = sgqlc.types.Field(sgqlc.types.non_null(Int), graphql_name="count")
"""The number of statuses with this state."""
state = sgqlc.types.Field(sgqlc.types.non_null(StatusState), graphql_name="state")
"""The state of a status context."""
| StatusContextStateCount |
python | huggingface__transformers | src/transformers/generation/logits_process.py | {
"start": 39850,
"end": 43117
} | class ____(LogitsProcessor):
r"""
[`LogitsProcessor`] that performs epsilon-sampling, i.e. restricting to tokens with `prob >= epsilon`. Takes the
largest min_tokens_to_keep tokens if no tokens satisfy this constraint. See [Truncation Sampling as Language Model
Desmoothing](https://huggingface.co/papers/2210.15191) for more information.
Args:
epsilon (`float`):
If set to > 0, only the most tokens with probabilities `epsilon` or higher are kept for generation.
filter_value (`float`, *optional*, defaults to -inf):
All filtered values will be set to this float value.
min_tokens_to_keep (`int`, *optional*, defaults to 1):
Minimum number of tokens that cannot be filtered.
Examples:
```python
>>> from transformers import AutoTokenizer, AutoModelForCausalLM, set_seed
>>> set_seed(1)
>>> model = AutoModelForCausalLM.from_pretrained("distilbert/distilgpt2")
>>> tokenizer = AutoTokenizer.from_pretrained("distilbert/distilgpt2")
>>> inputs = tokenizer("A sequence: 1, 2", return_tensors="pt")
>>> # With sampling, the output is unexpected -- sometimes too unexpected.
>>> outputs = model.generate(**inputs, do_sample=True)
>>> print(tokenizer.batch_decode(outputs, skip_special_tokens=True)[0])
A sequence: 1, 2, 3 | < 4 (left-hand pointer) ;
<BLANKLINE>
<BLANKLINE>
>>> # With epsilon sampling, the output gets restricted to high-probability tokens. Note that this is similar to
>>> # Top P sampling, which restricts tokens based on their cumulative probability.
>>> # Pro tip: The paper recommends using `epsilon_cutoff` values between 3e-4 and 9e-4
>>> outputs = model.generate(**inputs, do_sample=True, epsilon_cutoff=0.1)
>>> print(tokenizer.batch_decode(outputs, skip_special_tokens=True)[0])
A sequence: 1, 2, 3, 4, 5, 6, 7, 8, 9
```
"""
def __init__(self, epsilon: float, filter_value: float = -float("Inf"), min_tokens_to_keep: int = 1):
epsilon = float(epsilon)
if epsilon <= 0 or epsilon >= 1:
raise ValueError(f"`epsilon_cutoff` has to be a float > 0 and < 1, but is {epsilon}")
min_tokens_to_keep = int(min_tokens_to_keep)
if min_tokens_to_keep < 1:
raise ValueError(
f"`min_tokens_to_keep` has to be a strictly positive integer, but is {min_tokens_to_keep}"
)
self.epsilon = epsilon
self.filter_value = filter_value
self.min_tokens_to_keep = min_tokens_to_keep
@add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING)
def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
# Determine which indices to remove
probabilities = scores.softmax(dim=-1)
indices_to_remove = probabilities < self.epsilon
# Keep the words with the 'min_tokens_to_keep'-highest probabilities
top_k = min(self.min_tokens_to_keep, scores.size(-1)) # Safety check
indices_to_remove = indices_to_remove & (scores < torch.topk(scores, top_k)[0][..., -1, None])
scores_processed = scores.masked_fill(indices_to_remove, self.filter_value)
return scores_processed
| EpsilonLogitsWarper |
python | huggingface__transformers | src/transformers/models/chinese_clip/modeling_chinese_clip.py | {
"start": 14345,
"end": 15063
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
hidden_states = self.dense(hidden_states)
hidden_states = self.dropout(hidden_states)
hidden_states = self.LayerNorm(hidden_states + input_tensor)
return hidden_states
# Copied from transformers.models.align.modeling_align.AlignTextAttention with Align->ChineseCLIP
| ChineseCLIPTextSelfOutput |
python | plotly__plotly.py | _plotly_utils/png.py | {
"start": 10571,
"end": 10716
} | class ____(Error):
"""
Problem with the way the programming interface has been used,
or the data presented to it.
"""
| ProtocolError |
python | walkccc__LeetCode | solutions/25. Reverse Nodes in k-Group/25-2.py | {
"start": 0,
"end": 597
} | class ____:
def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
if not head or k == 1:
return head
def getLength(head: ListNode) -> int:
length = 0
while head:
length += 1
head = head.next
return length
length = getLength(head)
dummy = ListNode(0, head)
prev = dummy
curr = head
for _ in range(length // k):
for _ in range(k - 1):
next = curr.next
curr.next = next.next
next.next = prev.next
prev.next = next
prev = curr
curr = curr.next
return dummy.next
| Solution |
python | PrefectHQ__prefect | src/integrations/prefect-azure/prefect_azure/workers/container_instance.py | {
"start": 18895,
"end": 19025
} | class ____(BaseWorkerResult):
"""Contains information about the final state of a completed process"""
| AzureContainerWorkerResult |
python | dask__dask | dask/dataframe/dask_expr/_reductions.py | {
"start": 44575,
"end": 44810
} | class ____(MemoryUsageFrame):
reduction_chunk = total_mem_usage
@staticmethod
def reduction_combine(x, is_dataframe):
return x
@staticmethod
def reduction_aggregate(x):
return x
| TotalMemoryUsageFrame |
python | redis__redis-py | redis/asyncio/multidb/failover.py | {
"start": 1833,
"end": 3635
} | class ____(FailoverStrategyExecutor):
"""
Executes given failover strategy.
"""
def __init__(
self,
strategy: AsyncFailoverStrategy,
failover_attempts: int = DEFAULT_FAILOVER_ATTEMPTS,
failover_delay: float = DEFAULT_FAILOVER_DELAY,
):
self._strategy = strategy
self._failover_attempts = failover_attempts
self._failover_delay = failover_delay
self._next_attempt_ts: int = 0
self._failover_counter: int = 0
@property
def failover_attempts(self) -> int:
return self._failover_attempts
@property
def failover_delay(self) -> float:
return self._failover_delay
@property
def strategy(self) -> AsyncFailoverStrategy:
return self._strategy
async def execute(self) -> AsyncDatabase:
try:
database = await self._strategy.database()
self._reset()
return database
except NoValidDatabaseException as e:
if self._next_attempt_ts == 0:
self._next_attempt_ts = time.time() + self._failover_delay
self._failover_counter += 1
elif time.time() >= self._next_attempt_ts:
self._next_attempt_ts += self._failover_delay
self._failover_counter += 1
if self._failover_counter > self._failover_attempts:
self._reset()
raise e
else:
raise TemporaryUnavailableException(
"No database connections currently available. "
"This is a temporary condition - please retry the operation."
)
def _reset(self) -> None:
self._next_attempt_ts = 0
self._failover_counter = 0
| DefaultFailoverStrategyExecutor |
python | zarr-developers__zarr-python | tests/test_dtype/test_npy/test_int.py | {
"start": 1063,
"end": 2013
} | class ____(BaseTestZDType):
test_cls = Int16
scalar_type = np.int16
valid_dtype = (np.dtype(">i2"), np.dtype("<i2"))
invalid_dtype = (
np.dtype(np.int8),
np.dtype(np.uint16),
np.dtype(np.float64),
)
valid_json_v2 = (
{"name": ">i2", "object_codec_id": None},
{"name": "<i2", "object_codec_id": None},
)
valid_json_v3 = ("int16",)
invalid_json_v2 = (
"|i2",
"int16",
"|f8",
)
invalid_json_v3 = (
"|i2",
"|f8",
{"name": "int16", "configuration": {"endianness": "little"}},
)
scalar_v2_params = ((Int16(), 1), (Int16(), -1), (Int16(), 1.0))
scalar_v3_params = ((Int16(), 1), (Int16(), -1))
cast_value_params = (
(Int16(), 1, np.int16(1)),
(Int16(), -1, np.int16(-1)),
)
invalid_scalar_params = ((Int16(), {"set!"}), (Int16(), ("tuple",)))
item_size_params = (Int16(),)
| TestInt16 |
python | pytorch__pytorch | test/lazy/test_debug_util.py | {
"start": 312,
"end": 1441
} | class ____(TestCase):
def _run_linear(self):
device = "lazy"
model = nn.Linear(5, 5).to(device)
output = model(torch.randn(1, 5).to(device)) # noqa: F841
torch._lazy.mark_step()
def test_get_python_frames(self):
# We only care about the first "Python Stacktrace" part of the saved
# graph. However, we cannot save the whole stack for comparison given
# it depends on a lot of things.
partial_graph = (
r"Python Stacktrace:.*"
r"mark_step \(.*/_lazy/__init__.py:[0-9]+\).*"
r"_run_linear \(.*lazy/test_debug_util.py:[0-9]+\).*"
r"test_get_python_frames \(.*lazy/test_debug_util.py:[0-9]+\)"
)
with tempfile.NamedTemporaryFile(mode="r+", encoding="utf-8") as graph_file:
os.environ["LTC_SAVE_TENSORS_FILE"] = graph_file.name
self._run_linear()
file = graph_file.read()
if re.search(partial_graph, file, re.DOTALL) is None:
print(file)
self.assertTrue(False)
if __name__ == "__main__":
run_tests()
| DebugUtilTest |
python | kamyu104__LeetCode-Solutions | Python/convex-polygon.py | {
"start": 29,
"end": 600
} | class ____(object):
def isConvex(self, points):
"""
:type points: List[List[int]]
:rtype: bool
"""
def det(A):
return A[0][0]*A[1][1] - A[0][1]*A[1][0]
n, prev, curr = len(points), 0, None
for i in xrange(len(points)):
A = [[points[(i+j) % n][0] - points[i][0], points[(i+j) % n][1] - points[i][1]] for j in (1, 2)]
curr = det(A)
if curr:
if curr * prev < 0:
return False
prev = curr
return True
| Solution |
python | langchain-ai__langchain | libs/langchain_v1/tests/unit_tests/agents/test_response_format.py | {
"start": 24429,
"end": 29008
} | class ____:
"""Test response_format with middleware that modifies the model."""
def test_middleware_model_swap_provider_to_tool_strategy(self) -> None:
"""Test that strategy resolution is deferred until after middleware modifies the model.
Verifies that when a raw schema is provided, `_supports_provider_strategy` is called
on the middleware-modified model (not the original), ensuring the correct strategy is
selected based on the final model's capabilities.
"""
from unittest.mock import patch
from langchain.agents.middleware.types import AgentMiddleware, ModelRequest
from langchain_core.language_models.fake_chat_models import GenericFakeChatModel
# Custom model that we'll use to test whether the tool strategy is applied
# correctly at runtime.
class CustomModel(GenericFakeChatModel):
tool_bindings: list[Any] = []
def bind_tools(
self,
tools: Sequence[Union[dict[str, Any], type[BaseModel], Callable, BaseTool]],
**kwargs: Any,
) -> Runnable[LanguageModelInput, BaseMessage]:
# Record every tool binding event.
self.tool_bindings.append(tools)
return self
model = CustomModel(
messages=iter(
[
# Simulate model returning structured output directly
# (this is what provider strategy would do)
json.dumps(WEATHER_DATA),
]
)
)
# Create middleware that swaps the model in the request
class ModelSwappingMiddleware(AgentMiddleware):
def wrap_model_call(
self,
request: ModelRequest,
handler: Callable[[ModelRequest], CoreAIMessage],
) -> CoreAIMessage:
# Replace the model with our custom test model
return handler(request.override(model=model))
# Track which model is checked for provider strategy support
calls = []
def mock_supports_provider_strategy(model, tools) -> bool:
"""Track which model is checked and return True for ProviderStrategy."""
calls.append(model)
return True
# Use raw Pydantic model (not wrapped in ToolStrategy or ProviderStrategy)
# This should auto-detect strategy based on model capabilities
agent = create_agent(
model=model,
tools=[],
# Raw schema - should auto-detect strategy
response_format=WeatherBaseModel,
middleware=[ModelSwappingMiddleware()],
)
with patch(
"langchain.agents.factory._supports_provider_strategy",
side_effect=mock_supports_provider_strategy,
):
response = agent.invoke({"messages": [HumanMessage("What's the weather?")]})
# Verify strategy resolution was deferred: check was called once during _get_bound_model
assert len(calls) == 1
# Verify successful parsing of JSON as structured output via ProviderStrategy
assert response["structured_response"] == EXPECTED_WEATHER_PYDANTIC
# Two messages: Human input message and AI response with JSON content
assert len(response["messages"]) == 2
ai_message = response["messages"][1]
assert isinstance(ai_message, AIMessage)
# ProviderStrategy doesn't use tool calls - it parses content directly
assert ai_message.tool_calls == []
assert ai_message.content == json.dumps(WEATHER_DATA)
def test_union_of_types() -> None:
"""Test response_format as ProviderStrategy with Union (if supported)."""
tool_calls = [
[{"args": {}, "id": "1", "name": "get_weather"}],
[
{
"name": "WeatherBaseModel",
"id": "2",
"args": WEATHER_DATA,
}
],
]
model = FakeToolCallingModel[Union[WeatherBaseModel, LocationResponse]](
tool_calls=tool_calls, structured_response=EXPECTED_WEATHER_PYDANTIC
)
agent = create_agent(
model,
[get_weather, get_location],
response_format=ToolStrategy(Union[WeatherBaseModel, LocationResponse]),
)
response = agent.invoke({"messages": [HumanMessage("What's the weather?")]})
assert response["structured_response"] == EXPECTED_WEATHER_PYDANTIC
assert len(response["messages"]) == 5
| TestDynamicModelWithResponseFormat |
python | keras-team__keras | guides/making_new_layers_and_models_via_subclassing.py | {
"start": 4076,
"end": 5430
} | class ____(keras.layers.Layer):
def __init__(self, units=32):
super().__init__()
self.units = units
def build(self, input_shape):
self.w = self.add_weight(
shape=(input_shape[-1], self.units),
initializer="random_normal",
trainable=True,
)
self.b = self.add_weight(
shape=(self.units,), initializer="random_normal", trainable=True
)
def call(self, inputs):
return ops.matmul(inputs, self.w) + self.b
"""
The `__call__()` method of your layer will automatically run build the first time
it is called. You now have a layer that's lazy and thus easier to use:
"""
# At instantiation, we don't know on what inputs this is going to get called
linear_layer = Linear(32)
# The layer's weights are created dynamically the first time the layer is called
y = linear_layer(x)
"""
Implementing `build()` separately as shown above nicely separates creating weights
only once from using weights in every call.
"""
"""
## Layers are recursively composable
If you assign a Layer instance as an attribute of another Layer, the outer layer
will start tracking the weights created by the inner layer.
We recommend creating such sublayers in the `__init__()` method and leave it to
the first `__call__()` to trigger building their weights.
"""
| Linear |
python | pypa__warehouse | tests/unit/accounts/test_views.py | {
"start": 6906,
"end": 9095
} | class ____:
def test_unauthenticated_raises_401(self):
pyramid_request = pretend.stub(user=None)
with pytest.raises(HTTPUnauthorized):
views.accounts_search(pyramid_request)
def test_no_query_string_raises_400(self):
pyramid_request = pretend.stub(user=pretend.stub(), params=MultiDict({}))
with pytest.raises(HTTPBadRequest):
views.accounts_search(pyramid_request)
def test_returns_users_with_prefix(self, db_session, user_service):
foo = UserFactory.create(username="foo")
bas = [
UserFactory.create(username="bar"),
UserFactory.create(username="baz"),
]
request = pretend.stub(
user=pretend.stub(),
find_service=lambda svc, **kw: {
IUserService: user_service,
IRateLimiter: pretend.stub(
test=pretend.call_recorder(lambda ip_address: True),
hit=pretend.call_recorder(lambda ip_address: None),
),
}[svc],
ip_address=IpAddressFactory.build(),
)
request.params = MultiDict({"username": "f"})
result = views.accounts_search(request)
assert result == {"users": [foo]}
request.params = MultiDict({"username": "ba"})
result = views.accounts_search(request)
assert result == {"users": bas}
request.params = MultiDict({"username": "zzz"})
with pytest.raises(HTTPNotFound):
views.accounts_search(request)
def test_when_rate_limited(self, db_session):
search_limiter = pretend.stub(
test=pretend.call_recorder(lambda ip_address: False),
)
request = pretend.stub(
user=pretend.stub(),
find_service=lambda svc, **kw: {
IRateLimiter: search_limiter,
}[svc],
ip_address=IpAddressFactory.build(),
)
request.params = MultiDict({"username": "foo"})
result = views.accounts_search(request)
assert search_limiter.test.calls == [pretend.call(request.ip_address)]
assert result == {"users": []}
| TestAccountsSearch |
python | run-llama__llama_index | llama-index-core/llama_index/core/postprocessor/node.py | {
"start": 9102,
"end": 12628
} | class ____(BaseNodePostprocessor):
"""
Previous/Next Node post-processor.
Allows users to fetch additional nodes from the document store,
based on the prev/next relationships of the nodes.
NOTE: difference with PrevNextPostprocessor is that
this infers forward/backwards direction.
NOTE: this is a beta feature.
Args:
docstore (BaseDocumentStore): The document store.
num_nodes (int): The number of nodes to return (default: 1)
infer_prev_next_tmpl (str): The template to use for inference.
Required fields are {context_str} and {query_str}.
"""
model_config = ConfigDict(arbitrary_types_allowed=True)
docstore: BaseDocumentStore
llm: Optional[SerializeAsAny[LLM]] = None
num_nodes: int = Field(default=1)
infer_prev_next_tmpl: str = Field(default=DEFAULT_INFER_PREV_NEXT_TMPL)
refine_prev_next_tmpl: str = Field(default=DEFAULT_REFINE_INFER_PREV_NEXT_TMPL)
verbose: bool = Field(default=False)
response_mode: ResponseMode = Field(default=ResponseMode.COMPACT)
@classmethod
def class_name(cls) -> str:
return "AutoPrevNextNodePostprocessor"
def _parse_prediction(self, raw_pred: str) -> str:
"""Parse prediction."""
pred = raw_pred.strip().lower()
if "previous" in pred:
return "previous"
elif "next" in pred:
return "next"
elif "none" in pred:
return "none"
raise ValueError(f"Invalid prediction: {raw_pred}")
def _postprocess_nodes(
self,
nodes: List[NodeWithScore],
query_bundle: Optional[QueryBundle] = None,
) -> List[NodeWithScore]:
"""Postprocess nodes."""
llm = self.llm or Settings.llm
if query_bundle is None:
raise ValueError("Missing query bundle.")
infer_prev_next_prompt = PromptTemplate(
self.infer_prev_next_tmpl,
)
refine_infer_prev_next_prompt = PromptTemplate(self.refine_prev_next_tmpl)
all_nodes: Dict[str, NodeWithScore] = {}
for node in nodes:
all_nodes[node.node.node_id] = node
# use response builder instead of llm directly
# to be more robust to handling long context
response_builder = get_response_synthesizer(
llm=llm,
text_qa_template=infer_prev_next_prompt,
refine_template=refine_infer_prev_next_prompt,
response_mode=self.response_mode,
)
raw_pred = response_builder.get_response(
text_chunks=[node.node.get_content()],
query_str=query_bundle.query_str,
)
raw_pred = cast(str, raw_pred)
mode = self._parse_prediction(raw_pred)
logger.debug(f"> Postprocessor Predicted mode: {mode}")
if self.verbose:
print(f"> Postprocessor Predicted mode: {mode}")
if mode == "next":
all_nodes.update(get_forward_nodes(node, self.num_nodes, self.docstore))
elif mode == "previous":
all_nodes.update(
get_backward_nodes(node, self.num_nodes, self.docstore)
)
elif mode == "none":
pass
else:
raise ValueError(f"Invalid mode: {mode}")
sorted_nodes = sorted(all_nodes.values(), key=lambda x: x.node.node_id)
return list(sorted_nodes)
| AutoPrevNextNodePostprocessor |
python | getsentry__sentry | tests/sentry/api/endpoints/test_debug_files.py | {
"start": 13699,
"end": 16436
} | class ____(DebugFilesTestCases):
def setUp(self) -> None:
super().setUp()
self.associate_url = reverse(
"sentry-api-0-associate-dsym-files",
kwargs={
"organization_id_or_slug": self.organization.slug,
"project_id_or_slug": self.project.slug,
},
)
def test_associate_proguard_dsym(self) -> None:
response = self._upload_proguard(self.url, PROGUARD_UUID)
assert response.status_code == 201, response.content
assert len(response.data) == 1
assert response.data[0]["headers"] == {"Content-Type": "text/x-proguard+plain"}
assert response.data[0]["sha1"] == "e6d3c5185dac63eddfdc1a5edfffa32d46103b44"
assert response.data[0]["uuid"] == PROGUARD_UUID
assert response.data[0]["objectName"] == "proguard-mapping"
assert response.data[0]["cpuName"] == "any"
assert response.data[0]["symbolType"] == "proguard"
response = self.client.post(
self.associate_url,
{
"checksums": ["e6d3c5185dac63eddfdc1a5edfffa32d46103b44"],
"platform": "android",
"name": "MyApp",
"appId": "com.example.myapp",
"version": "1.0",
"build": "1",
},
format="json",
)
assert response.status_code == 200, response.content
assert "associatedDsymFiles" in response.data
assert response.data["associatedDsymFiles"] == []
def test_associate_proguard_dsym_no_build(self) -> None:
response = self._upload_proguard(self.url, PROGUARD_UUID)
assert response.status_code == 201, response.content
assert len(response.data) == 1
assert response.data[0]["headers"] == {"Content-Type": "text/x-proguard+plain"}
assert response.data[0]["sha1"] == "e6d3c5185dac63eddfdc1a5edfffa32d46103b44"
assert response.data[0]["uuid"] == PROGUARD_UUID
assert response.data[0]["objectName"] == "proguard-mapping"
assert response.data[0]["cpuName"] == "any"
assert response.data[0]["symbolType"] == "proguard"
response = self.client.post(
self.associate_url,
{
"checksums": ["e6d3c5185dac63eddfdc1a5edfffa32d46103b44"],
"platform": "android",
"name": "MyApp",
"appId": "com.example.myapp",
"version": "1.0",
},
format="json",
)
assert response.status_code == 200, response.content
assert "associatedDsymFiles" in response.data
assert response.data["associatedDsymFiles"] == []
| AssociateDebugFilesTest |
python | getsentry__sentry | src/sentry/uptime/endpoints/validators.py | {
"start": 13242,
"end": 16444
} | class ____(BaseDataSourceValidator[UptimeSubscription]):
@property
def data_source_type_handler(self) -> type[UptimeSubscriptionDataSourceHandler]:
return UptimeSubscriptionDataSourceHandler
url = URLField(required=True, max_length=255)
interval_seconds = serializers.ChoiceField(
required=True,
choices=UptimeSubscription.IntervalSeconds.choices,
help_text="Time in seconds between uptime checks.",
)
timeout_ms = serializers.IntegerField(
required=True,
min_value=1000,
max_value=60_000,
help_text="The number of milliseconds the request will wait for a response before timing-out.",
)
method = serializers.ChoiceField(
required=False,
choices=UptimeSubscription.SupportedHTTPMethods.choices,
help_text="The HTTP method used to make the check request.",
)
headers = serializers.JSONField(
required=False,
help_text="Additional headers to send with the check request.",
)
trace_sampling = serializers.BooleanField(
required=False,
default=False,
help_text="When enabled allows check requets to be considered for dowstream performance tracing.",
)
body = serializers.CharField(
required=False,
allow_null=True,
help_text="The body to send with the check request.",
)
class Meta:
model = UptimeSubscription
fields = [
"url",
"headers",
"timeout_ms",
"method",
"trace_sampling",
"body",
"interval_seconds",
]
def validate_url(self, url):
return _validate_url(url)
def validate_headers(self, headers):
return _validate_headers(headers)
def validate_mode(self, mode):
return _validate_mode(mode, self.context["request"])
def validate(self, attrs: dict[str, Any]):
attrs = super().validate(attrs)
headers = []
method = "GET"
body = None
url = ""
if self.instance:
headers = self.instance.headers
method = self.instance.method
body = self.instance.body
url = self.instance.url
_validate_request_size(
attrs.get("method", method),
attrs.get("url", url),
attrs.get("headers", headers),
attrs.get("body", body),
)
return attrs
@override
def create_source(self, validated_data: dict[str, Any]) -> UptimeSubscription:
with atomic_transaction(using=(router.db_for_write(UptimeSubscription),)):
uptime_subscription = create_uptime_subscription(
url=validated_data["url"],
interval_seconds=validated_data["interval_seconds"],
timeout_ms=validated_data["timeout_ms"],
trace_sampling=validated_data.get("trace_sampling", False),
method=validated_data.get("method", "GET"),
headers=validated_data.get("headers", None),
body=validated_data.get("body", None),
)
return uptime_subscription
| UptimeMonitorDataSourceValidator |
python | openai__openai-python | src/openai/types/shared/function_definition.py | {
"start": 237,
"end": 1475
} | class ____(BaseModel):
name: str
"""The name of the function to be called.
Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length
of 64.
"""
description: Optional[str] = None
"""
A description of what the function does, used by the model to choose when and
how to call the function.
"""
parameters: Optional[FunctionParameters] = None
"""The parameters the functions accepts, described as a JSON Schema object.
See the [guide](https://platform.openai.com/docs/guides/function-calling) for
examples, and the
[JSON Schema reference](https://json-schema.org/understanding-json-schema/) for
documentation about the format.
Omitting `parameters` defines a function with an empty parameter list.
"""
strict: Optional[bool] = None
"""Whether to enable strict schema adherence when generating the function call.
If set to true, the model will follow the exact schema defined in the
`parameters` field. Only a subset of JSON Schema is supported when `strict` is
`true`. Learn more about Structured Outputs in the
[function calling guide](https://platform.openai.com/docs/guides/function-calling).
"""
| FunctionDefinition |
python | getsentry__sentry | src/sentry/workflow_engine/typings/notification_action.py | {
"start": 10238,
"end": 10920
} | class ____(BaseActionTranslator):
@property
def action_type(self) -> ActionType:
return ActionType.DISCORD
@property
def required_fields(self) -> list[str]:
return [
ACTION_FIELD_MAPPINGS[ActionType.DISCORD][
ActionFieldMappingKeys.INTEGRATION_ID_KEY.value
],
ACTION_FIELD_MAPPINGS[ActionType.DISCORD][
ActionFieldMappingKeys.TARGET_IDENTIFIER_KEY.value
],
]
@property
def target_type(self) -> int:
return ActionTarget.SPECIFIC.value
@property
def blob_type(self) -> type[DataBlob]:
return DiscordDataBlob
| DiscordActionTranslator |
python | astropy__astropy | astropy/io/fits/hdu/base.py | {
"start": 28436,
"end": 30911
} | class ____(_BaseHDU, _Verify):
"""
A Non-standard HDU class.
This class is used for a Primary HDU when the ``SIMPLE`` Card has
a value of `False`. A non-standard HDU comes from a file that
resembles a FITS file but departs from the standards in some
significant way. One example would be files where the numbers are
in the DEC VAX internal storage format rather than the standard
FITS most significant byte first. The header for this HDU should
be valid. The data for this HDU is read from the file as a byte
stream that begins at the first byte after the header ``END`` card
and continues until the end of the file.
"""
_standard = False
@classmethod
def match_header(cls, header):
"""
Matches any HDU that has the 'SIMPLE' keyword but is not a standard
Primary or Groups HDU.
"""
# The SIMPLE keyword must be in the first card
card = header.cards[0]
return card.keyword == "SIMPLE" and card.value is False
@property
def size(self):
"""
Returns the size (in bytes) of the HDU's data part.
"""
if self._buffer is not None:
return len(self._buffer) - self._data_offset
return self._file.size - self._data_offset
def _writedata(self, fileobj):
"""
Differs from the base class :class:`_writedata` in that it doesn't
automatically add padding, and treats the data as a string of raw bytes
instead of an array.
"""
offset = 0
size = 0
fileobj.flush()
try:
offset = fileobj.tell()
except OSError:
offset = 0
if self.data is not None:
fileobj.write(self.data)
# flush, to make sure the content is written
fileobj.flush()
size = len(self.data)
# return both the location and the size of the data area
return offset, size
def _summary(self):
return (self.name, self.ver, "NonstandardHDU", len(self._header))
@lazyproperty
def data(self):
"""
Return the file data.
"""
return self._get_raw_data(self.size, "ubyte", self._data_offset)
def _verify(self, option="warn"):
errs = _ErrList([], unit="Card")
# verify each card
for card in self._header.cards:
errs.append(card._verify(option))
return errs
| _NonstandardHDU |
python | simonw__datasette | datasette/filters.py | {
"start": 6949,
"end": 7201
} | class ____:
key = None
display = None
no_argument = False
def where_clause(self, table, column, value, param_counter):
raise NotImplementedError
def human_clause(self, column, value):
raise NotImplementedError
| Filter |
python | hyperopt__hyperopt | hyperopt/ipy.py | {
"start": 735,
"end": 7548
} | class ____(Trials):
def __init__(self, client, job_error_reaction="raise", save_ipy_metadata=True):
self._client = client
self._clientlbv = client.load_balanced_view()
self.job_map = {}
self.job_error_reaction = job_error_reaction
self.save_ipy_metadata = save_ipy_metadata
Trials.__init__(self)
self._testing_fmin_was_called = False
def _insert_trial_docs(self, docs):
rval = [doc["tid"] for doc in docs]
self._dynamic_trials.extend(docs)
return rval
def refresh(self):
job_map = {}
# -- carry over state for active engines
for eid in self._client.ids:
job_map[eid] = self.job_map.pop(eid, (None, None))
# -- deal with lost engines, abandoned promises
for eid, (p, tt) in list(self.job_map.items()):
if self.job_error_reaction == "raise":
raise LostEngineError(p)
elif self.job_error_reaction == "log":
tt["error"] = "LostEngineError (%s)" % str(p)
tt["state"] = JOB_STATE_ERROR
else:
raise ValueError(self.job_error_reaction)
# -- remove completed jobs from job_map
for eid, (p, tt) in list(job_map.items()):
if p is None:
continue
if p.ready():
try:
tt["result"] = p.get()
tt["state"] = JOB_STATE_DONE
job_map[eid] = (None, None)
except Exception as e:
if self.job_error_reaction == "raise":
raise
elif self.job_error_reaction == "log":
tt["error"] = str(e)
tt["state"] = JOB_STATE_ERROR
else:
raise ValueError(self.job_error_reaction)
if self.save_ipy_metadata:
tt["ipy_metadata"] = p.metadata
tt["refresh_time"] = coarse_utcnow()
del job_map[eid]
self.job_map = job_map
Trials.refresh(self)
def fmin(self, fn, space, **kw):
# TODO: all underscore variables are completely unused throughout.
algo = kw.get("algo")
max_evals = kw.get("max_evals")
rstate = kw.get("rstate", None)
_allow_trials_fmin = (True,)
_pass_expr_memo_ctrl = (None,)
_catch_eval_exceptions = (False,)
verbose = kw.get("verbose", 0)
_return_argmin = (True,)
wait = (True,)
pass_expr_memo_ctrl = (None,)
if rstate is None:
rstate = np.random
# -- used in test_ipy
self._testing_fmin_was_called = True
if pass_expr_memo_ctrl is None:
try:
pass_expr_memo_ctrl = fn.pass_expr_memo_ctrl
except AttributeError:
pass_expr_memo_ctrl = False
domain = Domain(fn, space, None, pass_expr_memo_ctrl=False)
last_print_time = 0
while len(self._dynamic_trials) < max_evals:
self.refresh()
if verbose and last_print_time + 1 < time():
print(
"fmin: %4i/%4i/%4i/%4i %f"
% (
self.count_by_state_unsynced(JOB_STATE_NEW),
self.count_by_state_unsynced(JOB_STATE_RUNNING),
self.count_by_state_unsynced(JOB_STATE_DONE),
self.count_by_state_unsynced(JOB_STATE_ERROR),
min(
[float("inf")] + [l for l in self.losses() if l is not None]
),
)
)
last_print_time = time()
idles = [eid for (eid, (p, tt)) in list(self.job_map.items()) if p is None]
if idles:
new_ids = self.new_trial_ids(len(idles))
new_trials = algo(new_ids, domain, self, rstate.integers(2**31 - 1))
if len(new_trials) == 0:
break
assert len(idles) >= len(new_trials)
for eid, new_trial in zip(idles, new_trials):
now = coarse_utcnow()
new_trial["book_time"] = now
new_trial["refresh_time"] = now
(tid,) = self.insert_trial_docs([new_trial])
promise = call_domain(
domain,
spec_from_misc(new_trial["misc"]),
Ctrl(self, current_trial=new_trial),
new_trial,
self._clientlbv,
eid,
tid,
)
# -- XXX bypassing checks because 'ar'
# is not ok for SONify... but should check
# for all else being SONify
tt = self._dynamic_trials[-1]
assert tt["tid"] == tid
self.job_map[eid] = (promise, tt)
tt["state"] = JOB_STATE_RUNNING
if wait:
if verbose:
print("fmin: Waiting on remaining jobs...")
self.wait(verbose=verbose)
return self.argmin
def wait(self, verbose=False, verbose_print_interval=1.0):
last_print_time = 0
while True:
self.refresh()
if verbose and last_print_time + verbose_print_interval < time():
print(
"fmin: %4i/%4i/%4i/%4i %f"
% (
self.count_by_state_unsynced(JOB_STATE_NEW),
self.count_by_state_unsynced(JOB_STATE_RUNNING),
self.count_by_state_unsynced(JOB_STATE_DONE),
self.count_by_state_unsynced(JOB_STATE_ERROR),
min(
[float("inf")] + [l for l in self.losses() if l is not None]
),
)
)
last_print_time = time()
if self.count_by_state_unsynced(JOB_STATE_NEW):
sleep(1e-1)
continue
if self.count_by_state_unsynced(JOB_STATE_RUNNING):
sleep(1e-1)
continue
break
def __getstate__(self):
rval = dict(self.__dict__)
del rval["_client"]
del rval["_trials"]
del rval["job_map"]
# print rval.keys()
return rval
def __setstate__(self, dct):
self.__dict__ = dct
self.job_map = {}
Trials.refresh(self)
# Monkey patching to allow the apply_async call and response to
# be handled on behalf of the domain.
| IPythonTrials |
python | tensorflow__tensorflow | tensorflow/python/distribute/values_test.py | {
"start": 11386,
"end": 12495
} | class ____(test.TestCase, parameterized.TestCase):
@combinations.generate(
combinations.combine(
distribution=[
strategy_combinations.mirrored_strategy_with_gpu_and_cpu,
strategy_combinations
.mirrored_strategy_with_two_gpus_no_merge_call,
strategy_combinations.tpu_strategy,
strategy_combinations.tpu_strategy_packed_var,
strategy_combinations.central_storage_strategy_with_two_gpus,
] + strategy_combinations.multiworker_strategies,
mode=["eager"]))
def testUsePerReplicaInvalidContextGivesError(self, distribution):
if not tf2.enabled():
self.skipTest("Only V2 is supported.")
multiple_values = range(distribution.num_replicas_in_sync)
def value_fn(ctx):
return multiple_values[ctx.replica_id_in_sync_group]
distributed_values = (
distribution.experimental_distribute_values_from_function(value_fn))
with self.assertRaisesRegex(ValueError, "not inside a replica context"):
math_ops.cast(distributed_values, dtypes.float32)
| PerReplicaTest |
python | pennersr__django-allauth | tests/apps/socialaccount/providers/questrade/tests.py | {
"start": 246,
"end": 550
} | class ____(OAuth2TestsMixin, TestCase):
provider_id = QuestradeProvider.id
def get_mocked_response(self):
return MockedResponse(
HTTPStatus.OK,
"""{"userId":400,"accounts":[]}""",
)
def get_expected_to_str(self):
return "Questrade"
| QuestradeTests |
python | ray-project__ray | python/ray/data/_internal/datasource/sql_datasink.py | {
"start": 281,
"end": 1251
} | class ____(Datasink[None]):
_MAX_ROWS_PER_WRITE = 128
def __init__(self, sql: str, connection_factory: Callable[[], Connection]):
self.sql = sql
self.connection_factory = connection_factory
def write(
self,
blocks: Iterable[Block],
ctx: TaskContext,
) -> None:
with _connect(self.connection_factory) as cursor:
for block in blocks:
block_accessor = BlockAccessor.for_block(block)
values = []
for row in block_accessor.iter_rows(public_row_format=False):
values.append(tuple(row.values()))
assert len(values) <= self._MAX_ROWS_PER_WRITE, len(values)
if len(values) == self._MAX_ROWS_PER_WRITE:
cursor.executemany(self.sql, values)
values = []
if values:
cursor.executemany(self.sql, values)
| SQLDatasink |
python | django__django | django/forms/boundfield.py | {
"start": 12216,
"end": 13373
} | class ____:
"""
A container class used for iterating over widgets. This is useful for
widgets that have choices. For example, the following can be used in a
template:
{% for radio in myform.beatles %}
<label for="{{ radio.id_for_label }}">
{{ radio.choice_label }}
<span class="radio">{{ radio.tag }}</span>
</label>
{% endfor %}
"""
def __init__(self, parent_widget, data, renderer):
self.parent_widget = parent_widget
self.data = data
self.renderer = renderer
def __str__(self):
return self.tag(wrap_label=True)
def tag(self, wrap_label=False):
context = {"widget": {**self.data, "wrap_label": wrap_label}}
return self.parent_widget._render(self.template_name, context, self.renderer)
@property
def template_name(self):
if "template_name" in self.data:
return self.data["template_name"]
return self.parent_widget.template_name
@property
def id_for_label(self):
return self.data["attrs"].get("id")
@property
def choice_label(self):
return self.data["label"]
| BoundWidget |
python | django__django | django/test/utils.py | {
"start": 1806,
"end": 2970
} | class ____(list):
"""
A wrapper that provides direct key access to context items contained
in a list of context objects.
"""
def __getitem__(self, key):
if isinstance(key, str):
for subcontext in self:
if key in subcontext:
return subcontext[key]
raise KeyError(key)
else:
return super().__getitem__(key)
def get(self, key, default=None):
try:
return self.__getitem__(key)
except KeyError:
return default
def __contains__(self, key):
try:
self[key]
except KeyError:
return False
return True
def keys(self):
"""
Flattened keys of subcontexts.
"""
return set(chain.from_iterable(d for subcontext in self for d in subcontext))
def instrumented_test_render(self, context):
"""
An instrumented Template render method, providing a signal that can be
intercepted by the test Client.
"""
template_rendered.send(sender=self, template=self, context=context)
return self.nodelist.render(context)
| ContextList |
python | huggingface__transformers | src/transformers/models/llava_next/modeling_llava_next.py | {
"start": 5984,
"end": 6978
} | class ____(BaseModelOutputWithPast):
r"""
past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
`past_key_values` input) to speed up sequential decoding.
image_hidden_states (`torch.FloatTensor`, *optional*):
A `torch.FloatTensor` of size `(batch_size, num_images, sequence_length, hidden_size)`.
image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
"""
image_hidden_states: Optional[torch.FloatTensor] = None
@dataclass
@auto_docstring(
custom_intro="""
Base class for LlavaNext causal language model (or autoregressive) outputs.
"""
)
| LlavaNextModelOutputWithPast |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/execution.py | {
"start": 430,
"end": 893
} | class ____(graphene.ObjectType):
name = graphene.NonNull(graphene.String)
class Meta:
name = "ExecutionStepOutput"
def __init__(self, step_output_snap):
super().__init__()
self._step_output_snap = check.inst_param(
step_output_snap, "step_output_snap", ExecutionStepOutputSnap
)
def resolve_name(self, _graphene_info: ResolveInfo):
return self._step_output_snap.name
| GrapheneExecutionStepOutput |
python | getsentry__sentry | src/sentry/new_migrations/monkey/state.py | {
"start": 344,
"end": 4700
} | class ____(ProjectState):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.pending_deletion_models: dict[tuple[str, str], type[Model]] = {}
self.pending_deletion_fields: dict[tuple[str, str, str], type[Field]] = {}
def get_pending_deletion_model(self, app_label: str, model_name: str) -> type[Model]:
model_key = (app_label.lower(), model_name.lower())
if model_key not in self.pending_deletion_models:
raise UnsafeOperationException(
"Model must be in the pending deletion state before full deletion. "
"More info: https://develop.sentry.dev/api-server/application-domains/database-migrations/#deleting-tables"
)
return self.pending_deletion_models[model_key]
def get_pending_deletion_field(
self, app_label: str, model_name: str, field_name: str
) -> type[Field]:
field_key = (app_label.lower(), model_name.lower(), field_name.lower())
if field_key not in self.pending_deletion_fields:
raise UnsafeOperationException(
"Field must be in the pending deletion state before full deletion. "
"More info: https://develop.sentry.dev/api-server/application-domains/database-migrations/#deleting-columns"
)
return self.pending_deletion_fields[field_key]
def remove_model(
self, app_label: str, model_name: str, deletion_action: DeletionAction | None = None
) -> None:
model_key = (app_label.lower(), model_name.lower())
if deletion_action == DeletionAction.DELETE:
if model_key not in self.pending_deletion_models:
raise UnsafeOperationException(
"Model must be in the pending deletion state before full deletion. "
"More info: https://develop.sentry.dev/api-server/application-domains/database-migrations/#deleting-tables"
)
del self.pending_deletion_models[model_key]
return
if deletion_action == DeletionAction.MOVE_TO_PENDING:
if model_key in self.pending_deletion_models:
raise UnsafeOperationException(
f"{app_label}.{model_name} is already pending deletion. Use DeletionAction.DELETE to delete"
"More info: https://develop.sentry.dev/api-server/application-domains/database-migrations/#deleting-tables"
)
self.pending_deletion_models[model_key] = self.apps.get_model(app_label, model_name)
super().remove_model(app_label, model_name)
def remove_field(
self,
app_label: str,
model_name: str,
name: str,
deletion_action: DeletionAction | None = None,
):
field_key = app_label.lower(), model_name.lower(), name.lower()
if deletion_action == DeletionAction.DELETE:
if field_key not in self.pending_deletion_fields:
raise UnsafeOperationException(
"Field must be in the pending deletion state before full deletion. "
"More info: https://develop.sentry.dev/api-server/application-domains/database-migrations/#deleting-columns"
)
del self.pending_deletion_fields[field_key]
return
if deletion_action == DeletionAction.MOVE_TO_PENDING:
if field_key in self.pending_deletion_fields:
raise UnsafeOperationException(
f"{app_label}.{model_name}.{name} is already pending deletion. Use DeletionAction.DELETE to delete"
"More info: https://develop.sentry.dev/api-server/application-domains/database-migrations/#deleting-columns"
)
self.pending_deletion_fields[field_key] = self.apps.get_model(
app_label, model_name
)._meta.get_field(name)
super().remove_field(app_label, model_name, name)
def clone(self) -> SentryProjectState:
new_state = super().clone()
new_state.pending_deletion_models = deepcopy(self.pending_deletion_models) # type: ignore[attr-defined]
new_state.pending_deletion_fields = deepcopy(self.pending_deletion_fields) # type: ignore[attr-defined]
return new_state # type: ignore[return-value]
| SentryProjectState |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/memberAccess10.py | {
"start": 422,
"end": 713
} | class ____:
number_cls = IntDescriptorClass
reveal_type(X.number_cls, expected_text="int")
reveal_type(X().number_cls, expected_text="int")
X.number_cls = "hi"
X().number_cls = "hi"
# This should generate an error
X.number_cls = 1
# This should generate an error
X().number_cls = 1
| X |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/tryceratops/TRY004.py | {
"start": 363,
"end": 5455
} | class ____:
pass
def incorrect_with_issubclass(some_arg):
if issubclass(some_arg, MyClass):
pass
else:
raise Exception("...") # should be typeerror
def incorrect_with_callable(some_arg):
if callable(some_arg):
pass
else:
raise Exception("...") # should be typeerror
def incorrect_ArithmeticError(some_arg):
if isinstance(some_arg, int):
pass
else:
raise ArithmeticError("...") # should be typeerror
def incorrect_AssertionError(some_arg):
if isinstance(some_arg, int):
pass
else:
raise AssertionError("...") # should be typeerror
def incorrect_AttributeError(some_arg):
if isinstance(some_arg, int):
pass
else:
raise AttributeError("...") # should be typeerror
def incorrect_BufferError(some_arg):
if isinstance(some_arg, int):
pass
else:
raise BufferError # should be typeerror
def incorrect_EOFError(some_arg):
if isinstance(some_arg, int):
pass
else:
raise EOFError("...") # should be typeerror
def incorrect_ImportError(some_arg):
if isinstance(some_arg, int):
pass
else:
raise ImportError("...") # should be typeerror
def incorrect_LookupError(some_arg):
if isinstance(some_arg, int):
pass
else:
raise LookupError("...") # should be typeerror
def incorrect_MemoryError(some_arg):
if isinstance(some_arg, int):
pass
else:
# should be typeerror
# not multiline is on purpose for fix
raise MemoryError(
"..."
)
def incorrect_NameError(some_arg):
if isinstance(some_arg, int):
pass
else:
raise NameError("...") # should be typeerror
def incorrect_ReferenceError(some_arg):
if isinstance(some_arg, int):
pass
else:
raise ReferenceError("...") # should be typeerror
def incorrect_RuntimeError(some_arg):
if isinstance(some_arg, int):
pass
else:
raise RuntimeError("...") # should be typeerror
def incorrect_SyntaxError(some_arg):
if isinstance(some_arg, int):
pass
else:
raise SyntaxError("...") # should be typeerror
def incorrect_SystemError(some_arg):
if isinstance(some_arg, int):
pass
else:
raise SystemError("...") # should be typeerror
def incorrect_ValueError(some_arg):
if isinstance(some_arg, int):
pass
else:
raise ValueError("...") # should be typeerror
def incorrect_not_operator_isinstance(some_arg):
if not isinstance(some_arg):
pass
else:
raise Exception("...") # should be typeerror
def incorrect_and_operator_isinstance(arg1, arg2):
if isinstance(some_arg) and isinstance(arg2):
pass
else:
raise Exception("...") # should be typeerror
def incorrect_or_operator_isinstance(arg1, arg2):
if isinstance(some_arg) or isinstance(arg2):
pass
else:
raise Exception("...") # should be typeerror
def incorrect_multiple_operators_isinstance(arg1, arg2, arg3):
if not isinstance(arg1) and isinstance(arg2) or isinstance(arg3):
pass
else:
raise Exception("...") # should be typeerror
def incorrect_not_operator_callable(some_arg):
if not callable(some_arg):
pass
else:
raise Exception("...") # should be typeerror
def incorrect_and_operator_callable(arg1, arg2):
if callable(some_arg) and callable(arg2):
pass
else:
raise Exception("...") # should be typeerror
def incorrect_or_operator_callable(arg1, arg2):
if callable(some_arg) or callable(arg2):
pass
else:
raise Exception("...") # should be typeerror
def incorrect_multiple_operators_callable(arg1, arg2, arg3):
if not callable(arg1) and callable(arg2) or callable(arg3):
pass
else:
raise Exception("...") # should be typeerror
def incorrect_not_operator_issubclass(some_arg):
if not issubclass(some_arg):
pass
else:
raise Exception("...") # should be typeerror
def incorrect_and_operator_issubclass(arg1, arg2):
if issubclass(some_arg) and issubclass(arg2):
pass
else:
raise Exception("...") # should be typeerror
def incorrect_or_operator_issubclass(arg1, arg2):
if issubclass(some_arg) or issubclass(arg2):
pass
else:
raise Exception("...") # should be typeerror
def incorrect_multiple_operators_issubclass(arg1, arg2, arg3):
if not issubclass(arg1) and issubclass(arg2) or issubclass(arg3):
pass
else:
raise Exception("...") # should be typeerror
def incorrect_multi_conditional(arg1, arg2):
if isinstance(arg1, int):
pass
elif isinstance(arg2, int):
raise Exception("...") # should be typeerror
def multiple_is_instance_checks(some_arg):
if isinstance(some_arg, str):
pass
elif isinstance(some_arg, int):
pass
else:
raise Exception("...") # should be typeerror
| MyClass |
python | pytorch__pytorch | torch/_inductor/debug.py | {
"start": 17352,
"end": 28363
} | class ____:
def __init__(self, handler: DebugContext) -> None:
self.fopen = handler.fopen
self.fopen_context = handler.fopen_context
self.filename = handler.filename
self.handler = handler
def fx_graph(
self,
gm: torch.fx.GraphModule,
inputs: list[torch.Tensor],
) -> None:
with self.fopen("fx_graph_runnable.py") as fd:
save_dir = None
if torch._inductor.config.trace.save_real_tensors:
inputs = torch._subclasses.fake_utils.try_convert_fake_to_real(inputs)
save_dir = os.path.dirname(fd.name)
# dont try to use stable hash torchinductor compilation if saving real tensors
# and avoid recursively trying to save real tensors inside of the inductor compilation
# regardless
stable_hash = torch._inductor.config.trace.save_real_tensors
with torch._inductor.config.patch(
{"trace.enabled": False, "trace.save_real_tensors": False}
):
save_graph_repro(
fd,
gm,
inputs,
"inductor",
save_dir=save_dir,
stable_hash=stable_hash,
)
with self.fopen("fx_graph_readable.py") as fd:
fd.write(gm.print_readable(print_output=False))
def fx_graph_transformed(
self,
gm: torch.fx.GraphModule,
inputs: list[torch.Tensor],
) -> None:
with self.fopen("fx_graph_transformed.py") as fd:
fd.write(gm.print_readable(print_output=False))
def ir_pre_fusion(self, nodes: SchedulerNodeList) -> None:
with self.fopen("ir_pre_fusion.txt") as fd:
fd.write(self._write_ir(nodes))
def ir_post_fusion(self, nodes: SchedulerNodeList) -> None:
with self.fopen("ir_post_fusion.txt") as fd:
fd.write(self._write_ir(nodes))
@staticmethod
def _write_ir(nodes: SchedulerNodeList) -> str:
buf = io.StringIO()
for node in nodes:
buf.write(node.debug_str())
buf.write("\n\n\n")
return buf.getvalue()
def graph_diagram(self, nodes: SchedulerNodeList) -> None:
draw_buffers(nodes, fname=self.filename("graph_diagram.svg"))
def draw_orig_fx_graph(
self,
gm: torch.fx.GraphModule,
nodes: SchedulerNodeList,
) -> None:
annotate_orig_fx_with_snodes(gm, nodes)
draw_graph(
gm,
fname=self.filename("orig_fx_graph_diagram.svg"),
clear_meta=False,
prog=GRAPHVIZ_COMMAND_SCALABLE,
parse_stack_trace=True,
dot_graph_shape=config.trace.dot_graph_shape,
)
def output_code(self, filename: str, extension: str = "py") -> None:
shutil.copy(filename, self.filename(f"output_code.{extension}"))
def log_autotuning_results(
self,
name: str,
input_nodes: list[ir.IRNode],
timings: dict["ChoiceCaller", float], # type: ignore[name-defined] # noqa: F821
elapse: float,
precompile_elapse: float,
prescreening_elapse: Optional[float],
) -> None:
from .ir import FixedLayout
def build_node_info(node: ir.IRNode) -> dict[str, str]:
if hasattr(node, "name"):
node_name = node.name
else:
node_name = ""
node_info = {
"name": node_name,
"type": type(node).__name__,
}
try:
layout = node.get_output_spec()
if isinstance(layout, FixedLayout):
offset = 0
try:
offset = int(layout.offset)
except Exception:
try:
offset = V.graph.sizevars.size_hint(
layout.offset, fallback=0
)
except Exception:
pass
static_layout = FixedLayout(
layout.device,
dtype=layout.dtype,
size=[*V.graph.sizevars.size_hints(layout.size)],
stride=[*V.graph.sizevars.size_hints(layout.stride)],
offset=offset,
)
node_info["layout"] = str(static_layout)
else:
node_info["layout"] = str(layout)
except Exception:
pass
try:
node_info["dtype"] = str(node.get_dtype())
except Exception:
pass
try:
node_info["device"] = str(node.get_device())
except Exception:
pass
try:
node_info["stride"] = str(
V.graph.sizevars.size_hints(node.get_stride())
)
except Exception:
pass
try:
node_info["size"] = str(V.graph.sizevars.size_hints(node.get_size())) # type: ignore[arg-type]
except Exception:
pass
try:
node_info["numel"] = str(V.graph.sizevars.size_hint(node.get_numel()))
except Exception:
pass
if hasattr(node, "data") and isinstance(node.data, ir.IRNode):
node_info["data"] = build_node_info(node.data)
return node_info
general_properties = {
"op_name": name,
"cuda_device_name": torch.cuda.get_device_name(),
"cuda_device_count": torch.cuda.device_count(),
"input_nodes": [build_node_info(node) for node in input_nodes],
"autotuning_time": elapse,
"precompile_time": precompile_elapse,
"prescreening_time": prescreening_elapse,
}
with self.fopen_context(
"autotuning_result_json_list.txt", "at", encoding="utf-8"
) as fd:
for caller, time in timings.items():
info_dict = dict(caller.info_dict())
info_dict.update(general_properties)
info_dict["benchmark_result"] = time
json.dump(info_dict, fd)
fd.write("\n")
def log_ir_pre_fusion(nodes: SchedulerNodeList) -> None:
if ir_pre_fusion_log.isEnabledFor(logging.INFO):
ir_pre_fusion_log.info("BEFORE FUSION\n%s", DebugFormatter._write_ir(nodes))
V.debug.ir_pre_fusion(nodes)
def log_ir_post_fusion(nodes: SchedulerNodeList) -> None:
if ir_post_fusion_log.isEnabledFor(logging.INFO):
ir_post_fusion_log.info("AFTER FUSION\n%s", DebugFormatter._write_ir(nodes))
V.debug.ir_post_fusion(nodes)
def _dump_collective_schedule(schedule: list[Union[str, None]]) -> None:
try:
trace_structured(
"artifact",
metadata_fn=lambda: {
"name": "inductor_collective_schedule",
"encoding": "json",
},
payload_fn=lambda: schedule,
)
except Exception:
log.debug(
"Failed to log inductor_collective_schedule via structured logging",
exc_info=True,
)
def log_collective_schedule(nodes: Sequence[BaseSchedulerNode]) -> None:
schedule = [
getattr(op, "python_kernel_name", None)
for node in nodes
if isinstance(op := getattr(node, "node", None), ir._CollectiveKernel)
]
# Only log when there is at least one collective op
if schedule:
_dump_collective_schedule(schedule)
def log_runtime_and_tensor_meta(node_runtimes: Sequence[tuple[Any, float]]) -> None:
"""Log per-op runtime estimates and output tensor metadata for TLParse."""
try:
to_size_hints = V.graph.sizevars.size_hints
def to_list(x: Optional[Sequence[Any]]) -> list[Any]:
return list(to_size_hints(x)) if x is not None else []
def dtype_to_str(dtype: Any) -> Optional[str]:
if dtype is None:
return None
s = str(dtype)
s = s.removeprefix("torch.")
return s
ops: list[dict[str, Any]] = []
for s, runtime_ns in node_runtimes:
name = getattr(s.node, "python_kernel_name", s.get_name())
op_type = "collective" if utils.is_collective(s.node) else "compute"
# Build outputs metadata if available
outputs: list[dict[str, Any]] = []
try:
for buf in s.get_outputs():
irnode = buf.node
shape = irnode.maybe_get_size()
stride = (
irnode.get_stride()
if isinstance(irnode.layout, ir.Layout)
else None
)
dtype = irnode.maybe_get_dtype()
outputs.append(
{
"shape": to_list(shape),
"stride": to_list(stride),
"dtype": dtype_to_str(dtype),
}
)
except Exception:
pass
ops.append(
{
"name": name,
"type": op_type,
"estimated_runtime_ns": runtime_ns,
"outputs": outputs,
}
)
trace_structured(
"artifact",
metadata_fn=lambda: {
"name": "inductor_runtime_and_tensor_meta",
"encoding": "json",
},
payload_fn=lambda: {"ops": ops},
)
except Exception:
log.debug("Failed to log inductor_runtime_and_tensor_meta", exc_info=True)
def log_graph_execution() -> None:
"""Emit a structured artifact with the graph execution order."""
if not GRAPH_EXECUTION_ORDER:
return
try:
trace_structured(
"artifact",
metadata_fn=lambda: {
"name": "graph_execution",
"encoding": "json",
},
payload_fn=lambda: {"graph_execution_order": GRAPH_EXECUTION_ORDER},
)
except Exception:
log.debug("Failed to log graph_execution", exc_info=True)
@contextlib.contextmanager
def record_and_log_graph_execution_order() -> Iterator[None]:
"""Record graph execution order and log it once on exit."""
global RECORD_GRAPH_EXECUTION, GRAPH_EXECUTION_ORDER, GRAPH_COMPILE_IDS
GRAPH_EXECUTION_ORDER = []
GRAPH_COMPILE_IDS = {}
RECORD_GRAPH_EXECUTION = True
try:
yield
finally:
log_graph_execution()
RECORD_GRAPH_EXECUTION = False
GRAPH_EXECUTION_ORDER = None
GRAPH_COMPILE_IDS = None
@dataclasses.dataclass
| DebugFormatter |
python | huggingface__transformers | src/transformers/models/hubert/modeling_hubert.py | {
"start": 16068,
"end": 18989
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.pos_conv_embed = HubertPositionalConvEmbedding(config)
self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
self.dropout = nn.Dropout(config.hidden_dropout)
self.layers = nn.ModuleList([HubertEncoderLayer(config) for _ in range(config.num_hidden_layers)])
self.gradient_checkpointing = False
def forward(
self,
hidden_states: torch.tensor,
attention_mask: Optional[torch.Tensor] = None,
output_attentions: bool = False,
output_hidden_states: bool = False,
return_dict: bool = True,
):
all_hidden_states = () if output_hidden_states else None
all_self_attentions = () if output_attentions else None
if attention_mask is not None:
# make sure padded tokens output 0
expand_attention_mask = attention_mask.unsqueeze(-1).repeat(1, 1, hidden_states.shape[2])
hidden_states[~expand_attention_mask] = 0
attention_mask = create_bidirectional_mask(
config=self.config,
input_embeds=hidden_states,
attention_mask=attention_mask,
)
position_embeddings = self.pos_conv_embed(hidden_states)
hidden_states = hidden_states + position_embeddings
hidden_states = self.layer_norm(hidden_states)
hidden_states = self.dropout(hidden_states)
synced_gpus = is_deepspeed_zero3_enabled() or is_fsdp_managed_module(self)
for layer in self.layers:
if output_hidden_states:
all_hidden_states = all_hidden_states + (hidden_states,)
# add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
dropout_probability = torch.rand([])
skip_the_layer = self.training and dropout_probability < self.config.layerdrop
if not skip_the_layer or synced_gpus:
# under fsdp or deepspeed zero3 all gpus must run in sync
layer_outputs = layer(
hidden_states, attention_mask=attention_mask, output_attentions=output_attentions
)
hidden_states = layer_outputs[0]
if skip_the_layer:
layer_outputs = (None, None)
if output_attentions:
all_self_attentions = all_self_attentions + (layer_outputs[1],)
if output_hidden_states:
all_hidden_states = all_hidden_states + (hidden_states,)
if not return_dict:
return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
return BaseModelOutput(
last_hidden_state=hidden_states,
hidden_states=all_hidden_states,
attentions=all_self_attentions,
)
| HubertEncoder |
python | sqlalchemy__sqlalchemy | test/orm/test_relationships.py | {
"start": 146232,
"end": 159727
} | class ____(
_RelationshipErrors, fixtures.MappedTest
):
@classmethod
def define_tables(cls, metadata):
Table(
"foos",
metadata,
Column("id", Integer, primary_key=True),
Column("fid", Integer),
)
Table(
"bars",
metadata,
Column("id", Integer, primary_key=True),
Column("fid", Integer),
)
Table(
"foos_with_fks",
metadata,
Column("id", Integer, primary_key=True),
Column("fid", Integer, ForeignKey("foos_with_fks.id")),
)
Table(
"bars_with_fks",
metadata,
Column("id", Integer, primary_key=True),
Column("fid", Integer, ForeignKey("foos_with_fks.id")),
)
@classmethod
def setup_classes(cls):
class Foo(cls.Basic):
pass
class Bar(cls.Basic):
pass
def test_no_join(self):
bars, Foo, Bar, foos = (
self.tables.bars,
self.classes.Foo,
self.classes.Bar,
self.tables.foos,
)
self.mapper_registry.map_imperatively(
Foo, foos, properties={"bars": relationship(Bar)}
)
self.mapper_registry.map_imperatively(Bar, bars)
self._assert_raises_no_join(sa.orm.configure_mappers, "Foo.bars", None)
def test_no_join_self_ref(self):
bars, Foo, Bar, foos = (
self.tables.bars,
self.classes.Foo,
self.classes.Bar,
self.tables.foos,
)
self.mapper_registry.map_imperatively(
Foo, foos, properties={"foos": relationship(Foo)}
)
self.mapper_registry.map_imperatively(Bar, bars)
self._assert_raises_no_join(configure_mappers, "Foo.foos", None)
def test_no_equated(self):
bars, Foo, Bar, foos = (
self.tables.bars,
self.classes.Foo,
self.classes.Bar,
self.tables.foos,
)
self.mapper_registry.map_imperatively(
Foo,
foos,
properties={
"bars": relationship(Bar, primaryjoin=foos.c.id > bars.c.fid)
},
)
self.mapper_registry.map_imperatively(Bar, bars)
self._assert_raises_no_relevant_fks(
configure_mappers, "foos.id > bars.fid", "Foo.bars", "primary"
)
def test_no_equated_fks(self):
bars, Foo, Bar, foos = (
self.tables.bars,
self.classes.Foo,
self.classes.Bar,
self.tables.foos,
)
self.mapper_registry.map_imperatively(
Foo,
foos,
properties={
"bars": relationship(
Bar,
primaryjoin=foos.c.id > bars.c.fid,
foreign_keys=bars.c.fid,
)
},
)
self.mapper_registry.map_imperatively(Bar, bars)
self._assert_raises_no_equality(
sa.orm.configure_mappers,
"foos.id > bars.fid",
"Foo.bars",
"primary",
)
def test_no_equated_wo_fks_works_on_relaxed(self):
foos_with_fks, Foo, Bar, bars_with_fks, foos = (
self.tables.foos_with_fks,
self.classes.Foo,
self.classes.Bar,
self.tables.bars_with_fks,
self.tables.foos,
)
# very unique - the join between parent/child
# has no fks, but there is an fk join between two other
# tables in the join condition, for those users that try creating
# these big-long-string-of-joining-many-tables primaryjoins.
# in this case we don't get eq_pairs, but we hit the
# "works if viewonly" rule. so here we add another clause regarding
# "try foreign keys".
self.mapper_registry.map_imperatively(
Foo,
foos,
properties={
"bars": relationship(
Bar,
primaryjoin=and_(
bars_with_fks.c.fid == foos_with_fks.c.id,
foos_with_fks.c.id == foos.c.id,
),
)
},
)
self.mapper_registry.map_imperatively(Bar, bars_with_fks)
self._assert_raises_no_equality(
sa.orm.configure_mappers,
"bars_with_fks.fid = foos_with_fks.id "
"AND foos_with_fks.id = foos.id",
"Foo.bars",
"primary",
)
def test_ambiguous_fks(self):
bars, Foo, Bar, foos = (
self.tables.bars,
self.classes.Foo,
self.classes.Bar,
self.tables.foos,
)
self.mapper_registry.map_imperatively(
Foo,
foos,
properties={
"bars": relationship(
Bar,
primaryjoin=foos.c.id == bars.c.fid,
foreign_keys=[foos.c.id, bars.c.fid],
)
},
)
self.mapper_registry.map_imperatively(Bar, bars)
self._assert_raises_ambiguous_direction(
sa.orm.configure_mappers, "Foo.bars"
)
def test_ambiguous_remoteside_o2m(self):
bars, Foo, Bar, foos = (
self.tables.bars,
self.classes.Foo,
self.classes.Bar,
self.tables.foos,
)
self.mapper_registry.map_imperatively(
Foo,
foos,
properties={
"bars": relationship(
Bar,
primaryjoin=foos.c.id == bars.c.fid,
foreign_keys=[bars.c.fid],
remote_side=[foos.c.id, bars.c.fid],
viewonly=True,
)
},
)
self.mapper_registry.map_imperatively(Bar, bars)
self._assert_raises_no_local_remote(configure_mappers, "Foo.bars")
def test_ambiguous_remoteside_m2o(self):
bars, Foo, Bar, foos = (
self.tables.bars,
self.classes.Foo,
self.classes.Bar,
self.tables.foos,
)
self.mapper_registry.map_imperatively(
Foo,
foos,
properties={
"bars": relationship(
Bar,
primaryjoin=foos.c.id == bars.c.fid,
foreign_keys=[foos.c.id],
remote_side=[foos.c.id, bars.c.fid],
viewonly=True,
)
},
)
self.mapper_registry.map_imperatively(Bar, bars)
self._assert_raises_no_local_remote(configure_mappers, "Foo.bars")
def test_no_equated_self_ref_no_fks(self):
bars, Foo, Bar, foos = (
self.tables.bars,
self.classes.Foo,
self.classes.Bar,
self.tables.foos,
)
self.mapper_registry.map_imperatively(
Foo,
foos,
properties={
"foos": relationship(Foo, primaryjoin=foos.c.id > foos.c.fid)
},
)
self.mapper_registry.map_imperatively(Bar, bars)
self._assert_raises_no_relevant_fks(
configure_mappers, "foos.id > foos.fid", "Foo.foos", "primary"
)
def test_no_equated_self_ref_no_equality(self):
bars, Foo, Bar, foos = (
self.tables.bars,
self.classes.Foo,
self.classes.Bar,
self.tables.foos,
)
self.mapper_registry.map_imperatively(
Foo,
foos,
properties={
"foos": relationship(
Foo,
primaryjoin=foos.c.id > foos.c.fid,
foreign_keys=[foos.c.fid],
)
},
)
self.mapper_registry.map_imperatively(Bar, bars)
self._assert_raises_no_equality(
configure_mappers, "foos.id > foos.fid", "Foo.foos", "primary"
)
def test_no_equated_viewonly(self):
bars, Bar, bars_with_fks, foos_with_fks, Foo, foos = (
self.tables.bars,
self.classes.Bar,
self.tables.bars_with_fks,
self.tables.foos_with_fks,
self.classes.Foo,
self.tables.foos,
)
self.mapper_registry.map_imperatively(
Foo,
foos,
properties={
"bars": relationship(
Bar, primaryjoin=foos.c.id > bars.c.fid, viewonly=True
)
},
)
self.mapper_registry.map_imperatively(Bar, bars)
self._assert_raises_no_relevant_fks(
sa.orm.configure_mappers,
"foos.id > bars.fid",
"Foo.bars",
"primary",
)
self.mapper_registry.dispose()
self.mapper_registry.map_imperatively(
Foo,
foos_with_fks,
properties={
"bars": relationship(
Bar,
primaryjoin=foos_with_fks.c.id > bars_with_fks.c.fid,
viewonly=True,
)
},
)
self.mapper_registry.map_imperatively(Bar, bars_with_fks)
sa.orm.configure_mappers()
def test_no_equated_self_ref_viewonly(self):
bars, Bar, bars_with_fks, foos_with_fks, Foo, foos = (
self.tables.bars,
self.classes.Bar,
self.tables.bars_with_fks,
self.tables.foos_with_fks,
self.classes.Foo,
self.tables.foos,
)
self.mapper_registry.map_imperatively(
Foo,
foos,
properties={
"foos": relationship(
Foo, primaryjoin=foos.c.id > foos.c.fid, viewonly=True
)
},
)
self.mapper_registry.map_imperatively(Bar, bars)
self._assert_raises_no_relevant_fks(
sa.orm.configure_mappers,
"foos.id > foos.fid",
"Foo.foos",
"primary",
)
self.mapper_registry.dispose()
self.mapper_registry.map_imperatively(
Foo,
foos_with_fks,
properties={
"foos": relationship(
Foo,
primaryjoin=foos_with_fks.c.id > foos_with_fks.c.fid,
viewonly=True,
)
},
)
self.mapper_registry.map_imperatively(Bar, bars_with_fks)
sa.orm.configure_mappers()
def test_no_equated_self_ref_viewonly_fks(self):
Foo, foos = self.classes.Foo, self.tables.foos
self.mapper_registry.map_imperatively(
Foo,
foos,
properties={
"foos": relationship(
Foo,
primaryjoin=foos.c.id > foos.c.fid,
viewonly=True,
foreign_keys=[foos.c.fid],
)
},
)
sa.orm.configure_mappers()
eq_(Foo.foos.property.local_remote_pairs, [(foos.c.id, foos.c.fid)])
def test_equated(self):
bars, Bar, bars_with_fks, foos_with_fks, Foo, foos = (
self.tables.bars,
self.classes.Bar,
self.tables.bars_with_fks,
self.tables.foos_with_fks,
self.classes.Foo,
self.tables.foos,
)
self.mapper_registry.map_imperatively(
Foo,
foos,
properties={
"bars": relationship(Bar, primaryjoin=foos.c.id == bars.c.fid)
},
)
self.mapper_registry.map_imperatively(Bar, bars)
self._assert_raises_no_relevant_fks(
configure_mappers, "foos.id = bars.fid", "Foo.bars", "primary"
)
self.mapper_registry.dispose()
self.mapper_registry.map_imperatively(
Foo,
foos_with_fks,
properties={
"bars": relationship(
Bar, primaryjoin=foos_with_fks.c.id == bars_with_fks.c.fid
)
},
)
self.mapper_registry.map_imperatively(Bar, bars_with_fks)
sa.orm.configure_mappers()
def test_equated_self_ref(self):
Foo, foos = self.classes.Foo, self.tables.foos
self.mapper_registry.map_imperatively(
Foo,
foos,
properties={
"foos": relationship(Foo, primaryjoin=foos.c.id == foos.c.fid)
},
)
self._assert_raises_no_relevant_fks(
configure_mappers, "foos.id = foos.fid", "Foo.foos", "primary"
)
def test_equated_self_ref_wrong_fks(self):
bars, Foo, foos = (
self.tables.bars,
self.classes.Foo,
self.tables.foos,
)
self.mapper_registry.map_imperatively(
Foo,
foos,
properties={
"foos": relationship(
Foo,
primaryjoin=foos.c.id == foos.c.fid,
foreign_keys=[bars.c.id],
)
},
)
self._assert_raises_no_relevant_fks(
configure_mappers, "foos.id = foos.fid", "Foo.foos", "primary"
)
| InvalidRelationshipEscalationTest |
python | tensorflow__tensorflow | tensorflow/python/ops/ragged/dynamic_ragged_shape_test.py | {
"start": 4813,
"end": 116966
} | class ____(test_util.TensorFlowTestCase,
parameterized.TestCase):
def assertRowPartitionEq(self,
x: RowPartition,
y: RowPartition,
msg=None) -> None:
self.assertAllEqual(x.row_splits(), y.row_splits(), msg=msg)
def assertShapeEq(self,
x: DynamicRaggedShape,
y: DynamicRaggedShape,
msg=None) -> None:
assert isinstance(x, DynamicRaggedShape)
assert isinstance(y, DynamicRaggedShape)
if msg is None:
msg = ''
self.assertLen(
x.row_partitions, len(y.row_partitions), msg=msg + ': length unequal')
for i in range(len(x.row_partitions)):
x_dims = x.row_partitions[i]
y_dims = y.row_partitions[i]
self.assertRowPartitionEq(
x_dims, y_dims, msg=msg + ': row_partition ' + str(i))
self.assertAllEqual(
x.inner_shape, y.inner_shape, msg=msg + ': shapes unequal')
def assertLayerBroadcasterEq(self, x: _LayerBroadcaster,
y: _LayerBroadcaster) -> None:
assert isinstance(x, _LayerBroadcaster)
assert isinstance(y, _LayerBroadcaster)
self.assertAllEqual(x.gather_index, y.gather_index)
def assertBroadcasterEq(self, x: dynamic_ragged_shape._Broadcaster,
y: dynamic_ragged_shape._Broadcaster) -> None:
assert isinstance(x, dynamic_ragged_shape._Broadcaster)
assert isinstance(y, dynamic_ragged_shape._Broadcaster)
self.assertShapeEq(x.source_shape, y.source_shape)
self.assertShapeEq(x.target_shape, y.target_shape)
self.assertLen(x._layer_broadcasters, len(y._layer_broadcasters))
for x_layer, y_layer in zip(x._layer_broadcasters, y._layer_broadcasters):
self.assertLayerBroadcasterEq(x_layer, y_layer)
@parameterized.parameters([
dict(value='x', row_partitions=[], inner_shape=()),
dict(value=['a', 'b', 'c'], row_partitions=[], inner_shape=[3]),
dict(
value=[['a', 'b', 'c'], ['d', 'e', 'f']],
row_partitions=(),
inner_shape=[2, 3]),
dict(
value=[[['a', 'b', 'c'], ['d', 'e', 'f']]],
row_partitions=(),
inner_shape=[1, 2, 3]),
dict(
value=ragged_factory_ops.constant_value([['a', 'b', 'c'], ['d', 'e']],
ragged_rank=1),
row_partitions=[[0, 3, 5]],
inner_shape=[5]),
dict(
value=ragged_factory_ops.constant_value(
[[['a', 'b', 'c'], ['d', 'e', 'f']]], ragged_rank=1),
row_partitions=[[0, 2]],
inner_shape=[2, 3]),
dict(
value=ragged_factory_ops.constant_value(
[[[[1], [2]], [[3], [4]]], [[[5], [6]]]], ragged_rank=1),
row_partitions=[[0, 2, 3]],
inner_shape=[3, 2, 1]),
dict(
value=ragged_factory_ops.constant_value([[10, 20], [30]]),
row_partitions=[[0, 2, 3]],
inner_shape=[3]),
# Docstring examples:
dict(value=[[1, 2, 3], [4, 5, 6]], row_partitions=[], inner_shape=[2, 3]),
dict(
value=ragged_factory_ops.constant_value([[1, 2], [], [3, 4, 5]]),
row_partitions=[[0, 2, 2, 5]],
inner_shape=[5]),
dict(
value=ragged_factory_ops.constant_value([[[1, 2], [3, 4]], [[5, 6]]],
ragged_rank=1),
row_partitions=[[0, 2, 3]],
inner_shape=[3, 2]),
dict(
value=ragged_factory_ops.constant_value([[[1, 2], [3]], [[4, 5]]]),
row_partitions=[[0, 2, 3], [0, 2, 3, 5]],
inner_shape=[5]),
])
def testFromTensor(self, value, row_partitions, inner_shape):
shape = DynamicRaggedShape.from_tensor(value)
row_partitions = [RowPartition.from_row_splits(x) for x in row_partitions]
expected = DynamicRaggedShape(row_partitions, inner_shape)
self.assertShapeEq(shape, expected)
# pylint:disable=g-long-lambda
@parameterized.parameters([
# from_lengths | row_partitions | inner_shape
# ---------------------- | --------------------------| -------------
# [] | [] | []
# [2, (3, 2)] | [RP([3, 2])] | [5]
# [2, 2] | [] | [2, 2]
# [2, (3, 2), 7] | [RP([3, 2])] | [5, 7]
# [2, (2, 2), 3] | [RP([2, 2])] | [4, 3]
# [2, 2, 3] | [] | [2, 2, 3]
# [2, (2, 1), (2, 0, 3)] | [RP(2, 1), RP([2, 0, 3])] | [5]
dict(lengths=[], row_partitions=[], inner_shape=[]),
dict(
lengths=[2, (3, 2)],
row_partitions=lambda: [RowPartition.from_row_lengths([3, 2])],
inner_shape=[5]),
dict(lengths=[2, 2], row_partitions=[], inner_shape=[2, 2]),
dict(
lengths=[2, (3, 2), 7],
row_partitions=lambda: [RowPartition.from_row_lengths([3, 2])],
inner_shape=[5, 7]),
dict(
lengths=[2, (2, 2), 3],
row_partitions=lambda: [RowPartition.from_row_lengths([2, 2])],
inner_shape=[4, 3]),
dict(lengths=[2, 2, 3], row_partitions=[], inner_shape=[2, 2, 3]),
dict(
lengths=[2, (2, 1), (2, 0, 3)],
row_partitions=lambda: [
RowPartition.from_row_lengths([2, 1]),
RowPartition.from_row_lengths([2, 0, 3])
],
inner_shape=[5]),
# from_lengths | num_row | row_partitions | inner_shape
# : partitions : :
# ---------------| -----------|--------------------------|------------
# [2, (3, 2), 2] | 2 | [RP([3, 2]), URP(2, 10)] | [10]
# [2, 2] | 1 | [URP(2, 4)] | [4]
# [2, 2, 3] | 0 | [] | [2, 2, 3]
# [2, 2, 3] | 1 | [URP(2, 4)] | [4, 3]
# [2, 2, 3] | 2 | [URP(2, 4), URP(3, 12)] | [12]
dict(lengths=[2, (3, 2), 2],
num_row_partitions=2,
row_partitions=lambda: [RowPartition.from_row_lengths([3, 2]),
RowPartition.from_uniform_row_length(2, 10)],
inner_shape=[10]),
dict(lengths=[2, 2],
num_row_partitions=1,
row_partitions=lambda: [RowPartition.from_uniform_row_length(2, 4)],
inner_shape=[4]),
dict(lengths=[2, 2, 3],
num_row_partitions=0,
row_partitions=[],
inner_shape=[2, 2, 3]),
dict(lengths=[2, 2, 3],
num_row_partitions=1,
row_partitions=lambda: [RowPartition.from_uniform_row_length(2, 4)],
inner_shape=[4, 3]),
dict(lengths=[2, 2, 3],
num_row_partitions=2,
row_partitions=lambda: [RowPartition.from_uniform_row_length(2, 4),
RowPartition.from_uniform_row_length(3, 12)],
inner_shape=[12])
])
def testFromLengths(self,
lengths,
row_partitions,
inner_shape,
num_row_partitions=None):
if callable(row_partitions):
row_partitions = row_partitions()
shape = DynamicRaggedShape.from_lengths(
lengths, num_row_partitions=num_row_partitions)
expected = DynamicRaggedShape(row_partitions, inner_shape)
self.assertShapeEq(shape, expected)
@parameterized.parameters([
dict(
lengths=[2, (2, 1, 3)],
num_row_partitions=1,
msg='Shape not consistent'),
dict(
lengths=[2, 3],
num_row_partitions=2,
msg='num_row_partitions should be less than'),
dict(
lengths=[],
num_row_partitions=3,
msg='num_row_partitions==0 for a scalar shape'),
dict(
lengths=[(5, 3), 3],
num_row_partitions='a',
msg='num_row_partitions should be an int or None'),
dict(
lengths=[(5, 'a'), 3],
num_row_partitions=0,
msg='element of lengths should be int or tuple of ints'),
dict(
lengths=['a'],
num_row_partitions=0,
msg='element of lengths should be int or tuple of ints'),
dict(lengths=7, num_row_partitions=0, msg='lengths should be a list')
])
def testFromLengthsError(self, lengths, msg, num_row_partitions=None):
with self.assertRaisesRegex(ValueError, msg):
DynamicRaggedShape.from_lengths(
lengths, num_row_partitions=num_row_partitions)
def testGetItemSliceRankUnknownA(self):
if not context.executing_eagerly():
original_t = array_ops.placeholder_with_default(np.array([4, 5, 3]), None)
sh = DynamicRaggedShape.from_tensor(original_t)
known = sh[:1]
self.assertIsNone(known.rank)
def testGetItemSliceRankUnknownLong(self):
if not context.executing_eagerly():
original_t = array_ops.placeholder_with_default(np.array([4, 5, 3]), None)
sh = DynamicRaggedShape.from_tensor(original_t)
unknown = sh[:20]
self.assertIsNone(unknown.rank)
def testGetItemSliceRankKnownLong(self):
if not context.executing_eagerly():
original_t = constant_op.constant([4, 5, 3], dtypes.float32)
sh = DynamicRaggedShape.from_tensor(original_t)
unknown = sh[:20]
self.assertEqual(unknown.rank, 1)
def testGetBroadcaster(self):
origin_shape = DynamicRaggedShape(
[RowPartition.from_uniform_row_length(1, 3)], inner_shape=[3])
dest_shape = DynamicRaggedShape(
[RowPartition.from_uniform_row_length(2, 6)], inner_shape=[6])
actual = dynamic_ragged_shape._get_broadcaster(origin_shape, dest_shape)
expected = dynamic_ragged_shape._Broadcaster(origin_shape, dest_shape, [
_LayerBroadcaster.from_gather_index([0, 1, 2]),
_LayerBroadcaster.from_gather_index([0, 0, 1, 1, 2, 2])
])
self.assertBroadcasterEq(actual, expected)
def testGetBroadcaster2(self):
origin_shape = DynamicRaggedShape([], inner_shape=[])
dest_shape = DynamicRaggedShape([RowPartition.from_row_splits([0, 2, 3])],
inner_shape=[3])
actual = dynamic_ragged_shape._get_broadcaster(origin_shape, dest_shape)
expected = dynamic_ragged_shape._Broadcaster(origin_shape, dest_shape, [])
self.assertBroadcasterEq(actual, expected)
@parameterized.parameters([
dict(lengths=[2, 3], axis=0, expected=2),
dict(lengths=[2, 3], axis=1, expected=6),
dict(lengths=[2, 3], axis=-1, expected=6),
dict(lengths=[2, 3], axis=-2, expected=2),
dict(lengths=[2, 3, 4], axis=0, expected=2),
dict(lengths=[2, 3, 4], axis=1, expected=6),
dict(lengths=[2, 3, 4], axis=2, expected=24),
dict(lengths=[2, 3, 4], axis=-1, expected=24),
dict(lengths=[2, 3, 4], axis=-2, expected=6),
dict(lengths=[2, 3, 4], axis=-3, expected=2),
dict(lengths=[2, (2, 3), 7], axis=0, expected=2),
dict(lengths=[2, (2, 3), 7], axis=1, expected=5),
dict(lengths=[2, (2, 3), 7], axis=2, expected=35),
dict(lengths=[2, (2, 3), 7], axis=-1, expected=35),
dict(lengths=[2, (2, 3), 7], axis=-2, expected=5),
dict(lengths=[2, (2, 3), 7], axis=-3, expected=2),
])
def testNumSlicesInDimension(self, lengths, axis, expected):
original = DynamicRaggedShape.from_lengths(lengths)
actual = original._num_slices_in_dimension(axis)
self.assertAllEqual(expected, actual)
@parameterized.parameters([
dict(
lengths=[2, 3],
axis=0.5,
error_type=TypeError,
error_regex='axis must be an integer'),
])
def testNumSlicesInDimensionRaises(self, lengths, axis, error_type,
error_regex):
original = DynamicRaggedShape.from_lengths(lengths)
with self.assertRaisesRegex(error_type, error_regex):
original._num_slices_in_dimension(axis)
@parameterized.parameters([
dict(
lengths=[2, (1, 2), 4],
new_dense_rank=3,
error_type=ValueError,
error_regex='Cannot get an inner shape'),
dict(
lengths=[],
new_dense_rank=3,
error_type=ValueError,
error_regex='old inner_rank cannot be zero'),
dict(
lengths=[2, 3],
new_dense_rank=0,
error_type=ValueError,
error_regex='new_inner_rank cannot be zero'),
])
def testAltInnerShapeRaises(self, lengths, new_dense_rank, error_type,
error_regex):
original = DynamicRaggedShape.from_lengths(lengths)
with self.assertRaisesRegex(error_type, error_regex):
original._alt_inner_shape(new_dense_rank)
@parameterized.parameters([
dict(
lengths=[2, (1, 2), 4], new_dense_rank=2, expected_inner_shape=[3,
4]),
])
def testAltInnerShape(self, lengths, new_dense_rank, expected_inner_shape):
original = DynamicRaggedShape.from_lengths(lengths)
actual = original._alt_inner_shape(new_dense_rank)
self.assertAllEqual(actual, expected_inner_shape)
def testWithNumRowPartitionsDynamic(self):
@def_function.function(
input_signature=[tensor.TensorSpec([3], dtypes.int64)])
def fun(x):
shape = DynamicRaggedShape([
RowPartition.from_row_lengths([1, 3], dtype=dtypes.int64),
RowPartition.from_row_lengths([2, 3, 4, 5], dtype=dtypes.int64)
], x)
result = shape._with_num_row_partitions(3)
expected = DynamicRaggedShape([
RowPartition.from_row_lengths([1, 3], dtype=dtypes.int64),
RowPartition.from_row_lengths([2, 3, 4, 5], dtype=dtypes.int64),
RowPartition.from_uniform_row_length(
2, nrows=14, nvals=28, dtype=dtypes.int64)
], [14 * 2, 3])
self.assertShapeEq(expected, result)
fun(constant_op.constant([14, 2, 3], dtype=dtypes.int64))
@parameterized.parameters([
dict(
lengths=[2],
new_dense_rank=2,
error_type=ValueError,
error_regex='Cannot change inner_rank if'),
])
def testWithDenseRankRaises(self, lengths, new_dense_rank, error_type,
error_regex):
original = DynamicRaggedShape.from_lengths(lengths)
with self.assertRaisesRegex(error_type, error_regex):
original._with_inner_rank(new_dense_rank)
@parameterized.parameters([
dict(
lengths=[2, (1, 2)],
num_row_partitions=2,
error_type=ValueError,
error_regex='num_row_partitions must be less than rank'),
dict(
lengths=[2],
num_row_partitions=-1,
error_type=ValueError,
error_regex='num_row_partitions must be nonnegative'),
dict(
lengths=[2],
num_row_partitions=0.5,
error_type=ValueError,
error_regex='num_row_partitions must be an int'),
])
def testWithNumRowPartitionsRaises(self, lengths, num_row_partitions,
error_type, error_regex):
original = DynamicRaggedShape.from_lengths(lengths)
with self.assertRaisesRegex(error_type, error_regex):
original._with_num_row_partitions(num_row_partitions)
def testDimensionRaises(self):
original = DynamicRaggedShape.from_lengths([2, (1, 2)])
with self.assertRaisesRegex(TypeError, 'index should be an int'):
# This error is not exposed directly to the end user.
original._dimension(0.5)
@parameterized.parameters([
# The whole shape (num_row_partitions=0, start=negative, stop=really big)
dict(lengths=[2, 3], s=slice(-1000, 100), expected_lengths=[2, 3]),
# The whole shape (num_row_partitions=0, stop=really big)
dict(lengths=[2, 3], s=slice(0, 100), expected_lengths=[2, 3]),
# The whole shape (num_row_partitions=0, stop=None)
dict(lengths=[2, 3], s=slice(0, None), expected_lengths=[2, 3]),
# start = None, num_row_partitions=1, stop = 3 < rank = 4
dict(
lengths=[2, (1, 2), 3, 4],
s=slice(None, 3),
expected_lengths=[2, (1, 2), 3]),
# start = 1, num_row_partitions=1, stop = 4, rank = 4
dict(
lengths=[2, 3, 3, 4],
num_row_partitions=1,
s=slice(1, 4),
expected_lengths=[3, 3, 4]),
# start = 1, num_row_partitions=1, stop = 3 < rank = 4
dict(
lengths=[2, 3, 3, 4],
num_row_partitions=1,
s=slice(1, 3),
expected_lengths=[3, 3]),
# start = 1, num_row_partitions=2, stop = 3 < rank = 4
dict(
lengths=[2, 3, 4, 3, 4],
num_row_partitions=2,
s=slice(1, 3),
expected_lengths=[3, 4]),
# start = 0, num_row_partitions=1, stop = 3 < rank = 4
dict(
lengths=[2, (1, 2), 3, 4],
s=slice(0, 3),
expected_lengths=[2, (1, 2), 3]),
# start = 0, num_row_partitions=0, stop < rank
dict(lengths=[2, 3, 4], s=slice(0, 2), expected_lengths=[2, 3]),
# start=0 < stop=2 <= num_row_partitions
dict(
lengths=[2, (1, 2), (3, 4, 5)],
s=slice(0, 2),
expected_lengths=[2, (1, 2)]),
# start=0 < stop=1 <= num_row_partitions
dict(lengths=[2, (1, 2), (3, 4, 5)], s=slice(0, 1), expected_lengths=[2]),
# Reversed indices, gives scalar shape.
dict(lengths=[2, 3], s=slice(2, 0), expected_lengths=[]),
# The whole shape (num_row_partitions=0)
dict(lengths=[2, 3], s=slice(0, 2), expected_lengths=[2, 3]),
])
def testGetItemSlice(self,
lengths,
s,
expected_lengths,
num_row_partitions=None):
original = DynamicRaggedShape.from_lengths(lengths)
if num_row_partitions is not None:
original = original._with_num_row_partitions(num_row_partitions)
expected = DynamicRaggedShape.from_lengths(expected_lengths)
actual = original[s]
self.assertShapeEq(expected, actual)
@parameterized.parameters([
dict(
lengths=[2, (1, 2), 3, 4],
index=0.5,
error_type=TypeError,
error_regex='Argument is not an int or a slice'),
dict(
lengths=[2, (1, 2), 3, 4],
index=slice(0, 1, 2),
error_type=IndexError,
error_regex='Cannot stride through a shape'),
dict(
lengths=[2, (1, 2), 3, 4],
index=1,
error_type=ValueError,
error_regex='Index 1 is not uniform'),
dict(
lengths=[2, 3, 3, 4],
num_row_partitions=1,
index=-20,
error_type=IndexError,
error_regex='Index must be non-negative'),
dict(
lengths=[2, 3, 3, 4],
num_row_partitions=1,
index=9,
error_type=IndexError,
error_regex='Index is too big'),
])
def testGetItemRaisesStatic(self,
lengths,
index,
error_type,
error_regex,
num_row_partitions=None):
original = DynamicRaggedShape.from_lengths(lengths)
if num_row_partitions is not None:
original = original._with_num_row_partitions(num_row_partitions)
with self.assertRaisesRegex(error_type, error_regex):
original[index] # pylint: disable=pointless-statement
def testBroadcastToAlt(self):
origin = RaggedTensor.from_uniform_row_length([3, 4, 5],
uniform_row_length=1)
expected = RaggedTensor.from_uniform_row_length([3, 3, 4, 4, 5, 5],
uniform_row_length=2)
expected_shape = DynamicRaggedShape.from_tensor(expected)
actual = dynamic_ragged_shape.broadcast_to(origin, expected_shape)
self.assertAllEqual(actual, expected)
@parameterized.parameters([
dict(
source_lengths=[3],
target_lengths=[1, 3],
target_num_row_partitions=1,
expected_gather_indices=[[0, 1, 2]]),
dict( # BroadcastTensorTo4 broadcaster.
source_lengths=[2, 3],
target_lengths=[1, 2, 3],
target_num_row_partitions=2,
expected_gather_indices=[[0, 1], [0, 1, 2, 3, 4, 5]]),
dict( # raggedTensor1.
source_lengths=[3, (1, 2, 1), 2, 2],
source_num_row_partitions=3,
target_lengths=[1, 1, 3, (1, 2, 1), 2, 2],
target_num_row_partitions=5,
expected_gather_indices=[[0, 1, 2], [0, 1, 2, 3],
[0, 1, 2, 3, 4, 5, 6, 7],
[
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
13, 14, 15
]]),
])
def testBroadcaster(self,
source_lengths,
target_lengths,
expected_gather_indices,
source_num_row_partitions=None,
target_num_row_partitions=None):
source = DynamicRaggedShape.from_lengths(source_lengths)
if source_num_row_partitions is not None:
source = source._with_num_row_partitions(source_num_row_partitions)
target = DynamicRaggedShape.from_lengths(target_lengths)
if target_num_row_partitions is not None:
target = target._with_num_row_partitions(target_num_row_partitions)
expected_gather_indices = [
_LayerBroadcaster.from_gather_index(x) for x in expected_gather_indices
]
actual = dynamic_ragged_shape._get_broadcaster(source, target)
expected = dynamic_ragged_shape._Broadcaster(source, target,
expected_gather_indices)
self.assertBroadcasterEq(actual, expected)
def testRaggedGradientSimple1(self):
if context.executing_eagerly():
return
def func(x):
rt1 = RaggedTensor.from_row_splits(
values=x, row_splits=[0, 4, 7, 8], validate=False)
rt2 = rt1 * [[10], [100], [1000]]
return rt2.flat_values
x = constant_op.constant([3.0, 1.0, 4.0, 1.0, 1.0, 0.0, 2.0, 1.0])
y = func(x)
g = gradients_impl.gradients(ys=y, xs=x)[0]
self.assertAllClose(ops.convert_to_tensor(g),
[10., 10., 10., 10., 100., 100., 100, 1000.])
def testRaggedGradientSimple2(self):
if context.executing_eagerly():
return
def func(x):
rt1 = RaggedTensor._from_row_partition(
x,
RowPartition.from_row_splits(row_splits=[0, 4, 7, 8], validate=False))
rt2 = rt1 * [[10], [100], [1000]]
return rt2.flat_values
x = constant_op.constant([3.0, 1.0, 4.0, 1.0, 1.0, 0.0, 2.0, 1.0])
y = func(x)
g = gradients_impl.gradients(ys=y, xs=x)[0]
self.assertAllClose(ops.convert_to_tensor(g),
[10., 10., 10., 10., 100., 100., 100, 1000.])
def testRaggedGradientSimple3(self):
if context.executing_eagerly():
return
def func(x):
rt1 = RaggedTensor._from_row_partition(
x,
RowPartition.from_row_splits(row_splits=[0, 4, 7, 8],
dtype=dtypes.int32, validate=False))
rt2 = rt1 * [[10], [100], [1000]]
return rt2.flat_values
x = constant_op.constant([3.0, 1.0, 4.0, 1.0, 1.0, 0.0, 2.0, 1.0])
y = func(x)
g = gradients_impl.gradients(ys=y, xs=x)[0]
self.assertAllClose(ops.convert_to_tensor(g),
[10., 10., 10., 10., 100., 100., 100, 1000.])
def testRaggedMul(self):
if context.executing_eagerly():
return
x = constant_op.constant([3.0, 1.0, 4.0, 1.0, 1.0, 0.0, 2.0, 1.0])
rt1 = RaggedTensor._from_row_partition(
x,
RowPartition.from_row_splits(row_splits=[0, 4, 7, 8],
dtype=dtypes.int64, validate=False))
rt2 = rt1 * [[10], [100], [1000]]
self.assertAllClose(rt2.flat_values,
[30.0, 10.0, 40.0, 10.0, 100.0, 0.0, 200.0, 1000.0])
def testBroadcastToGradient(self):
if context.executing_eagerly():
return
def func(x):
target_shape = DynamicRaggedShape.from_row_partitions(
[RowPartition.from_row_splits(row_splits=[0, 4, 7, 8])])
rt = dynamic_ragged_shape.broadcast_to(x, target_shape)
return rt.flat_values
x = constant_op.constant([[3.0], [1.0], [4.0]])
y = func(x)
g = gradients_impl.gradients(ys=y, xs=x)[0]
self.assertAllClose(g, [[4.], [3.], [1.]])
def testBroadcastScalarToScalar(self):
origin = constant_op.constant(b'x')
expected = origin
expected_shape = DynamicRaggedShape.from_tensor(expected)
actual = dynamic_ragged_shape.broadcast_to(origin, expected_shape)
self.assertAllEqual(actual, expected)
@parameterized.parameters([
dict(lengths=[2, 3], axis=0),
dict(lengths=[2, 3], axis=1),
dict(lengths=[2, (2, 3), 7, 4], num_row_partitions=2, axis=0),
dict(lengths=[2, (2, 3), 7, 4], num_row_partitions=2, axis=2),
dict(lengths=[2, (2, 3), 7, 4], num_row_partitions=2, axis=3),
])
def testIsUniformTrue(self, lengths, axis, num_row_partitions=None):
shape = DynamicRaggedShape.from_lengths(lengths)
if num_row_partitions is not None:
shape = shape._with_num_row_partitions(num_row_partitions)
actual = shape.is_uniform(axis)
self.assertTrue(actual)
@parameterized.parameters([
dict(lengths=[2, (2, 3), 7, 4], num_row_partitions=2, axis=1),
dict(
lengths=[2, (2, 3), 2, (0, 1, 2, 3, 4, 5, 6, 7, 8, 9), 4],
num_row_partitions=3,
axis=3),
])
def testIsUniformFalse(self, lengths, num_row_partitions, axis):
shape = DynamicRaggedShape.from_lengths(lengths)._with_num_row_partitions(
num_row_partitions)
actual = shape.is_uniform(axis)
self.assertFalse(actual)
@parameterized.parameters([
dict(
lengths=[2, (2, 3), 7, 4],
num_row_partitions=2,
axis=10,
error_type=IndexError,
error_regex='Expected axis=10 < rank=4'),
dict(
lengths=[2, (2, 3), 7, 4],
num_row_partitions=2,
axis=-1,
error_type=IndexError,
error_regex='Negative axis values are not supported'),
dict(
lengths=[2, (2, 3), 7, 4],
num_row_partitions=2,
axis=0.5,
error_type=TypeError,
error_regex='axis must be an integer'),
])
def testIsUniformRaises(self, lengths, num_row_partitions, axis, error_type,
error_regex):
shape = DynamicRaggedShape.from_lengths(lengths)._with_num_row_partitions(
num_row_partitions)
with self.assertRaisesRegex(error_type, error_regex):
shape.is_uniform(axis)
@parameterized.parameters([
dict(lengths=[2, 3], num_row_partitions_a=0, num_row_partitions_b=1),
dict(
lengths=[2, (2, 3), 7, 4],
num_row_partitions_a=2,
num_row_partitions_b=1),
dict(
lengths=[3, (2, 0, 1), 5],
num_row_partitions_a=1,
num_row_partitions_b=2)
])
def testWithNumRowPartitions(self, lengths, num_row_partitions_a,
num_row_partitions_b):
shape = DynamicRaggedShape.from_lengths(lengths)
original_row_partitions = shape.num_row_partitions
shape_a = shape._with_num_row_partitions(num_row_partitions_a)
self.assertEqual(shape_a.num_row_partitions, num_row_partitions_a)
shape_b = shape_a._with_num_row_partitions(num_row_partitions_b)
self.assertEqual(shape_b.num_row_partitions, num_row_partitions_b)
actual = shape_b._with_num_row_partitions(original_row_partitions)
self.assertShapeEq(actual, shape)
@parameterized.parameters([
dict(
lengths=[2, (2, 3), 7, 4], num_row_partitions=2, axis=-2, expected=7),
dict(lengths=[2, (2, 3), 7, 4], num_row_partitions=2, axis=0, expected=2),
dict(lengths=[2, (2, 3), 7, 4], num_row_partitions=2, axis=2, expected=7),
dict(lengths=[2, (2, 3), 7, 4], num_row_partitions=2, axis=3, expected=4),
dict(
lengths=[2, (2, 3), 7, 4, 3],
num_row_partitions=2,
axis=4,
expected=3),
dict(lengths=[3], axis=0, expected=3),
dict(lengths=[3, 4, 5], axis=0, expected=3),
dict(lengths=[3, 4, 5], axis=1, expected=4),
dict(lengths=[3, 4, 5], axis=2, expected=5),
])
def testGetItem(self, lengths, axis, expected, num_row_partitions=None):
shape = DynamicRaggedShape.from_lengths(lengths)
if num_row_partitions is not None:
shape = shape._with_num_row_partitions(num_row_partitions)
actual = shape[axis]
self.assertAllEqual(actual, expected)
def testNumElements(self):
shape = DynamicRaggedShape.from_lengths([2, 3, 4,
5])._with_num_row_partitions(2)
self.assertAllEqual(shape._num_elements(), 120)
def test_to_row_partitions_from_lengths(self):
# Testing the test.
actual = _to_row_partitions_from_lengths([1, 2, 3])
expected = [
RowPartition.from_row_splits([0, 2]),
RowPartition.from_row_splits([0, 3, 6])
]
self.assertRowPartitionEq(actual[0], expected[0])
self.assertRowPartitionEq(actual[1], expected[1])
@parameterized.parameters([
dict(
origin=b'x',
expected_lengths=[2, (1, 2)],
expected=[[b'x'], [b'x', b'x']]),
dict(
origin=b'x',
expected_lengths=[1, 1, 1],
expected_num_row_partitions=2,
expected=[[[b'x']]]),
dict(
origin=[b'a', b'b', b'c'],
expected_lengths=[3],
expected=[b'a', b'b', b'c']),
dict(
origin=[b'a', b'b', b'c'],
expected_lengths=[1, 1, 3],
expected_num_row_partitions=2,
expected=[[[b'a', b'b', b'c']]]),
dict(
origin=[[b'a', b'b', b'c'], [b'd', b'e', b'f']],
expected_lengths=[1, 2, 3],
expected_num_row_partitions=2,
expected=[[[b'a', b'b', b'c'], [b'd', b'e', b'f']]]),
])
def testBroadcastTensorTo(self,
origin,
expected_lengths,
expected,
expected_num_row_partitions=None):
origin = constant_op.constant(origin)
expected_shape = DynamicRaggedShape.from_lengths(expected_lengths)
if expected_num_row_partitions is not None:
expected_shape = expected_shape._with_num_row_partitions(
expected_num_row_partitions)
expected = ragged_factory_ops.constant_value(expected)
actual = dynamic_ragged_shape.broadcast_to(origin, expected_shape)
self.assertAllEqual(actual, expected)
def testBroadcastFlatValues(self):
origin_lengths = [3, (1, 2, 1), 2, 2]
dest_lengths = [1, 1, 3, (1, 2, 1), 2, 2]
origin_values = constant_op.constant([
b'a', b'b', b'c', b'd', b'e', b'f', b'g', b'h', b'i', b'j', b'k', b'l',
b'm', b'n', b'o', b'p'
])
origin_shape = DynamicRaggedShape.from_lengths(
origin_lengths)._with_num_row_partitions(3)
dest_shape = DynamicRaggedShape.from_lengths(
dest_lengths)._with_num_row_partitions(5)
broadcaster = dynamic_ragged_shape._get_broadcaster(origin_shape,
dest_shape)
actual = broadcaster.broadcast_flat_values(origin_values)
self.assertAllEqual(origin_values, actual)
@parameterized.parameters([
dict(
origin_lengths=[3],
origin_values=[b'a', b'b', b'c'],
expected_lengths=[2],
expected_values=[[b'a', b'b', b'c'], [b'a', b'b', b'c']]),
dict(
origin_lengths=[3, (3, 2, 4)],
origin_values=[7, 4, 5, 6, 1, 2, 3, 7, 89],
expected_lengths=[3, (3, 2, 4)],
expected_values=[7, 4, 5, 6, 1, 2, 3, 7, 89]),
dict(
origin_lengths=[3, (3, 2, 4)],
origin_values=[7, 4, 5, 6, 1, 2, 3, 7, 89],
expected_lengths=[1, 3, (3, 2, 4)],
expected_values=[7, 4, 5, 6, 1, 2, 3, 7, 89]),
dict(
origin_lengths=[3, (3, 2, 4)],
origin_values=[7, 4, 5, 6, 1, 2, 3, 7, 89],
expected_lengths=[1, 1, 3, (3, 2, 4)],
expected_values=[7, 4, 5, 6, 1, 2, 3, 7, 89]),
# Broadcast [1, 2, (1, 2)] to [2, 2, (1, 2, 1, 2)]
dict(
origin_lengths=[1, 2, (1, 2)],
origin_values=[2, 3, 5],
expected_lengths=[2, 2, (1, 2, 1, 2)],
expected_values=[2, 3, 5, 2, 3, 5]),
# Broadcast [2, 1, (1, 2)] to [2, 2, (1, 1, 2, 2)] (NEW)
dict(
origin_lengths=[2, 1, (1, 2)],
origin_values=[2, 3, 5],
expected_lengths=[2, 2, (1, 1, 2, 2)],
expected_values=[2, 2, 3, 5, 3, 5]),
dict(
origin_lengths=[2, 1, 1],
origin_values=[2, 3], # [[[2]], [[3]]]
expected_lengths=[2, 1, (3, 3)],
expected_values=[2, 2, 2, 3, 3, 3]),
dict(
origin_lengths=[3],
origin_values=[b'a', b'b', b'c'],
expected_lengths=[4, 2, 3],
expected_values=[
b'a', b'b', b'c', b'a', b'b', b'c', b'a', b'b', b'c', b'a', b'b',
b'c', b'a', b'b', b'c', b'a', b'b', b'c', b'a', b'b', b'c', b'a',
b'b', b'c'
]),
dict(
origin_lengths=[2, 3],
origin_values=[b'a', b'b', b'c', b'a', b'b', b'c'],
expected_lengths=[4, 2, 3],
expected_values=[
b'a', b'b', b'c', b'a', b'b', b'c', b'a', b'b', b'c', b'a', b'b',
b'c', b'a', b'b', b'c', b'a', b'b', b'c', b'a', b'b', b'c', b'a',
b'b', b'c'
]),
dict(
origin_lengths=[3, (1, 2, 1), 2, 2],
origin_values=[
b'a', b'b', b'c', b'd', b'e', b'f', b'g', b'h', b'i', b'j', b'k',
b'l', b'm', b'n', b'o', b'p'
],
expected_lengths=[1, 1, 3, (1, 2, 1), 2, 2],
expected_values=[
b'a', b'b', b'c', b'd', b'e', b'f', b'g', b'h', b'i', b'j', b'k',
b'l', b'm', b'n', b'o', b'p'
]),
dict(
origin_lengths=[3, (1, 2, 1), 2, 2],
origin_values=[7, 4, 5, 6, 1, 2, 3, 7, 7, 4, 5, 6, 1, 2, 3, 7],
expected_lengths=[1, 1, 3, (1, 2, 1), 2, 2],
expected_values=[7, 4, 5, 6, 1, 2, 3, 7, 7, 4, 5, 6, 1, 2, 3, 7],
),
])
def testBroadcastRaggedTo(self, origin_lengths, origin_values,
expected_lengths, expected_values):
origin = _to_ragged_tensor_from_lengths(origin_values, origin_lengths)
expected = _to_ragged_tensor_from_lengths(expected_values, expected_lengths)
expected_shape = DynamicRaggedShape.from_tensor(expected)
actual = dynamic_ragged_shape.broadcast_to(origin, expected_shape)
self.assertAllEqual(actual, expected)
def testDynamicRaggedShapeFromTensor2(self):
raw_rt = [[[[7, 4], [5, 6]], [[1, 2], [3, 7]]], [[[7, 4], [5, 6]]],
[[[1, 2], [3, 7]]]]
raw_rt = ragged_factory_ops.constant_value(raw_rt)
actual_shape = DynamicRaggedShape.from_tensor(raw_rt)
expected_shape = DynamicRaggedShape.from_lengths(
[3, (2, 1, 1), 2, 2])._with_num_row_partitions(3)
self.assertShapeEq(actual_shape, expected_shape)
# pylint: disable=g-long-lambda
@parameterized.parameters([
# A row partition as opposed to a list of row partitions.
dict(
row_partitions=lambda: RowPartition.from_row_splits([0, 2, 3]),
inner_shape=lambda: [4],
error_type=TypeError,
error_regex='row_partitions should be'),
# A list of lists of integers for row_partitions.
dict(
row_partitions=lambda: [[0, 2, 3]],
inner_shape=lambda: [4],
error_type=TypeError,
error_regex='row_partitions contains'),
# nvals and nrows don't match (3 != 6) statically
dict(
row_partitions=lambda: [ # pylint: disable=g-long-lambda
RowPartition.from_value_rowids([0, 2, 4], nrows=5),
RowPartition.from_value_rowids([0, 2, 5], nrows=6)
],
inner_shape=lambda: [3],
validate=False,
error_type=ValueError,
error_regex='RowPartitions in DynamicRaggedShape do not'),
# nvals and inner_shape[0] don't match (3 != 6) statically
dict(
row_partitions=lambda: [
RowPartition.from_value_rowids([0, 2, 4], nrows=5),
],
inner_shape=lambda: [6],
validate=False,
error_type=ValueError,
error_regex='Last row partition does not match inner_shape.'),
])
def testConstructorRaisesStatic(self,
row_partitions,
inner_shape,
error_type,
error_regex,
validate=False,
dtype=None):
row_partitions = row_partitions()
inner_shape = inner_shape()
with self.assertRaisesRegex(error_type, error_regex):
DynamicRaggedShape(
row_partitions, inner_shape, dtype=dtype, validate=validate)
def testConstructorStaticOK(self):
row_partitions = [
RowPartition.from_value_rowids([0, 2, 4], nrows=5),
RowPartition.from_value_rowids([0, 1, 2], nrows=3)
]
inner_shape = [3]
rts = DynamicRaggedShape(row_partitions, inner_shape, validate=True)
static_inner_shape = tensor_util.constant_value(rts.inner_shape)
static_valid_rowids0 = tensor_util.constant_value(
rts.row_partitions[0].value_rowids())
static_valid_rowids1 = tensor_util.constant_value(
rts.row_partitions[1].value_rowids())
self.assertAllEqual(static_inner_shape, [3])
self.assertAllEqual(static_valid_rowids0, [0, 2, 4])
self.assertAllEqual(static_valid_rowids1, [0, 1, 2])
def testConstructorWithStaticInnerShape(self):
row_partitions = [
RowPartition.from_value_rowids([0, 2, 4], nrows=5),
RowPartition.from_value_rowids([0, 1, 2], nrows=3)
]
inner_shape = [3]
rts = DynamicRaggedShape(row_partitions, inner_shape, validate=True,
static_inner_shape=[3])
static_inner_shape = tensor_util.constant_value(rts.inner_shape)
static_valid_rowids0 = tensor_util.constant_value(
rts.row_partitions[0].value_rowids())
static_valid_rowids1 = tensor_util.constant_value(
rts.row_partitions[1].value_rowids())
self.assertAllEqual(static_inner_shape, [3])
self.assertAllEqual(static_valid_rowids0, [0, 2, 4])
self.assertAllEqual(static_valid_rowids1, [0, 1, 2])
def testZeros(self):
shape_x = DynamicRaggedShape.from_lengths([3, (1, 3, 2), 4])
foo = ragged_array_ops.zeros(shape_x)
self.assertShapeEq(shape_x, DynamicRaggedShape.from_tensor(foo))
self.assertAllEqual(array_ops.zeros([6, 4]), foo.flat_values)
def testOnes(self):
shape_x = DynamicRaggedShape.from_lengths([3, (1, 3, 2), 4])
foo = ragged_array_ops.ones(shape_x)
self.assertShapeEq(shape_x, DynamicRaggedShape.from_tensor(foo))
self.assertAllEqual(array_ops.ones([6, 4]), foo.flat_values)
def testReshapeTensor(self):
foo = array_ops.zeros([3, 2, 4])
shape_b = DynamicRaggedShape.from_lengths([3, (3, 2, 1), 4])
result = ragged_array_ops.ragged_reshape(foo, shape_b)
self.assertShapeEq(shape_b, DynamicRaggedShape.from_tensor(result))
self.assertAllEqual(array_ops.zeros([6, 4]), result.flat_values)
def test_reshape_ragged_tensor(self):
shape_x = DynamicRaggedShape.from_lengths([3, (1, 3, 2), 4])
foo = ragged_array_ops.zeros(shape_x)
shape_b = DynamicRaggedShape.from_lengths([3, (3, 2, 1), 4])
result = ragged_array_ops.ragged_reshape(foo, shape_b)
self.assertShapeEq(shape_b, DynamicRaggedShape.from_tensor(result))
self.assertAllEqual(array_ops.zeros([6, 4]), result.flat_values)
@parameterized.parameters([
dict(
lengths_a=[3, (1, 4, 2)],
lengths_b=[3, (1, 4, 2)],
lengths_e=[3, (1, 4, 2)]),
dict(
lengths_a=[1, 2, (1, 4)],
lengths_b=[3, 2, (1, 4, 1, 4, 1, 4)],
lengths_e=[3, 2, (1, 4, 1, 4, 1, 4)]),
dict(
lengths_a=[1, 1],
num_row_partitions_a=1,
lengths_b=[3, 5],
num_row_partitions_b=1,
lengths_e=[3, 5],
num_row_partitions_e=1),
dict(lengths_a=[1, 4, 5], lengths_b=[3, 1, 1], lengths_e=[3, 4, 5]),
dict(lengths_a=[3], lengths_b=[4, 2, 1], lengths_e=[4, 2, 3]),
dict(lengths_a=[2, 3], lengths_b=[4, 2, 1], lengths_e=[4, 2, 3]),
# Outermost dimension-both partitioned
# Also, neither has uniform_row_length
dict(
lengths_a=[2, (1, 3), 1],
lengths_b=[2, (1, 3), (3, 4, 5, 6)],
lengths_e=[2, (1, 3), (3, 4, 5, 6)]),
# Outermost dimension-Only one is partitioned
# Also, partitioned dimension doesn't have uniform_row_length
dict(
lengths_a=[2, 1, 5],
lengths_b=[2, (1, 3), 5],
num_row_partitions_b=2,
lengths_e=[2, (1, 3), 5],
num_row_partitions_e=2),
# Cover [5, R], [1, 5, R]
dict(
lengths_a=[5, (1, 2, 0, 3, 1)],
lengths_b=[1, 5, (1, 2, 0, 3, 1)],
lengths_e=[1, 5, (1, 2, 0, 3, 1)]),
# When two uniform row lengths are equal
dict(
lengths_a=[1, 5],
num_row_partitions_a=1,
lengths_b=[3, 5],
num_row_partitions_b=1,
lengths_e=[3, 5],
num_row_partitions_e=1),
# Dense + Partitioned dimension has uniform_row_length
# [1, 3, [5, 1, 6]] and DENSE [2, 1, 1] -> [2, 3, [5, 1, 6, 5, 1, 6]]
dict(
lengths_a=[1, 3, (5, 1, 6)],
lengths_b=[2, 1, 1],
lengths_e=[2, 3, (5, 1, 6, 5, 1, 6)]),
# Both partitioned; one has uniform_row_length
# (uniform_row_length [2,1,1]) and [2,[1,3],[3,4,5,6]]
dict(
lengths_a=[2, 1, 1],
num_row_partitions_a=2,
lengths_b=[2, (1, 3), (3, 4, 5, 6)],
lengths_e=[2, (1, 3), (3, 4, 5, 6)]),
# When broadcasting uniform_row_length to uniform_row_length.
# Also, both have uniform_row_length
dict(
lengths_a=[3, 1, 5],
num_row_partitions_a=2,
lengths_b=[3, 4, 5],
num_row_partitions_b=2,
lengths_e=[3, 4, 5],
num_row_partitions_e=2),
# When broadcasting above a U_R_L
# [2,1, 5] and [2, [1,3], 5] -> [2, [1,3], 5]
dict(
lengths_a=[2, 1, 5],
num_row_partitions_a=2,
lengths_b=[2, (1, 3), 5],
num_row_partitions_b=2,
lengths_e=[2, (1, 3), 5],
num_row_partitions_e=2),
# What if the larger-dimensional shape has uniform_row_length on the
# matching dim, but has larger dimensions above
# ([3,1,5],[15]) vs ([2,1],[2]))
dict(
lengths_a=[3, 1, 5],
num_row_partitions_a=2,
lengths_b=[2, 1],
num_row_partitions_b=1,
lengths_e=[3, 2, 5],
num_row_partitions_e=2),
# Inner non-ragged dimensions
# Can delegate to dense broadcast operations.
# Implementation detail: not testable.
# ([2, [1,2]],[3,2,1]) and ([2,1],[2,1,3])
dict(
lengths_a=[2, (1, 2), 2, 1],
lengths_b=[2, 1, 1, 3],
num_row_partitions_b=1,
lengths_e=[2, (1, 2), 2, 3],
),
])
def testBroadcastDynamicShapeExtended(self,
lengths_a,
lengths_b,
lengths_e,
num_row_partitions_a=None,
num_row_partitions_b=None,
num_row_partitions_e=None):
# This test is predicated on the fact that broadcast_to is correct.
# Thus, it tests:
# Whether the shape generated is correct.
# Whether broadcasting is the same as broadcast_to.
# Instead of specifying values, it just uses primes.
shape_a = DynamicRaggedShape.from_lengths(lengths_a)
if num_row_partitions_a is not None:
shape_a = shape_a._with_num_row_partitions(num_row_partitions_a)
shape_b = DynamicRaggedShape.from_lengths(lengths_b)
if num_row_partitions_b is not None:
shape_b = shape_b._with_num_row_partitions(num_row_partitions_b)
shape_e = DynamicRaggedShape.from_lengths(lengths_e)
if num_row_partitions_e is not None:
shape_e = shape_e._with_num_row_partitions(num_row_partitions_e)
[actual, bc_a, bc_b
] = dynamic_ragged_shape.broadcast_dynamic_shape_extended(shape_a, shape_b)
[actual_rev, bc_b_rev, bc_a_rev
] = dynamic_ragged_shape.broadcast_dynamic_shape_extended(shape_b, shape_a)
self.assertShapeEq(actual, shape_e)
self.assertShapeEq(actual_rev, shape_e)
rt_a = ragged_array_ops.ragged_reshape(
_lowest_primes(_num_elements_of_lengths(lengths_a)), shape_a)
bc_a_actual = bc_a.broadcast(rt_a)
bc_a_actual_rev = bc_a_rev.broadcast(rt_a)
bc_a_expected = dynamic_ragged_shape.broadcast_to(rt_a, shape_e)
self.assertAllEqual(bc_a_expected, bc_a_actual)
self.assertAllEqual(bc_a_expected, bc_a_actual_rev)
rt_b = ragged_array_ops.ragged_reshape(
_lowest_primes(_num_elements_of_lengths(lengths_b)), shape_b)
bc_b_expected = dynamic_ragged_shape.broadcast_to(rt_b, shape_e)
bc_b_actual = bc_b.broadcast(rt_b)
bc_b_actual_rev = bc_b_rev.broadcast(rt_b)
self.assertAllEqual(bc_b_expected, bc_b_actual)
self.assertAllEqual(bc_b_expected, bc_b_actual_rev)
@parameterized.parameters([
dict(
lengths=[3, (1, 4, 2)],
dense_rank=1,
lengths_e=[3, (1, 4, 2)],
),
dict(
lengths=[3, (1, 4, 2), 5],
dense_rank=2,
lengths_e=[3, (1, 4, 2), 5],
),
dict(
lengths=[3],
dense_rank=1,
lengths_e=[3],
),
])
def testWithDenseRank(self, lengths, dense_rank, lengths_e):
# Makes little sense with from_lengths/_with_num_row_partitions.
original = DynamicRaggedShape.from_lengths(lengths)
actual = original._with_inner_rank(dense_rank)
self.assertAllEqual(actual.inner_rank, dense_rank)
self.assertAllEqual(actual.static_lengths(), lengths_e)
@parameterized.parameters([
dict(
rps=[3, [1, 4, 2]],
lengths_e=[3, (1, 4, 2)],
num_row_partitions_e=1,
),
dict(
rps=[3, [1, 4, 2], 2],
lengths_e=[3, (1, 4, 2), 2],
num_row_partitions_e=2,
),
])
def testFromRowPartitions(self, rps, lengths_e, num_row_partitions_e):
rps = _to_row_partitions_from_lengths(rps)
actual = DynamicRaggedShape.from_row_partitions(rps)
expected = DynamicRaggedShape.from_lengths(
lengths_e)._with_num_row_partitions(num_row_partitions_e)
self.assertShapeEq(expected, actual)
def testFromRowPartitionsError(self):
with self.assertRaisesRegex(ValueError, 'row_partitions cannot be empty'):
DynamicRaggedShape.from_row_partitions([])
@parameterized.parameters([
#=========================================================================
# dimension[axis] is uniform inner; and row_lengths is a scalar
#=========================================================================
# shape: [BROADCAST(UNIFORM), UNIFORM, UNIFORM]
dict(original_lengths=[1, 4, 5],
broadcast_lengths=[3, 4, 5]),
# shape: [UNIFORM, UNIFORM, BROADCAST(UNIFORM)]
dict(original_lengths=[3, 4, 1],
broadcast_lengths=[3, 4, 5]),
# shape: [UNIFORM, RAGGED, BROADCAST(UNIFORM)]
dict(original_lengths=[3, (3, 2, 8), 1],
broadcast_lengths=[3, (3, 2, 8), 5]),
# shape: [UNIFORM, RAGGED, RAGGED, UNIFORM, UNIFORM, BROADCAST(UNIFORM)]
dict(original_lengths=[2, (2, 1), (3, 2, 8), 3, 4, 1],
broadcast_lengths=[2, (2, 1), (3, 2, 8), 3, 4, 5]),
#=========================================================================
# dimension[axis] is uniform inner; and row_lengths is a vector
#=========================================================================
# shape: [UNIFORM, BROADCAST(UNIFORM)]
dict(original_lengths=[3, 1],
broadcast_lengths=[3, (2, 0, 1)]),
# shape: [UNIFORM, BROADCAST(UNIFORM), UNIFORM]
dict(original_lengths=[3, 1, 5],
broadcast_lengths=[3, (2, 0, 1), 5]),
# shape: [UNIFORM, UNIFORM, BROADCAST(UNIFORM)]
dict(original_lengths=[4, 3, 1],
broadcast_lengths=[4, 3, (2, 0, 1, 3, 8, 2, 3, 4, 1, 8, 7, 0)]),
# shape: [UNIFORM, RAGGED, BROADCAST(UNIFORM)]
dict(original_lengths=[2, (2, 1), 1],
broadcast_lengths=[2, (2, 1), (2, 5, 3)]),
# shape: [UNIFORM, RAGGED, UNIFORM, UNIFORM, BROADCAST(UNIFORM), UNIFORM]
dict(original_lengths=[2, (2, 1), 3, 2, 1, 8],
broadcast_lengths=[2, (2, 1), 3, 2, tuple(range(18)), 8]),
#=========================================================================
# dimension[axis] is uniform partitioned; and row_lengths is a scalar
#=========================================================================
# shape: [BROADCAST(UNIFORM), RAGGED]
dict(original_lengths=[1, (5,)],
broadcast_lengths=[3, (5, 5, 5)]),
# shape: [BROADCAST(UNIFORM), UNIFORM, RAGGED]
dict(original_lengths=[1, 3, (3, 0, 2)],
broadcast_lengths=[2, 3, (3, 0, 2, 3, 0, 2)]),
# shape: [BROADCAST(UNIFORM), RAGGED, RAGGED, UNIFORM, UNIFORM]
dict(original_lengths=[1, (3,), (3, 5, 2), 9, 4, 5],
broadcast_lengths=[3, (3, 3, 3), (3, 5, 2, 3, 5, 2, 3, 5, 2),
9, 4, 5]),
# shape: [BROADCAST(UNIFORM), UNIFORM, RAGGED, UNIFORM]
dict(original_lengths=[1, 2, (2, 1), (3, 5, 2), 2],
broadcast_lengths=[2, 2, (2, 1, 2, 1), (3, 5, 2, 3, 5, 2), 2]),
# shape: [UNIFORM, BROADCAST(UNIFORM), RAGGED, UNIFORM]
# This is wrong. should broadcast to [3, 2, (4, 4, 0, 0, 2, 2), 5]
# dict(original_lengths=[3, 1, [4, 0, 2], 5],
# broadcast_lengths=[3, 2, [4, 0, 2, 4, 0, 2], 5]),
dict(original_lengths=[3, 1, (4, 0, 2), 5],
broadcast_lengths=[3, 2, (4, 4, 0, 0, 2, 2), 5]),
# shape: [UNIFORM, BROADCAST(UNIFORM), RAGGED]
dict(original_lengths=[2, 3, (1, 2, 3, 4, 5, 6)],
broadcast_lengths=[2, 3, (1, 2, 3, 4, 5, 6)]),
#=========================================================================
# dimension[axis] is uniform partitioned; and row_lengths is a vector
#=========================================================================
# shape: [UNIFORM, BROADCAST(UNIFORM), RAGGED, UNIFORM]
dict(original_lengths=[
3, # axis=0
1, # axis=1 (broadcast)
(3, 1, 2), # axis=2
5], # axis=3
broadcast_lengths=[
3, # axis=0
(4, 1, 2), # axis=1 (broadcast)
(3, 3, 3, 3, 1, 2, 2), # axis=2
5]), # axis=3
# shape: [UNIFORM, BROADCAST(UNIFORM), RAGGED, RAGGED]
dict(original_lengths=[
3, # axis=0
1, # axis=1 (broadcast)
(3, 1, 2), # axis=2
(3, 1, 4, 1, 5, 9)], # axis=3
broadcast_lengths=[
3, # axis=0
(2, 0, 3), # axis=1 (broadcast)
(3, 3, 2, 2, 2), # axis=2
(3, 1, 4, 3, 1, 4, 5, 9, 5, 9, 5, 9)]), # axis=3
# shape: [UNIFORM, RAGGED, BROADCAST(UNIFORM), RAGGED, RAGGED, UNIFORM]
dict(original_lengths=[
3, # axis=0
(2, 0, 1), # axis=1
1, # axis=2 (broadcast)
(3, 2, 1), # axis=3
(1, 0, 1, 0, 2, 3), # axis=4
5], # axis=5
broadcast_lengths=[
3, # axis=0
(2, 0, 1), # axis=2
(4, 1, 2), # axis=2 (broadcast)
(3, 3, 3, 3, 2, 1, 1), # axis=3
(1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, # axis=4
2, 3, 3),
5]), # axis=5
dict(original_lengths=[1, 1, 2, (2, 1)],
broadcast_lengths=[2, 1, 2, (2, 1, 2, 1)]),
dict(original_lengths=[2, 1, 2, (2, 1, 2, 1)],
broadcast_lengths=[2, (2, 1), 2, (2, 1, 2, 1, 2, 1)]),
dict(original_lengths=[2, (2, 1), 2, (2, 1, 2, 1, 2, 1)],
broadcast_lengths=[2, (2, 1), 2, (2, 1, 2, 1, 2, 1)]),
dict(original_lengths=[2, (2, 1), 2, 1],
broadcast_lengths=[2, (2, 1), 2, (2, 1, 2, 1, 2, 1)]),
]) # pyformat: disable
def testBroadcastDimension(self, original_lengths, broadcast_lengths):
"""Tests broadcast_to on a single dimension."""
original_rt = _to_prime_tensor_from_lengths(original_lengths)
bcast_shape = DynamicRaggedShape.from_lengths(broadcast_lengths)
result_rt = dynamic_ragged_shape.broadcast_to(original_rt, bcast_shape)
result_shape = DynamicRaggedShape.from_tensor(result_rt)
self.assertShapeEq(bcast_shape, result_shape)
def testAsRowPartitions(self):
my_shape = DynamicRaggedShape.from_lengths([3, (2, 0, 1), 5])
rps = my_shape._as_row_partitions()
self.assertLen(rps, 2)
def testAsRowPartitionsRaises(self):
my_shape = DynamicRaggedShape.from_lengths([])
with self.assertRaisesRegex(ValueError,
'rank must be >= 1 for _as_row_partitions'):
my_shape._as_row_partitions()
def testToPrimeTensorFromDimSizes(self):
"""Tests the test utility."""
original_lengths = [3, (3, 2, 8), 1]
original_rt = _to_prime_tensor_from_lengths(original_lengths)
expected_rt = _to_ragged_tensor_from_lengths(
[[2], [3], [5], [7], [11], [13], [17], [19], [23], [29], [31], [37],
[41]], [3, (3, 2, 8)])
self.assertAllEqual(expected_rt, original_rt)
@parameterized.parameters([
# Broadcast scalar
dict(x_dims=[], y_dims=[], expected_dims=[]),
dict(x_dims=[], y_dims=[2], expected_dims=[2]),
dict(x_dims=[], y_dims=[2, 3], expected_dims=[2, 3]),
dict(
x_dims=[],
y_dims=[2, (2, 3), (5, 7, 2, 0, 9)],
expected_dims=[2, (2, 3), (5, 7, 2, 0, 9)]),
# Broadcast vector
dict(x_dims=[3], y_dims=[4, 2, 3], expected_dims=[4, 2, 3]),
dict(x_dims=[1], y_dims=[4, 2, 3], expected_dims=[4, 2, 3]),
dict(x_dims=[3], y_dims=[4, 2, 1], expected_dims=[4, 2, 3]),
dict(
x_dims=[3], y_dims=[3, (2, 3, 1), 1], expected_dims=[3, (2, 3, 1),
3]),
dict(x_dims=[1], y_dims=[3, (2, 1, 3)], expected_dims=[3, (2, 1, 3)]),
dict(
x_dims=[1], y_dims=[3, (2, 1, 3), 8], expected_dims=[3, (2, 1, 3),
8]),
dict(
x_dims=[1],
y_dims=[2, (2, 3), (5, 7, 2, 0, 9)],
expected_dims=[2, (2, 3), (5, 7, 2, 0, 9)]),
# Mixed broadcasting
dict(
x_dims=[
1, # axis=0
3, # axis=1
(3, 0, 2), # axis=2
1, # axis=3
2, # axis=4
],
y_dims=[
2, # axis=0
1, # axis=1
1, # axis=2
(7, 2), # axis=3
1, # axis=4
],
expected_dims=[
2, # axis=0
3, # axis=1
(3, 0, 2, 3, 0, 2), # axis=2
(7, 7, 7, 7, 7, 2, 2, 2, 2, 2), # axis=3
2, # axis=4
]),
dict(
x_dims=[2, (2, 1), 2, 1],
y_dims=[1, 1, 2, (2, 1)],
expected_dims=[2, (2, 1), 2, (2, 1, 2, 1, 2, 1)]),
])
def testBroadcastDynamicShape(self, x_dims, y_dims, expected_dims):
shape_a = DynamicRaggedShape.from_lengths(x_dims)
shape_b = DynamicRaggedShape.from_lengths(y_dims)
shape_e = DynamicRaggedShape.from_lengths(expected_dims)
[actual, bc_a, bc_b
] = dynamic_ragged_shape.broadcast_dynamic_shape_extended(shape_a, shape_b)
[actual_rev, bc_b_rev, bc_a_rev
] = dynamic_ragged_shape.broadcast_dynamic_shape_extended(shape_b, shape_a)
self.assertShapeEq(actual, shape_e)
self.assertShapeEq(actual_rev, shape_e)
rt_a = _to_prime_tensor_from_lengths(x_dims)
bc_a_actual = bc_a.broadcast(rt_a)
bc_a_actual_rev = bc_a_rev.broadcast(rt_a)
bc_a_expected = dynamic_ragged_shape.broadcast_to(rt_a, shape_e)
self.assertAllEqual(bc_a_expected, bc_a_actual)
self.assertAllEqual(bc_a_expected, bc_a_actual_rev)
rt_b = _to_prime_tensor_from_lengths(y_dims)
bc_b_expected = dynamic_ragged_shape.broadcast_to(rt_b, shape_e)
bc_b_actual = bc_b.broadcast(rt_b)
bc_b_actual_rev = bc_b_rev.broadcast(rt_b)
self.assertAllEqual(bc_b_expected, bc_b_actual)
self.assertAllEqual(bc_b_expected, bc_b_actual_rev)
# This just wraps broadcast_dynamic_shape_extended, so nothing
# deeper is required.
result1 = dynamic_ragged_shape.broadcast_dynamic_shape(shape_a, shape_b)
self.assertShapeEq(shape_e, result1)
# Again, just a wrapper.
result2 = ragged_array_ops.broadcast_dynamic_shape(shape_a, shape_b)
self.assertShapeEq(shape_e, result2)
def testBroadcastDynamicShapeFirstLayer(self):
a_0 = constant_op.constant(1, dtypes.int64)
b_0 = constant_op.constant(3, dtypes.int64)
[a_layer, b_layer
] = dynamic_ragged_shape._broadcast_dynamic_shape_first_layer(a_0, b_0)
expected_a_layer = _LayerBroadcaster.from_gather_index([0, 0, 0])
expected_b_layer = _LayerBroadcaster.from_gather_index([0, 1, 2])
self.assertLayerBroadcasterEq(expected_a_layer, a_layer)
self.assertLayerBroadcasterEq(expected_b_layer, b_layer)
def testBroadcastDynamicShapeNextLayer(self):
a_1 = RowPartition.from_uniform_row_length(
1, nvals=1, nrows=1, dtype_hint=dtypes.int64)
b_1 = RowPartition.from_row_lengths([2, 1, 3], dtype_hint=dtypes.int64)
ac_0 = _LayerBroadcaster.from_gather_index(
constant_op.constant([0, 0, 0], dtype=dtypes.int64))
bc_0 = _LayerBroadcaster.from_gather_index(
constant_op.constant([0, 1, 2], dtype=dtypes.int64))
dynamic_ragged_shape._broadcast_dynamic_shape_next_layer_half_ragged(
ac_0, bc_0, a_1, b_1)
def testBroadcastDynamicShapeRaisesLeft(self):
shape = DynamicRaggedShape.from_tensor(constant_op.constant([1, 2, 3]))
with self.assertRaisesRegex(TypeError, 'shape_x must be'):
dynamic_ragged_shape.broadcast_dynamic_shape(1, shape)
def testBroadcastDynamicShapeRaisesRight(self):
shape = DynamicRaggedShape.from_tensor(constant_op.constant([1, 2, 3]))
with self.assertRaisesRegex(TypeError, 'shape_y must be'):
dynamic_ragged_shape.broadcast_dynamic_shape(shape, 1)
def testBroadcastToRaises(self):
rt = constant_op.constant([1, 2, 3])
with self.assertRaisesRegex(TypeError, 'shape must be'):
dynamic_ragged_shape.broadcast_to(rt, 1)
@parameterized.parameters([
dict(
x=[[10], [20], [30]], # shape=[3, 1]
lengths=[3, 2],
expected=[[10, 10], [20, 20], [30, 30]]),
dict(
x=[[10], [20], [30]], # shape=[3, 1]
lengths=[3, (3, 0, 2)],
expected=ragged_factory_ops.constant_value(
[[10, 10, 10], [], [30, 30]], dtype=np.int32)),
dict(
x=[[[1, 2, 3]], [[4, 5, 6]]], # shape = [2, 1, 3]
lengths=[2, (2, 3), 3],
expected=ragged_factory_ops.constant_value(
[[[1, 2, 3], [1, 2, 3]], [[4, 5, 6], [4, 5, 6], [4, 5, 6]]],
dtype=np.int32,
ragged_rank=1)),
dict(
x=[[[1]], [[2]]], # shape = [2, 1, 1]
lengths=[2, (2, 3), (0, 2, 1, 2, 0)],
expected=ragged_factory_ops.constant_value(
[[[], [1, 1]], [[2], [2, 2], []]], dtype=np.int32,
ragged_rank=2)),
dict(
x=10,
lengths=[3, (3, 0, 2)],
expected=ragged_factory_ops.constant_value([[10, 10, 10], [],
[10, 10]])),
dict(
x=ragged_factory_ops.constant_value([[[1], [2]], [[3]]],
ragged_rank=1),
lengths=[2, (2, 1), 2],
expected=ragged_factory_ops.constant_value(
[[[1, 1], [2, 2]], [[3, 3]]], ragged_rank=1)),
])
def testRaggedBroadcastTo(self, x, lengths, expected):
shape = DynamicRaggedShape.from_lengths(lengths)
result = dynamic_ragged_shape.broadcast_to(x, shape)
self.assertEqual(
getattr(result, 'num_row_partitions', 0),
getattr(expected, 'num_row_partitions', 0))
self.assertAllEqual(result, expected)
# broadcast_to just calls dynamic_ragged_shape.broadcast_to, so
# this should be sufficient.
result2 = ragged_array_ops.broadcast_to(x, shape)
self.assertAllEqual(result2, expected)
@parameterized.parameters([
dict(
doc='x.shape=[3, (D1)]; y.shape=[3, 1]; bcast.shape=[3, (D1)]',
x=ragged_factory_ops.constant_value([[1, 2, 3], [], [4, 5]],
dtype=np.int32),
y=[[10], [20], [30]],
expected=ragged_factory_ops.constant_value([[11, 12, 13], [],
[34, 35]])),
dict(
doc='x.shape=[3, (D1)]; y.shape=[]; bcast.shape=[3, (D1)]',
x=ragged_factory_ops.constant_value([[1, 2, 3], [], [4, 5]],
dtype=np.int32),
y=10,
expected=ragged_factory_ops.constant_value([[11, 12, 13], [],
[14, 15]])),
dict(
doc='x.shape=[1, (D1)]; y.shape=[3, 1]; bcast.shape=[3, (D1)]',
x=ragged_factory_ops.constant_value([[1, 2, 3]], dtype=np.int32),
y=[[10], [20], [30]],
expected=ragged_factory_ops.constant_value(
[[11, 12, 13], [21, 22, 23], [31, 32, 33]], dtype=np.int32)),
dict(
doc=('x.shape=[2, (D1), 1]; y.shape=[1, (D2)]; '
'bcast.shape=[2, (D1), (D2)]'),
x=ragged_factory_ops.constant_value([[[1], [2], [3]], [[4]]],
ragged_rank=1),
y=ragged_factory_ops.constant_value([[10, 20, 30]]),
expected=ragged_factory_ops.constant_value([[[11, 21,
31], [12, 22, 32],
[13, 23, 33]],
[[14, 24, 34]]])),
dict(
doc=('x.shape=[2, (D1), 1]; y.shape=[1, 1, 4]; '
'bcast.shape=[2, (D1), 4]'),
x=ragged_factory_ops.constant_value([[[10], [20]], [[30]]],
ragged_rank=1),
y=[[[1, 2, 3, 4]]],
expected=ragged_factory_ops.constant_value(
[[[11, 12, 13, 14], [21, 22, 23, 24]], [[31, 32, 33, 34]]],
ragged_rank=1)),
dict(
doc=('x.shape=[2, (D1), 2, 1]; y.shape=[2, (D2)]; '
'bcast.shape=[2, (D1), (2), (D2)'),
x=ragged_factory_ops.constant_value(
[[[[1], [2]], [[3], [4]]], [[[5], [6]]]], ragged_rank=1),
y=ragged_factory_ops.constant_value([[10, 20], [30]]),
expected=ragged_factory_ops.constant_value([[[[11, 21], [32]],
[[13, 23], [34]]],
[[[15, 25], [36]]]])),
])
def testRaggedAddWithBroadcasting(self, x, y, expected, doc):
del doc
expected_rrank = getattr(expected, 'num_row_partitions', 0)
x = ragged_tensor.convert_to_tensor_or_ragged_tensor(x, dtype=dtypes.int32)
y = ragged_tensor.convert_to_tensor_or_ragged_tensor(y, dtype=dtypes.int32)
result = x + y
result_rrank = getattr(result, 'num_row_partitions', 0)
self.assertEqual(expected_rrank, result_rrank)
if hasattr(expected, 'tolist'):
expected = expected.tolist()
self.assertAllEqual(result, expected)
@parameterized.parameters([
dict(lengths_a=[3, (1, 4, 2)], new_impl=True, op_max=10), # Actual ops: 5
dict(lengths_a=[3, (1, 4, 2)], new_impl=False, op_max=300),
])
def testAddSelf(self, lengths_a, new_impl, op_max, num_row_partitions_a=None):
if context.executing_eagerly():
return
shape_a0 = DynamicRaggedShape.from_lengths(
lengths_a, num_row_partitions=num_row_partitions_a)
rt_a = ragged_array_ops.ragged_reshape(
_lowest_primes(_num_elements_of_lengths(lengths_a)), shape_a0)
rt_b = rt_a
g = rt_a.flat_values.graph if ragged_tensor.is_ragged(rt_a) else rt_a.graph
nodes_at_a = len(g.as_graph_def().node)
if new_impl:
dynamic_ragged_shape.ragged_binary_elementwise_op_impl(
gen_math_ops.add_v2, rt_a, rt_b)
nodes_at_b = len(g.as_graph_def().node)
node_delta = nodes_at_b - nodes_at_a
self.assertLessEqual(node_delta, op_max)
else:
if isinstance(rt_a, RaggedTensor):
rt_a = rt_a.with_row_splits_dtype(dtypes.int32)
rt_b = rt_a
nodes_at_b = len(g.as_graph_def().node)
rt_a + rt_b # pylint: disable=pointless-statement
nodes_at_d = len(g.as_graph_def().node)
node_delta = nodes_at_d - nodes_at_b
self.assertLessEqual(node_delta, op_max)
def testAndSelfBool(self):
if context.executing_eagerly():
return
values = constant_op.constant([True, False, True, True, True])
rt_a = RaggedTensor.from_row_splits(values, [0, 3, 3, 5])
result = dynamic_ragged_shape.ragged_binary_elementwise_op_impl(
gen_math_ops.logical_and, rt_a, rt_a)
expected_values = values
expected = RaggedTensor.from_row_splits(expected_values, [0, 3, 3, 5])
self.assertAllEqual(result, expected)
def testEquals(self):
if context.executing_eagerly():
return
rt_a = ragged_factory_ops.constant([[3, 1, 3], [3]])
b = constant_op.constant(3)
rt_expected = ragged_factory_ops.constant([[True, False, True], [True]])
result = dynamic_ragged_shape.ragged_binary_elementwise_op_impl(
math_ops.equal, rt_a, b)
self.assertAllEqual(result, rt_expected)
def testEquals2(self):
splits = constant_op.constant([0, 1])
a = RaggedTensor.from_row_splits([[1, 2]], splits)
b = RaggedTensor.from_row_splits([[3, 4, 5]], splits)
self.assertIs(a == b, False)
def testEquals3(self):
a = RaggedTensor.from_row_splits([[1, 2]], [0, 1])
b = RaggedTensor.from_row_splits([[3, 4, 5]], [0, 1])
self.assertIs(a == b, False)
@parameterized.parameters([
dict(
lengths_a=[3, (1, 4, 2)], lengths_b=[], new_impl=True,
max_num_ops=5), # Actual ops: 1
dict(
lengths_a=[3, (1, 4, 2), 3, 2],
lengths_b=[3, 2],
new_impl=True,
max_num_ops=5), # Actual ops: 1
dict(
lengths_a=[3, (1, 4, 2)], lengths_b=[], new_impl=False,
max_num_ops=5), # Actual ops: 1
dict(
lengths_a=[3, (1, 4, 2), 3, 2],
lengths_b=[3, 2],
new_impl=False,
max_num_ops=5), # Actual ops: 1
])
def testAdd(self,
lengths_a,
lengths_b,
new_impl,
max_num_ops,
num_row_partitions_a=None,
num_row_partitions_b=None):
if context.executing_eagerly():
return
shape_a0 = DynamicRaggedShape.from_lengths(
lengths_a, num_row_partitions=num_row_partitions_a)
shape_b0 = DynamicRaggedShape.from_lengths(
lengths_b, num_row_partitions=num_row_partitions_b)
rt_a = ragged_array_ops.ragged_reshape(
_lowest_primes(_num_elements_of_lengths(lengths_a)), shape_a0)
rt_b = ragged_array_ops.ragged_reshape(
_lowest_primes(_num_elements_of_lengths(lengths_b)), shape_b0)
g = rt_a.flat_values.graph if ragged_tensor.is_ragged(rt_a) else rt_a.graph
nodes_at_a = len(g.as_graph_def().node)
if new_impl:
dynamic_ragged_shape.ragged_binary_elementwise_op_impl(
gen_math_ops.add_v2,
rt_a,
rt_b)
nodes_at_b = len(g.as_graph_def().node)
num_nodes = nodes_at_b - nodes_at_a
self.assertLessEqual(num_nodes, max_num_ops)
else:
if isinstance(rt_a, RaggedTensor):
rt_a = rt_a.with_row_splits_dtype(dtypes.int32)
if isinstance(rt_b, RaggedTensor):
rt_b = rt_b.with_row_splits_dtype(dtypes.int32)
nodes_at_b = len(g.as_graph_def().node)
rt_a + rt_b # pylint: disable=pointless-statement
nodes_at_d = len(g.as_graph_def().node)
num_nodes = nodes_at_d - nodes_at_b
@parameterized.parameters([
dict(
lengths_a=[3, (1, 4, 2)], lengths_b=[],
shape_e=[3, None], new_impl=False),
dict(
lengths_a=[3, (1, 4, 2)], lengths_b=[],
shape_e=[3, None], new_impl=True),
dict(
lengths_a=[5, (1, 4, 2, 1, 3), 3],
lengths_b=[5, 1, 3],
shape_e=[5, None, 3], new_impl=False),
dict(
lengths_a=[5, (1, 4, 2, 1, 3), 3],
lengths_b=[5, 1, 3],
shape_e=[5, None, 3], new_impl=True),
dict(
lengths_a=[3, 2, (1, 4, 2, 1, 3, 1), 3],
lengths_b=[3, 2, 1, 3],
shape_e=[3, 2, None, 3], new_impl=False),
dict(
lengths_a=[3, 2, (1, 4, 2, 1, 3, 1), 3],
lengths_b=[3, 2, 1, 3],
shape_e=[3, 2, None, 3],
new_impl=True),
dict(
lengths_a=[3, (1, 4, 2)], lengths_b=[3, 1],
shape_e=[3, None], new_impl=False),
dict(
lengths_a=[3, (1, 4, 2)], lengths_b=[3, 1],
shape_e=[3, None], new_impl=True),
])
def testAddShape(self,
lengths_a,
lengths_b,
shape_e,
new_impl=False,
num_row_partitions_a=None,
num_row_partitions_b=None):
if context.executing_eagerly():
return
shape_a = DynamicRaggedShape.from_lengths(
lengths_a, num_row_partitions=num_row_partitions_a)
shape_b = DynamicRaggedShape.from_lengths(
lengths_b, num_row_partitions=num_row_partitions_b)
rt_a = ragged_array_ops.ragged_reshape(
_lowest_primes(_num_elements_of_lengths(lengths_a)), shape_a)
rt_b = ragged_array_ops.ragged_reshape(
_lowest_primes(_num_elements_of_lengths(lengths_b)), shape_b)
if new_impl:
result = dynamic_ragged_shape.ragged_binary_elementwise_op_impl(
math_ops.add, rt_a, rt_b)
shape_e = tensor_shape.TensorShape(shape_e)
self.assertEqual(shape_e.as_list(), result.shape.as_list())
else:
if isinstance(rt_a, RaggedTensor):
rt_a = rt_a.with_row_splits_dtype(dtypes.int32)
if isinstance(rt_b, RaggedTensor):
rt_b = rt_b.with_row_splits_dtype(dtypes.int32)
result = rt_a + rt_b
shape_e = tensor_shape.TensorShape(shape_e)
self.assertEqual(shape_e.as_list(), result.shape.as_list())
@parameterized.parameters([
dict(
lengths_a=[3, (1, 4, 2)], lengths_b=[],
shape_e=[3, (1, 4, 2)]),
dict(
lengths_a=[5], lengths_b=[1],
shape_e=[5]),
dict(
lengths_a=[5, (1, 4, 2, 1, 3), 3],
lengths_b=[5, 1, 3],
shape_e=[5, None, 3]),
dict(
lengths_a=[3, 2, (1, 4, 2, 1, 3, 1), 3],
lengths_b=[3, 2, 1, 3],
shape_e=[3, 2, None, 3]),
dict(lengths_a=[3, (1, 4, 2)], lengths_b=[3, 1], shape_e=[3, None]),
dict(lengths_a=[5, 1, 3], lengths_b=[2, 3], shape_e=[5, 2, 3]),
dict(lengths_a=[5, 1, (3, 2, 4, 1, 3)], lengths_b=[2, 1],
shape_e=[5, 2, None]),
dict(lengths_a=[5, 4, 1, 3], lengths_b=[2, 1], shape_e=[5, 4, 2, 3]),
])
def testBroadcastDynamicShapeStatic(self,
lengths_a,
lengths_b,
shape_e,
num_row_partitions_a=None,
num_row_partitions_b=None):
if context.executing_eagerly():
return
shape_a = DynamicRaggedShape.from_lengths(
lengths_a, num_row_partitions=num_row_partitions_a)
shape_b = DynamicRaggedShape.from_lengths(
lengths_b, num_row_partitions=num_row_partitions_b)
result = dynamic_ragged_shape.broadcast_dynamic_shape(shape_a, shape_b)
result_shape = result._to_tensor_shape()
tensor_shape_e = [None if isinstance(x, tuple) else x for x in shape_e]
self.assertEqual(shape_e, result.static_lengths())
self.assertEqual(tensor_shape_e, result_shape.as_list())
def testBroadcastDynamicShapePartiallyKnown(self):
if context.executing_eagerly():
return
@def_function.function(
input_signature=[tensor.TensorSpec(None, dtypes.int64)])
def fun(x):
shape_a = DynamicRaggedShape([], array_ops_stack.stack([5, x, 3]))
shape_b = DynamicRaggedShape.from_lengths([1, 3], dtype=dtypes.int64)
result = dynamic_ragged_shape.broadcast_dynamic_shape(shape_a, shape_b)
self.assertAllEqual([5, None, 3], result.static_lengths())
fun(constant_op.constant(2, dtype=dtypes.int64))
def testBroadcastDynamicShapePartiallyKnownNiceToHave(self):
if context.executing_eagerly():
return
@def_function.function(
input_signature=[tensor.TensorSpec(None, dtypes.int64)])
def fun(x):
shape_a = DynamicRaggedShape([], array_ops_stack.stack([5, x, 3]))
shape_b = DynamicRaggedShape.from_lengths([2, 3], dtype=dtypes.int64)
result = dynamic_ragged_shape.broadcast_dynamic_shape(shape_a, shape_b)
self.assertAllEqual([5, 2, 3], result.static_lengths())
fun(constant_op.constant(2, dtype=dtypes.int64))
def testFromRowPartitionsStatic(self):
if context.executing_eagerly():
return
rp = RowPartition.from_row_lengths([4, 2, 3])
result = DynamicRaggedShape.from_row_partitions([rp])
self.assertEqual([3, (4, 2, 3)], result.static_lengths())
@parameterized.parameters([
dict(
lengths_a=[3, (1, 4, 2)], dim=0,
expected=3),
dict(
lengths_a=[5], dim=0,
expected=5),
dict(
lengths_a=[5, (1, 4, 2, 1, 3), 3],
dim=0,
expected=5),
dict(
lengths_a=[5, (1, 4, 2, 1, 3), 3],
dim=2,
expected=3),
dict(
lengths_a=[3, 2, (1, 4, 2, 1, 3, 1), 3],
dim=1,
expected=2),
dict(lengths_a=[5, 1, 3], dim=0, expected=5),
])
def testDimStatic(self, lengths_a, dim, expected):
if context.executing_eagerly():
return
shape_a = DynamicRaggedShape.from_lengths(lengths_a)
result = tensor_util.constant_value(shape_a[dim])
self.assertEqual(result, expected)
@parameterized.parameters([
dict(
lengths_a=[5, (1, 4, 2, 1, 3), 3],
shape_e=[5, (1, 4, 2, 1, 3), 3],
new_num_row_partitions=2), # Fails
dict(
lengths_a=[3, 2, (1, 4, 2, 1, 3, 1), 3],
shape_e=[3, 2, (1, 4, 2, 1, 3, 1), 3],
new_num_row_partitions=3), # Fails
])
def testNumRowPartitionShapeStatic(self,
lengths_a,
shape_e,
new_num_row_partitions,
num_row_partitions_a=None):
if context.executing_eagerly():
return
shape_a = DynamicRaggedShape.from_lengths(
lengths_a, num_row_partitions=num_row_partitions_a)
result = shape_a._with_num_row_partitions(new_num_row_partitions)
self.assertEqual(shape_e, result.static_lengths())
@parameterized.parameters([
dict(lengths_a=[5, (1, 4, 2, 1, 3), 3]),
dict(lengths_a=[3, 2, (1, 4, 2, 1, 3, 1), 3]),
])
def testFromLengthsNRowsStatic(self, lengths_a):
if context.executing_eagerly():
return
shape_a = DynamicRaggedShape.from_lengths(lengths_a)
for rp in shape_a.row_partitions:
actual = tensor_util.constant_value(rp.nrows())
self.assertIsNotNone(actual, 'Failed on ' + str(rp))
@parameterized.parameters([
dict(
lengths_a=[5, (1, 4, 2, 1, 3), 3], inner_shape=[33],
new_inner_rank=1),
dict(
lengths_a=[3, 2, (1, 4, 2, 1, 3, 1), 3],
inner_shape=[36],
new_inner_rank=1),
dict(
lengths_a=[3, 2, (1, 4, 2, 1, 3, 1), 3, 4],
inner_shape=[36, 4],
new_inner_rank=2),
])
def testAltInnerShapeStatic(self,
lengths_a,
inner_shape,
new_inner_rank,
num_row_partitions_a=None):
if context.executing_eagerly():
return
shape_a = DynamicRaggedShape.from_lengths(
lengths_a, num_row_partitions=num_row_partitions_a)
result = shape_a._alt_inner_shape(new_inner_rank)
result_static = tensor_util.constant_value_as_shape(result)
self.assertEqual(inner_shape, result_static.as_list())
@parameterized.parameters([
dict(
lengths=[3, (1, 4, 2)],
shape_e=[3, None]),
dict(
lengths=[3, (1, 4, 2)],
shape_e=[3, None]),
dict(
lengths=[5, (1, 4, 2, 1, 3), 3],
shape_e=[5, None, 3]),
dict(
lengths=[5, (1, 4, 2, 1, 3), 3],
shape_e=[5, None, 3]),
dict(
lengths=[3, 2, (1, 4, 2, 1, 3, 1), 3],
shape_e=[3, 2, None, 3]),
dict(
lengths=[3, 2, (1, 4, 2, 1, 3, 1), 3],
shape_e=[3, 2, None, 3]),
])
def testStaticShape(self,
lengths,
shape_e,
num_row_partitions=None):
# Testing the shape has enough information.
# In particular, any uniform_row_length should be reproduced.
if context.executing_eagerly():
return
shape = DynamicRaggedShape.from_lengths(
lengths, num_row_partitions=num_row_partitions)
rt_a = ragged_array_ops.ragged_reshape(
_lowest_primes(_num_elements_of_lengths(lengths)), shape)
shape_e = tensor_shape.TensorShape(shape_e)
self.assertEqual(shape_e.as_list(), rt_a.shape.as_list())
@parameterized.parameters([
dict(
lengths=[5, (1, 4, 2, 1, 3), 3],
shape_e=[5, (1, 4, 2, 1, 3), 3]),
dict(
lengths=[3, 2, (1, 4, 2, 1, 3, 1), 3],
shape_e=[3, 2, (1, 4, 2, 1, 3, 1), 3]),
])
def testWithNumRowPartitionsStatic(self,
lengths,
shape_e,
num_row_partitions=None):
# Note that this test loses the later static values.
if context.executing_eagerly():
return
shape = DynamicRaggedShape.from_lengths(
lengths, num_row_partitions=num_row_partitions)
shape_b = shape._with_num_row_partitions(shape.rank - 1)
self.assertEqual(shape_e, shape_b.static_lengths())
def testWithNumRowPartitionsStaticAlt(self):
# Note that this test loses the later static values.
if context.executing_eagerly():
return
shape = DynamicRaggedShape.from_lengths(
[5, 2, 3], num_row_partitions=2)
shape_b = shape._with_num_row_partitions(0)
self.assertEqual([5, 2, 3], shape_b.static_lengths())
def testWithNumRowPartitionsDType(self):
# Note that this test loses the later static values.
shape = DynamicRaggedShape([], constant_op.constant([5, 2, 3],
dtype=dtypes.int32))
self.assertEqual(shape.dtype, dtypes.int32)
result = shape._with_num_row_partitions(2)
self.assertEqual(result.dtype, dtypes.int32)
def test_merge_with(self):
original = DynamicRaggedShape.from_lengths([2, (3, 5), 6])
result = original._merge_with(original)
self.assertShapeEq(result, original)
def test_merge_with_spec(self):
original = DynamicRaggedShape.from_lengths([2, (3, 5), 6],
dtype=dtypes.int64)
spec = DynamicRaggedShape.Spec(
row_partitions=[
RowPartitionSpec(nrows=2,
nvals=8,
dtype=dtypes.int64)
],
static_inner_shape=tensor_shape.TensorShape([8, 6]),
dtype=dtypes.int64)
result = original._merge_with_spec(spec)
self.assertShapeEq(result, original)
def test_merge_with_spec_raises(self):
original = DynamicRaggedShape.from_lengths([2, (3, 5), 6],
dtype=dtypes.int64)
spec = DynamicRaggedShape.Spec(
row_partitions=[
RowPartitionSpec(nrows=2,
nvals=8,
dtype=dtypes.int32)
],
static_inner_shape=tensor_shape.TensorShape([8, 6]),
dtype=dtypes.int32)
with self.assertRaisesRegex(
ValueError,
'RowPartition and RowPartitionSpec are not compatible'):
original._merge_with_spec(spec)
def test_merge_with_spec_uniform(self):
original = DynamicRaggedShape.from_lengths(
[2, (4, 4), 6], dtype=dtypes.int64)
spec = DynamicRaggedShape.Spec._from_tensor_shape(
tensor_shape.TensorShape([2, 4, 6]),
num_row_partitions=0,
dtype=dtypes.int64)
result = original._merge_with_spec(spec)
original = DynamicRaggedShape.from_lengths([2, 4, 6],
num_row_partitions=1,
dtype=dtypes.int64)
self.assertShapeEq(result, original)
@parameterized.parameters([
dict(
doc='x.shape=[3, (D1)]; y.shape=[3, 1]; bcast.shape=[3, (D1)]',
x=ragged_factory_ops.constant_value([[1, 2, 3], [], [4, 5]],
dtype=np.int32),
y=[[10], [20], [30]],
expected=ragged_factory_ops.constant_value([[11, 12, 13], [],
[34, 35]])),
dict(
doc='x.shape=[3, (D1)]; y.shape=[]; bcast.shape=[3, (D1)]',
x=ragged_factory_ops.constant_value([[1, 2, 3], [], [4, 5]],
dtype=np.int32),
y=10,
expected=ragged_factory_ops.constant_value([[11, 12, 13], [],
[14, 15]])),
dict(
doc='x.shape=[1, (D1)]; y.shape=[3, 1]; bcast.shape=[3, (D1)]',
x=ragged_factory_ops.constant_value([[1, 2, 3]], dtype=np.int32),
y=[[10], [20], [30]],
expected=ragged_factory_ops.constant_value(
[[11, 12, 13], [21, 22, 23], [31, 32, 33]], dtype=np.int32)),
dict(
doc=('x.shape=[2, (D1), 1]; y.shape=[1, (D2)]; '
'bcast.shape=[2, (D1), (D2)]'),
x=ragged_factory_ops.constant_value([[[1], [2], [3]], [[4]]],
ragged_rank=1),
y=ragged_factory_ops.constant_value([[10, 20, 30]]),
expected=ragged_factory_ops.constant_value([[[11, 21,
31], [12, 22, 32],
[13, 23, 33]],
[[14, 24, 34]]])),
dict(
doc=('x.shape=[2, (D1), 1]; y.shape=[1, 1, 4]; '
'bcast.shape=[2, (D1), 4]'),
x=ragged_factory_ops.constant_value([[[10], [20]], [[30]]],
ragged_rank=1),
y=[[[1, 2, 3, 4]]],
expected=ragged_factory_ops.constant_value(
[[[11, 12, 13, 14], [21, 22, 23, 24]], [[31, 32, 33, 34]]],
ragged_rank=1)),
dict(
doc=('x.shape=[2, (D1), 2, 1]; y.shape=[2, (D2)]; '
'bcast.shape=[2, (D1), (2), (D2)'),
x=ragged_factory_ops.constant_value(
[[[[1], [2]], [[3], [4]]], [[[5], [6]]]], ragged_rank=1),
y=ragged_factory_ops.constant_value([[10, 20], [30]]),
expected=ragged_factory_ops.constant_value([[[[11, 21], [32]],
[[13, 23], [34]]],
[[[15, 25], [36]]]])),
])
def testRaggedDispatchImplWithBroadcasting(self, x, y, expected, doc):
del doc
expected_rrank = getattr(expected, 'num_row_partitions', 0)
x = ragged_tensor.convert_to_tensor_or_ragged_tensor(x, dtype=dtypes.int32)
y = ragged_tensor.convert_to_tensor_or_ragged_tensor(y, dtype=dtypes.int32)
result = dynamic_ragged_shape.ragged_binary_elementwise_op_impl(
gen_math_ops.add_v2, x, y)
result_rrank = getattr(result, 'num_row_partitions', 0)
self.assertEqual(expected_rrank, result_rrank)
if hasattr(expected, 'tolist'):
expected = expected.tolist()
self.assertAllEqual(result, expected)
def testDimensions(self):
a = DynamicRaggedShape._from_inner_shape([1, 2, 3])
self.assertAllEqual(1, a._dimension(0))
def testGetItemIsInstanceTensor(self):
a = dynamic_ragged_shape.DynamicRaggedShape._from_inner_shape([1, 2, 3])
self.assertIsInstance(a[0], tensor.Tensor)
@parameterized.parameters([
dict(
lengths=[2, 2],
num_row_partitions=1,
expected=[2, 2]),
dict(lengths=[2, 2], num_row_partitions=0, expected=[2, 2]),
dict(
lengths=[2, (1, 2), 2], num_row_partitions=1, expected=[2, (1, 2), 2])
])
def testStaticLengths(self,
lengths,
num_row_partitions,
expected,
expected_eager=None):
a = DynamicRaggedShape.from_lengths(lengths)._with_num_row_partitions(
num_row_partitions)
actual = a.static_lengths()
if context.executing_eagerly() and expected_eager is not None:
self.assertAllEqual(expected_eager, actual)
else:
self.assertAllEqual(expected, actual)
def testStaticLengthsUnknown(self):
@def_function.function(
input_signature=[tensor.TensorSpec(None, dtypes.int32)])
def foo(row_lengths):
a = DynamicRaggedShape([RowPartition.from_row_lengths(row_lengths)], [6])
actual = a.static_lengths()
self.assertAllEqual([None, None], actual)
foo([3, 3])
def testStaticLengthsRankUnknown(self):
# Note that the rank of the shape is unknown, so we can only provide a
# prefix of the lengths.
@def_function.function(
input_signature=[tensor.TensorSpec(None, dtypes.int32)])
def foo(inner_shape):
a = DynamicRaggedShape([RowPartition.from_row_lengths([3, 3])],
inner_shape)
actual = a.static_lengths()
self.assertAllEqual([2, (3, 3), ...], actual)
foo([6, 3])
def testReprRankKnown(self):
a = DynamicRaggedShape.from_lengths([2, (1, 2), 3])
actual = str(a)
self.assertEqual(
'<DynamicRaggedShape lengths=[2, (1, 2), 3] num_row_partitions=1>',
actual)
def assertDimsEqual(self, x: tensor_shape.TensorShape,
y: tensor_shape.TensorShape):
if x.rank is None:
self.assertIsNone(
y.rank,
'x has an unknown rank, but y does not: x={}, y={}'.format(x, y))
return
self.assertIsNotNone(
y.rank,
'y has an unknown rank, but x does not: x={}, y={}'.format(x, y))
self.assertAllEqual(x.as_list(), y.as_list())
def testToTensorShapeRankKnown(self):
a = DynamicRaggedShape.from_lengths([2, (1, 2), 3])
actual = a._to_tensor_shape()
self.assertDimsEqual(tensor_shape.TensorShape([2, None, 3]), actual)
def testReprRankUnknown(self):
@def_function.function(
input_signature=[tensor.TensorSpec(None, dtypes.int32)])
def foo(inner_shape):
a = DynamicRaggedShape([RowPartition.from_row_lengths([3, 3])],
inner_shape)
actual = str(a)
self.assertEqual(
'<DynamicRaggedShape lengths=[2, (3, 3), ...] num_row_partitions=1>',
actual)
foo([6, 3])
def testToTensorShapeRankUnknown(self):
@def_function.function(
input_signature=[tensor.TensorSpec(None, dtypes.int32)])
def foo(inner_shape):
a = DynamicRaggedShape([RowPartition.from_row_lengths([3, 3])],
inner_shape)
actual = a._to_tensor_shape()
self.assertDimsEqual(
tensor_shape.TensorShape(None), actual)
foo([6, 3])
def testBroadcastDynamicShapeExtendedRankOne(self):
a = DynamicRaggedShape._from_inner_shape([1])
b = DynamicRaggedShape._from_inner_shape([3])
(c, ac, bc) = dynamic_ragged_shape.broadcast_dynamic_shape_extended(a, b)
expected_c = DynamicRaggedShape._from_inner_shape([3])
self.assertShapeEq(c, expected_c)
ac_result = ac.broadcast(constant_op.constant([4]))
self.assertAllEqual(ac_result, [4, 4, 4])
bc_result = bc.broadcast(constant_op.constant([4, 7, 1]))
self.assertAllEqual(bc_result, [4, 7, 1])
def testBroadcastDynamicShapeExtendedRankOneRev(self):
a = DynamicRaggedShape._from_inner_shape([3])
b = DynamicRaggedShape._from_inner_shape([1])
(c, ac, bc) = dynamic_ragged_shape.broadcast_dynamic_shape_extended(a, b)
expected_c = DynamicRaggedShape._from_inner_shape([3])
self.assertShapeEq(c, expected_c)
bc_result = bc.broadcast(constant_op.constant([4]))
self.assertAllEqual(bc_result, [4, 4, 4])
ac_result = ac.broadcast(constant_op.constant([4, 7, 1]))
self.assertAllEqual(ac_result, [4, 7, 1])
def testBroadcastDynamicShapeExtendedRankOneIdentity(self):
a = DynamicRaggedShape._from_inner_shape([3])
b = DynamicRaggedShape._from_inner_shape([3])
(c, ac, bc) = dynamic_ragged_shape.broadcast_dynamic_shape_extended(a, b)
expected_c = DynamicRaggedShape._from_inner_shape([3])
self.assertShapeEq(c, expected_c)
bc_result = bc.broadcast(constant_op.constant([4, 7, 1]))
self.assertAllEqual(bc_result, [4, 7, 1])
ac_result = ac.broadcast(constant_op.constant([4, 7, 1]))
self.assertAllEqual(ac_result, [4, 7, 1])
def testFromGatherLayerIndexRaises(self):
bad_gather_index = constant_op.constant([0.0, 0.5, 1.0])
with self.assertRaisesRegex(ValueError, 'gather_index must be'):
_LayerBroadcaster.from_gather_index(bad_gather_index)
### Tests mostly for code coverage ###########################################
def testFindPreferredDtypeIntNone(self):
actual = dynamic_ragged_shape._find_dtype(3, None)
self.assertIsNone(actual)
@parameterized.parameters([
dict(
source_shape=lambda: DynamicRaggedShape._from_inner_shape([3]),
target_shape=lambda: DynamicRaggedShape._from_inner_shape([3]),
layer_broadcasters=lambda: [int],
dtype=None,
error_type=TypeError,
error_regex=r'Not a LayerBroadcaster'),
dict(
source_shape=lambda: DynamicRaggedShape._from_inner_shape([3]),
target_shape=lambda: DynamicRaggedShape._from_inner_shape([3]),
layer_broadcasters=lambda: _LayerBroadcaster.from_gather_index(
[0, 1, 2]),
dtype=None,
error_type=TypeError,
error_regex=r'layer'),
dict(
source_shape=lambda: DynamicRaggedShape._from_inner_shape([3]),
target_shape=lambda: None,
layer_broadcasters=lambda:
[_LayerBroadcaster.from_gather_index([0, 1, 2])],
dtype=None,
error_type=TypeError,
error_regex='target_shape is not a DynamicRaggedShape'),
dict(
source_shape=lambda: None,
target_shape=lambda: DynamicRaggedShape._from_inner_shape([3]),
layer_broadcasters=lambda:
[_LayerBroadcaster.from_gather_index([0, 1, 2])],
dtype=None,
error_type=TypeError,
error_regex='source_shape is not a DynamicRaggedShape')
])
def testBroadcasterInitRaises(self, source_shape, target_shape,
layer_broadcasters, dtype, error_type,
error_regex):
source_shape = source_shape()
target_shape = target_shape()
layer_broadcasters = layer_broadcasters()
with self.assertRaisesRegex(error_type, error_regex):
dynamic_ragged_shape._Broadcaster(
source_shape, target_shape, layer_broadcasters, dtype=dtype)
def testBroadcasterRepr(self):
source_shape = DynamicRaggedShape(
[RowPartition.from_row_splits(constant_op.constant([0, 1, 2]))],
constant_op.constant([3]))
target_shape = DynamicRaggedShape(
[RowPartition.from_row_splits(constant_op.constant([0, 1, 2]))],
constant_op.constant([3]))
layer_broadcasters = [
_LayerBroadcaster.from_gather_index(constant_op.constant([0, 1, 2])),
_LayerBroadcaster.from_gather_index(constant_op.constant([0, 1, 2]))
]
bc = dynamic_ragged_shape._Broadcaster(source_shape, target_shape,
layer_broadcasters)
actual = str(bc)
self.assertRegex(actual, '.src_shape..DynamicRaggedShape')
def testBroadcasterWithDtype(self):
source_shape = DynamicRaggedShape(
[RowPartition.from_row_splits(constant_op.constant([0, 1, 2]))],
constant_op.constant([3]))
target_shape = DynamicRaggedShape(
[RowPartition.from_row_splits(constant_op.constant([0, 1, 2]))],
constant_op.constant([3]))
layer_broadcasters = [
_LayerBroadcaster.from_gather_index(constant_op.constant([0, 1, 2])),
_LayerBroadcaster.from_gather_index(constant_op.constant([0, 1, 2]))
]
bc = dynamic_ragged_shape._Broadcaster(
source_shape, target_shape, layer_broadcasters, dtype=dtypes.int32)
bc2 = bc.with_dtype(dtypes.int64)
self.assertEqual(bc2.dtype, dtypes.int64)
# TODO(martinz): This doesn't work for ragged_tensor_shape.
# Uncomment when we switch over the implementation.
# dict(dtype=dtypes.int32)
@parameterized.parameters([
dict(dtype=dtypes.int64)
])
def testBroadcasterWithDenseDType(self, dtype):
a = constant_op.constant([[4]])
b = RaggedTensor.from_row_splits([[2], [3], [4], [5]], [0, 3, 4])
b = b.with_row_splits_dtype(dtype)
c = a + b
self.assertEqual(c.row_splits.dtype, dtype)
d = b + a
self.assertEqual(d.row_splits.dtype, dtype)
@parameterized.parameters([
dict(dtype_left=dtypes.int64,
dtype_right=dtypes.int32),
dict(dtype_left=dtypes.int32,
dtype_right=dtypes.int64)])
def testBroadcastWithDifferentDenseShapeDTypes(self, dtype_left,
dtype_right):
s_left = DynamicRaggedShape._from_inner_shape(
constant_op.constant([4, 1], dtype_left))
s_right = DynamicRaggedShape._from_inner_shape(
constant_op.constant([1, 4], dtype_right))
s_result = dynamic_ragged_shape.broadcast_dynamic_shape(s_left, s_right)
self.assertEqual(s_result.dtype, dtypes.int64)
def testBroadcastFlatValuesToDenseExpand(self):
source = RaggedTensor.from_uniform_row_length([0, 1, 2, 3], 2)
target_shape = DynamicRaggedShape._from_inner_shape([1, 2, 2])
broadcaster = dynamic_ragged_shape._get_broadcaster(
DynamicRaggedShape.from_tensor(source), target_shape)
flat_values = broadcaster.broadcast_flat_values(source)
self.assertAllEqual(flat_values, [[[0, 1], [2, 3]]])
# TODO(edloper): Confirm that this is the expected behavior.
def testBroadcastFlatValuesToDenseExpandInnerDimensionsFalse(self):
source = RaggedTensor.from_uniform_row_length([0, 1, 2, 3], 2)
target_shape = DynamicRaggedShape._from_inner_shape([1, 2, 2])
broadcaster = dynamic_ragged_shape._get_broadcaster(
DynamicRaggedShape.from_tensor(source), target_shape)
flat_values = broadcaster.broadcast_flat_values(
source, inner_dimensions=False)
self.assertAllEqual(flat_values, [[0, 1], [2, 3]])
def testGetLayerBroadcastersFromRPSRaisesTypeError(self):
with self.assertRaisesRegex(TypeError, 'Not a _LayerBroadcaster'):
dynamic_ragged_shape._get_layer_broadcasters_from_rps(int, [], [])
def testGetBroadcasterRankDrop(self):
with self.assertRaisesRegex(ValueError, 'Cannot broadcast'):
a = DynamicRaggedShape._from_inner_shape([3, 4, 5])
b = DynamicRaggedShape._from_inner_shape([4, 5])
dynamic_ragged_shape._get_broadcaster(a, b)
@parameterized.parameters([
dict(
ac_0=lambda: _LayerBroadcaster.from_gather_index([0, 1, 2]),
bc_0=lambda: _LayerBroadcaster.from_gather_index([0, 1, 2]),
a_1=lambda: RowPartition.from_row_splits([0, 1, 2]),
b_1=lambda: None,
error_type=TypeError,
error_regex='b_1 should be a RowPartition'),
dict(
ac_0=lambda: None,
bc_0=lambda: _LayerBroadcaster.from_gather_index([0, 1, 2]),
a_1=lambda: RowPartition.from_row_splits([0, 1, 2]),
b_1=lambda: RowPartition.from_row_splits([0, 1, 2]),
error_type=TypeError,
error_regex='ac_0 should be a _LayerBroadcaster'),
dict(
ac_0=lambda: _LayerBroadcaster.from_gather_index([0, 1, 2]),
bc_0=lambda: None,
a_1=lambda: RowPartition.from_row_splits([0, 1, 2]),
b_1=lambda: RowPartition.from_row_splits([0, 1, 2]),
error_type=TypeError,
error_regex='bc_0 should be a _LayerBroadcaster'),
dict(
ac_0=lambda: _LayerBroadcaster.from_gather_index([0, 1, 2]),
bc_0=lambda: _LayerBroadcaster.from_gather_index([0, 1, 2]),
a_1=lambda: None,
b_1=lambda: RowPartition.from_row_splits([0, 1, 2]),
error_type=TypeError,
error_regex='a_1 should be a RowPartition')
])
def testBroadcastDynamicShapeNextLayerHalfRaggedRaises(
self, ac_0, bc_0, a_1, b_1, error_type, error_regex):
ac_0 = ac_0()
bc_0 = bc_0()
a_1 = a_1()
b_1 = b_1()
with self.assertRaisesRegex(error_type, error_regex):
dynamic_ragged_shape._broadcast_dynamic_shape_next_layer_half_ragged(
ac_0, bc_0, a_1, b_1)
@parameterized.parameters([
dict(
ac_0=lambda: _LayerBroadcaster.from_gather_index([0, 1, 2]),
bc_0=lambda: _LayerBroadcaster.from_gather_index([0, 1, 2]),
a_1=lambda: RowPartition.from_row_splits([0, 1, 2]),
b_1=lambda: None,
error_type=TypeError,
error_regex='b_1 should be a RowPartition'),
dict(
ac_0=lambda: None,
bc_0=lambda: _LayerBroadcaster.from_gather_index([0, 1, 2]),
a_1=lambda: RowPartition.from_row_splits([0, 1, 2]),
b_1=lambda: RowPartition.from_row_splits([0, 1, 2]),
error_type=TypeError,
error_regex='ac_0 should be a _LayerBroadcaster'),
dict(
ac_0=lambda: _LayerBroadcaster.from_gather_index([0, 1, 2]),
bc_0=lambda: None,
a_1=lambda: RowPartition.from_row_splits([0, 1, 2]),
b_1=lambda: RowPartition.from_row_splits([0, 1, 2]),
error_type=TypeError,
error_regex='bc_0 should be a _LayerBroadcaster'),
dict(
ac_0=lambda: _LayerBroadcaster.from_gather_index([0, 1, 2]),
bc_0=lambda: _LayerBroadcaster.from_gather_index([0, 1, 2]),
a_1=lambda: None,
b_1=lambda: RowPartition.from_row_splits([0, 1, 2]),
error_type=TypeError,
error_regex='a_1 should be a RowPartition')
])
def testBroadcastDynamicShapeNextLayerBothUniformRaises(
self, ac_0, bc_0, a_1, b_1, error_type, error_regex):
ac_0 = ac_0()
bc_0 = bc_0()
a_1 = a_1()
b_1 = b_1()
with self.assertRaisesRegex(error_type, error_regex):
dynamic_ragged_shape._broadcast_dynamic_shape_next_layer_both_uniform(
ac_0, bc_0, a_1, b_1)
@parameterized.parameters([
dict(
ac_0=lambda: _LayerBroadcaster.from_gather_index([0, 1, 2]),
bc_0=lambda: _LayerBroadcaster.from_gather_index([0, 1, 2]),
a_1=lambda: RowPartition.from_row_splits([0, 1, 2]),
b_1=lambda: None,
error_type=TypeError,
error_regex='b_1 should be a RowPartition'),
dict(
ac_0=lambda: None,
bc_0=lambda: _LayerBroadcaster.from_gather_index([0, 1, 2]),
a_1=lambda: RowPartition.from_row_splits([0, 1, 2]),
b_1=lambda: RowPartition.from_row_splits([0, 1, 2]),
error_type=TypeError,
error_regex='ac_0 should be a _LayerBroadcaster'),
dict(
ac_0=lambda: _LayerBroadcaster.from_gather_index([0, 1, 2]),
bc_0=lambda: None,
a_1=lambda: RowPartition.from_row_splits([0, 1, 2]),
b_1=lambda: RowPartition.from_row_splits([0, 1, 2]),
error_type=TypeError,
error_regex='bc_0 should be a _LayerBroadcaster'),
dict(
ac_0=lambda: _LayerBroadcaster.from_gather_index([0, 1, 2]),
bc_0=lambda: _LayerBroadcaster.from_gather_index([0, 1, 2]),
a_1=lambda: None,
b_1=lambda: RowPartition.from_row_splits([0, 1, 2]),
error_type=TypeError,
error_regex='a_1 should be a RowPartition')
])
def testBroadcastDynamicShapeNextLayerRaises(self, ac_0, bc_0, a_1, b_1,
error_type, error_regex):
ac_0 = ac_0()
bc_0 = bc_0()
a_1 = a_1()
b_1 = b_1()
with self.assertRaisesRegex(error_type, error_regex):
dynamic_ragged_shape._broadcast_dynamic_shape_next_layer(
ac_0, bc_0, a_1, b_1)
@parameterized.parameters([
dict(
left_dtype=dtypes.int64,
right_dtype=dtypes.int64,
expected_dtype=dtypes.int64),
dict(
left_dtype=dtypes.int32,
right_dtype=dtypes.int32,
expected_dtype=dtypes.int32)
])
def testAddingRowSplits(self, left_dtype, right_dtype, expected_dtype):
x = ragged_factory_ops.constant([[1, 2]]).with_row_splits_dtype(left_dtype)
y = ragged_factory_ops.constant([[1, 2]]).with_row_splits_dtype(right_dtype)
z = math_ops.add(x, y)
self.assertEqual(z.row_splits.dtype, expected_dtype)
@parameterized.parameters([
dict(left_dtype=dtypes.int32, right_dtype=dtypes.int64),
dict(left_dtype=dtypes.int64, right_dtype=dtypes.int32),
])
def testAddingRowSplitsError(self, left_dtype, right_dtype):
x = ragged_factory_ops.constant([[1, 2]]).with_row_splits_dtype(left_dtype)
y = ragged_factory_ops.constant([[1, 2]]).with_row_splits_dtype(right_dtype)
with self.assertRaisesRegex(
ValueError, 'Input RaggedTensors have mismatched row_splits dtypes'):
math_ops.add(x, y)
def testAddRowPartitionsInvalidV1(self):
if not context.executing_eagerly():
return
with self.assertRaisesRegex(
(errors_impl.InvalidArgumentError, ValueError),
'Last row partition does not match flat_values.'):
rt = ragged_factory_ops.constant([[3], [4, 5], [6]])
rt_shape = DynamicRaggedShape.from_tensor(rt)
new_flat_values = constant_op.constant(['a', 'b', 'c', 'd', 'e'])
rt_shape._add_row_partitions(new_flat_values, validate=True)
# Example #1:
# [2, (3, 1), 5], num_row_partitions = 1, outer_axis = 0, inner_axis = 1.
# Result: [4, 5], num_row_partitions = 0.
# Example #2:
# [2, (2, 1), (7, 8, 9), 5], num_row_partitions = 2, outer_axis = 1,
# inner_axis = 2.
# Result: [2, (15, 9), 5], num_row_partitions = 1.
# Example #3:
# [2, (2, 1), (7, 8, 9), 5], num_row_partitions = 2, outer_axis = 0,
# inner_axis = 1.
# Result: [(7, 8, 9), 5], num_row_partitions = 1.
# Here, we are merging the tail of the row_partitions,
# but the inner_shape is unchanged.
@parameterized.parameters([
# NOOP
dict(
lengths=[2, (3, 1), 5],
num_row_partitions=1,
outer_axis=1,
inner_axis=1,
expected_lengths=[2, (3, 1), 5],
expected_num_row_partitions=1),
# Where num_row_partitions == 0
dict(
lengths=[2, 7, 5, 4],
num_row_partitions=0,
outer_axis=1,
inner_axis=2,
expected_lengths=[2, 35, 4],
expected_num_row_partitions=0),
# Where inner_axis <= self.num_row_partitions
dict(
lengths=[2, (3, 1), 5],
num_row_partitions=1,
outer_axis=0,
inner_axis=1,
expected_lengths=[4, 5],
expected_num_row_partitions=0),
dict(
lengths=[2, (2, 1), (7, 8, 9), 5],
num_row_partitions=2,
outer_axis=1,
inner_axis=2,
expected_lengths=[2, (15, 9), 5],
expected_num_row_partitions=1),
# outer_axis > num_row_partitions (only inner_shape changed)
dict(
lengths=[2, (1, 2), 5, 3],
num_row_partitions=1,
outer_axis=2,
inner_axis=3,
expected_lengths=[2, (1, 2), 15],
expected_num_row_partitions=1),
# outer_axis <= num_row_partitions
# inner_axis > num_row_partitions (everything changes)
# (If outer_axis == 0, all row_partitions are truncated).
dict(
lengths=[2, (2, 1), (7, 8, 9), 2, 5],
num_row_partitions=2,
outer_axis=0,
inner_axis=3,
expected_lengths=[48, 5],
expected_num_row_partitions=0),
dict(
lengths=[2, (2, 1), (7, 8, 9), 2, 5],
num_row_partitions=2,
outer_axis=1,
inner_axis=3,
expected_lengths=[2, (30, 18), 5],
expected_num_row_partitions=1),
])
def test_merge_dims(self, lengths, num_row_partitions, outer_axis, inner_axis,
expected_lengths, expected_num_row_partitions):
original = DynamicRaggedShape.from_lengths(
lengths, num_row_partitions=num_row_partitions)
actual = original._merge_dims(outer_axis, inner_axis)
expected = DynamicRaggedShape.from_lengths(expected_lengths,
expected_num_row_partitions)
self.assertShapeEq(actual, expected)
def test_merge_dims_special(self):
rt = ragged_factory_ops.constant([[[1, 2], [3]], [[4]]])
original = DynamicRaggedShape.from_tensor(rt)
actual = original._merge_dims(0, 1)
self.assertAllEqual(actual[0], 3)
def testGetItemRankNoneTruncate(self):
@def_function.function(
input_signature=[tensor.TensorSpec(None, dtypes.int32)])
def foo(x):
rts = DynamicRaggedShape.from_tensor(x)
actual = rts[:1]
self.assertShapeEq(rts, actual)
foo([1, 2, 3])
def test_dataset_only_dense(self):
ragged = DynamicRaggedShape.from_lengths([4, 5, 2, 3])
dataset_ops.DatasetV2.from_tensors(ragged)
def test_dataset_only_ragged(self):
ragged = DynamicRaggedShape.from_lengths([4, (3, 0, 4, 5), 2, 3])
dataset_ops.DatasetV2.from_tensors(ragged)
def test_ragged_dataset(self):
rt = RaggedTensor.from_row_splits(array_ops.zeros([5, 2, 3]), [0, 3, 5])
dataset_ops.DatasetV2.from_tensors(rt)
def test_ones_shape(self):
ragged = DynamicRaggedShape.from_lengths([4, (3, 0, 4, 5)])
ones = dynamic_ragged_shape.ones(ragged, dtype=bool)
sh2 = DynamicRaggedShape.from_tensor(ones)
self.assertAllEqual(sh2.static_lengths(), [4, (3, 0, 4, 5)])
def test_dataset_only_simple_ragged(self):
ragged = DynamicRaggedShape.from_lengths([4, (3, 0, 4, 5)])
dataset_ops.DatasetV2.from_tensors(ragged)
# ValueError: _to_batched_tensor_list doesn't support ragged_rank=0 yet
def test_unbatch_batch_dense(self):
ragged = DynamicRaggedShape.from_lengths([4, 5, 2, 3])
ds = dataset_ops.DatasetV2.from_tensors(ragged)
dsu = ds.unbatch()
if context.executing_eagerly():
values = list(dsu)
self.assertAllEqual(values[0].static_lengths(), [5, 2, 3])
self.assertAllEqual(values[2].static_lengths(), [5, 2, 3])
dsb = dsu.batch(2)
if context.executing_eagerly():
valuesb = list(dsb)
self.assertAllEqual(valuesb[0].static_lengths(), [2, 5, 2, 3])
self.assertAllEqual(valuesb[1].static_lengths(), [2, 5, 2, 3])
def test_unbatch_batch_values_shape_0(self):
batched = DynamicRaggedShape.from_lengths([2])
batch_size = 2
ds = dataset_ops.Dataset.from_tensors(batched)
ds2 = ds.unbatch()
if context.executing_eagerly():
v = list(ds2.batch(batch_size))
self.assertAllEqual(v[0], batched)
def test_unbatch_batch_values_shape_1(self):
batched = DynamicRaggedShape.from_lengths([2, 3])
rebatched = DynamicRaggedShape.from_lengths([2, 3], num_row_partitions=1)
batch_size = 2
ds = dataset_ops.Dataset.from_tensors(batched)
ds2 = ds.unbatch()
if context.executing_eagerly():
v = list(ds2.batch(batch_size))
self.assertAllEqual(v[0], rebatched)
def test_unbatch_dense_matrix(self):
ragged = DynamicRaggedShape.from_lengths([2, 3])
ds = dataset_ops.DatasetV2.from_tensors(ragged)
dsu = ds.unbatch()
if context.executing_eagerly():
values = list(dsu)
self.assertAllEqual(values[0].static_lengths(), [3])
self.assertAllEqual(values[1].static_lengths(), [3])
def test_unbatch_dense_vector(self):
ragged = DynamicRaggedShape.from_lengths([3])
ds = dataset_ops.DatasetV2.from_tensors(ragged)
dsu = ds.unbatch()
if context.executing_eagerly():
values = list(dsu)
self.assertAllEqual(values[0].static_lengths(), [])
self.assertAllEqual(values[1].static_lengths(), [])
def test_unbatch_ragged(self):
ragged = DynamicRaggedShape.from_lengths([4, (3, 0, 4, 5), 2, 3])
ds = dataset_ops.DatasetV2.from_tensors(ragged)
dsu = ds.unbatch()
if context.executing_eagerly():
dsu.__iter__()
def test_unbatch_batch_ragged(self):
ragged = DynamicRaggedShape.from_lengths([4, (3, 0, 4, 5), 2, 3])
ds = dataset_ops.DatasetV2.from_tensors(ragged)
dsu = ds.unbatch()
if context.executing_eagerly():
values = list(dsu)
self.assertAllEqual(values[0].static_lengths(), [3, 2, 3])
self.assertAllEqual(values[2].static_lengths(), [4, 2, 3])
dsb = dsu.batch(2)
if context.executing_eagerly():
valuesb = list(dsb)
self.assertAllEqual(valuesb[0].static_lengths(), [2, (3, 0), 2, 3])
self.assertAllEqual(valuesb[1].static_lengths(), [2, (4, 5), 2, 3])
| DynamicRaggedShapeTest |
python | geekcomputers__Python | venv/Lib/site-packages/pip/_vendor/rich/pretty.py | {
"start": 7910,
"end": 13849
} | class ____(JupyterMixin):
"""A rich renderable that pretty prints an object.
Args:
_object (Any): An object to pretty print.
highlighter (HighlighterType, optional): Highlighter object to apply to result, or None for ReprHighlighter. Defaults to None.
indent_size (int, optional): Number of spaces in indent. Defaults to 4.
justify (JustifyMethod, optional): Justify method, or None for default. Defaults to None.
overflow (OverflowMethod, optional): Overflow method, or None for default. Defaults to None.
no_wrap (Optional[bool], optional): Disable word wrapping. Defaults to False.
indent_guides (bool, optional): Enable indentation guides. Defaults to False.
max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.
Defaults to None.
max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to None.
max_depth (int, optional): Maximum depth of nested data structures, or None for no maximum. Defaults to None.
expand_all (bool, optional): Expand all containers. Defaults to False.
margin (int, optional): Subtrace a margin from width to force containers to expand earlier. Defaults to 0.
insert_line (bool, optional): Insert a new line if the output has multiple new lines. Defaults to False.
"""
def __init__(
self,
_object: Any,
highlighter: Optional["HighlighterType"] = None,
*,
indent_size: int = 4,
justify: Optional["JustifyMethod"] = None,
overflow: Optional["OverflowMethod"] = None,
no_wrap: Optional[bool] = False,
indent_guides: bool = False,
max_length: Optional[int] = None,
max_string: Optional[int] = None,
max_depth: Optional[int] = None,
expand_all: bool = False,
margin: int = 0,
insert_line: bool = False,
) -> None:
self._object = _object
self.highlighter = highlighter or ReprHighlighter()
self.indent_size = indent_size
self.justify: Optional["JustifyMethod"] = justify
self.overflow: Optional["OverflowMethod"] = overflow
self.no_wrap = no_wrap
self.indent_guides = indent_guides
self.max_length = max_length
self.max_string = max_string
self.max_depth = max_depth
self.expand_all = expand_all
self.margin = margin
self.insert_line = insert_line
def __rich_console__(
self, console: "Console", options: "ConsoleOptions"
) -> "RenderResult":
pretty_str = pretty_repr(
self._object,
max_width=options.max_width - self.margin,
indent_size=self.indent_size,
max_length=self.max_length,
max_string=self.max_string,
max_depth=self.max_depth,
expand_all=self.expand_all,
)
pretty_text = Text.from_ansi(
pretty_str,
justify=self.justify or options.justify,
overflow=self.overflow or options.overflow,
no_wrap=pick_bool(self.no_wrap, options.no_wrap),
style="pretty",
)
pretty_text = (
self.highlighter(pretty_text)
if pretty_text
else Text(
f"{type(self._object)}.__repr__ returned empty string",
style="dim italic",
)
)
if self.indent_guides and not options.ascii_only:
pretty_text = pretty_text.with_indent_guides(
self.indent_size, style="repr.indent"
)
if self.insert_line and "\n" in pretty_text:
yield ""
yield pretty_text
def __rich_measure__(
self, console: "Console", options: "ConsoleOptions"
) -> "Measurement":
pretty_str = pretty_repr(
self._object,
max_width=options.max_width,
indent_size=self.indent_size,
max_length=self.max_length,
max_string=self.max_string,
max_depth=self.max_depth,
expand_all=self.expand_all,
)
text_width = (
max(cell_len(line) for line in pretty_str.splitlines()) if pretty_str else 0
)
return Measurement(text_width, text_width)
def _get_braces_for_defaultdict(_object: DefaultDict[Any, Any]) -> Tuple[str, str, str]:
return (
f"defaultdict({_object.default_factory!r}, {{",
"})",
f"defaultdict({_object.default_factory!r}, {{}})",
)
def _get_braces_for_array(_object: "array[Any]") -> Tuple[str, str, str]:
return (f"array({_object.typecode!r}, [", "])", f"array({_object.typecode!r})")
_BRACES: Dict[type, Callable[[Any], Tuple[str, str, str]]] = {
os._Environ: lambda _object: ("environ({", "})", "environ({})"),
array: _get_braces_for_array,
defaultdict: _get_braces_for_defaultdict,
Counter: lambda _object: ("Counter({", "})", "Counter()"),
deque: lambda _object: ("deque([", "])", "deque()"),
dict: lambda _object: ("{", "}", "{}"),
UserDict: lambda _object: ("{", "}", "{}"),
frozenset: lambda _object: ("frozenset({", "})", "frozenset()"),
list: lambda _object: ("[", "]", "[]"),
UserList: lambda _object: ("[", "]", "[]"),
set: lambda _object: ("{", "}", "set()"),
tuple: lambda _object: ("(", ")", "()"),
MappingProxyType: lambda _object: ("mappingproxy({", "})", "mappingproxy({})"),
}
_CONTAINERS = tuple(_BRACES.keys())
_MAPPING_CONTAINERS = (dict, os._Environ, MappingProxyType, UserDict)
def is_expandable(obj: Any) -> bool:
"""Check if an object may be expanded by pretty print."""
return (
_safe_isinstance(obj, _CONTAINERS)
or (is_dataclass(obj))
or (hasattr(obj, "__rich_repr__"))
or _is_attr_object(obj)
) and not isclass(obj)
@dataclass
| Pretty |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_managed_kafka.py | {
"start": 18691,
"end": 19754
} | class ____:
@mock.patch(MANAGED_KAFKA_PATH.format("ManagedKafkaHook"))
def test_execute(self, mock_hook):
op = ManagedKafkaDeleteConsumerGroupOperator(
task_id=TASK_ID,
gcp_conn_id=GCP_CONN_ID,
impersonation_chain=IMPERSONATION_CHAIN,
location=GCP_LOCATION,
project_id=GCP_PROJECT,
cluster_id=TEST_CLUSTER_ID,
consumer_group_id=TEST_CONSUMER_GROUP_ID,
retry=RETRY,
timeout=TIMEOUT,
metadata=METADATA,
)
op.execute(context={})
mock_hook.assert_called_once_with(gcp_conn_id=GCP_CONN_ID, impersonation_chain=IMPERSONATION_CHAIN)
mock_hook.return_value.delete_consumer_group.assert_called_once_with(
location=GCP_LOCATION,
project_id=GCP_PROJECT,
cluster_id=TEST_CLUSTER_ID,
consumer_group_id=TEST_CONSUMER_GROUP_ID,
retry=RETRY,
timeout=TIMEOUT,
metadata=METADATA,
)
| TestManagedKafkaDeleteConsumerGroupOperator |
python | sympy__sympy | sympy/solvers/ode/single.py | {
"start": 73323,
"end": 77198
} | class ____(SingleODESolver):
r"""
Solves an `n`\th order linear homogeneous differential equation with
constant coefficients.
This is an equation of the form
.. math:: a_n f^{(n)}(x) + a_{n-1} f^{(n-1)}(x) + \cdots + a_1 f'(x)
+ a_0 f(x) = 0\text{.}
These equations can be solved in a general manner, by taking the roots of
the characteristic equation `a_n m^n + a_{n-1} m^{n-1} + \cdots + a_1 m +
a_0 = 0`. The solution will then be the sum of `C_n x^i e^{r x}` terms,
for each where `C_n` is an arbitrary constant, `r` is a root of the
characteristic equation and `i` is one of each from 0 to the multiplicity
of the root - 1 (for example, a root 3 of multiplicity 2 would create the
terms `C_1 e^{3 x} + C_2 x e^{3 x}`). The exponential is usually expanded
for complex roots using Euler's equation `e^{I x} = \cos(x) + I \sin(x)`.
Complex roots always come in conjugate pairs in polynomials with real
coefficients, so the two roots will be represented (after simplifying the
constants) as `e^{a x} \left(C_1 \cos(b x) + C_2 \sin(b x)\right)`.
If SymPy cannot find exact roots to the characteristic equation, a
:py:class:`~sympy.polys.rootoftools.ComplexRootOf` instance will be return
instead.
>>> from sympy import Function, dsolve
>>> from sympy.abc import x
>>> f = Function('f')
>>> dsolve(f(x).diff(x, 5) + 10*f(x).diff(x) - 2*f(x), f(x),
... hint='nth_linear_constant_coeff_homogeneous')
... # doctest: +NORMALIZE_WHITESPACE
Eq(f(x), C5*exp(x*CRootOf(_x**5 + 10*_x - 2, 0))
+ (C1*sin(x*im(CRootOf(_x**5 + 10*_x - 2, 1)))
+ C2*cos(x*im(CRootOf(_x**5 + 10*_x - 2, 1))))*exp(x*re(CRootOf(_x**5 + 10*_x - 2, 1)))
+ (C3*sin(x*im(CRootOf(_x**5 + 10*_x - 2, 3)))
+ C4*cos(x*im(CRootOf(_x**5 + 10*_x - 2, 3))))*exp(x*re(CRootOf(_x**5 + 10*_x - 2, 3))))
Note that because this method does not involve integration, there is no
``nth_linear_constant_coeff_homogeneous_Integral`` hint.
Examples
========
>>> from sympy import Function, dsolve, pprint
>>> from sympy.abc import x
>>> f = Function('f')
>>> pprint(dsolve(f(x).diff(x, 4) + 2*f(x).diff(x, 3) -
... 2*f(x).diff(x, 2) - 6*f(x).diff(x) + 5*f(x), f(x),
... hint='nth_linear_constant_coeff_homogeneous'))
x -2*x
f(x) = (C1 + C2*x)*e + (C3*sin(x) + C4*cos(x))*e
References
==========
- https://en.wikipedia.org/wiki/Linear_differential_equation section:
Nonhomogeneous_equation_with_constant_coefficients
- M. Tenenbaum & H. Pollard, "Ordinary Differential Equations",
Dover 1963, pp. 211
# indirect doctest
"""
hint = "nth_linear_constant_coeff_homogeneous"
has_integral = False
def _matches(self):
eq = self.ode_problem.eq_high_order_free
func = self.ode_problem.func
order = self.ode_problem.order
x = self.ode_problem.sym
self.r = self.ode_problem.get_linear_coefficients(eq, func, order)
if order and self.r and not any(self.r[i].has(x) for i in self.r if i >= 0):
if not self.r[-1]:
return True
else:
return False
return False
def _get_general_solution(self, *, simplify_flag: bool = True):
fx = self.ode_problem.func
order = self.ode_problem.order
roots, collectterms = _get_const_characteristic_eq_sols(self.r, fx, order)
# A generator of constants
constants = self.ode_problem.get_numbered_constants(num=len(roots))
gsol_rhs = Add(*[i*j for (i, j) in zip(constants, roots)])
gsol = Eq(fx, gsol_rhs)
if simplify_flag:
gsol = _get_simplified_sol([gsol], fx, collectterms)
return [gsol]
| NthLinearConstantCoeffHomogeneous |
python | dagster-io__dagster | python_modules/libraries/dagster-dg-cli/dagster_dg_cli/cli/scaffold/branch/models.py | {
"start": 149,
"end": 1029
} | class ____:
"""A recorded session of the `scaffold branch` command, useful for evaluating effectiveness."""
# isoformat
timestamp: str
# what code was used - semver for published package, commit hash for local development
dg_version: str
# the name of the branch created (even if AI not used)
branch_name: str
# the title of the PR created (even if AI not used)
pr_title: str
# the URL of the PR created. Used to identify the target repo. Empty string if local-only.
pr_url: str
# the commit hash of the branch base. Used to identify the state of the target repo.
branch_base_sha: str
# the commit hash of the generated first pass commit, if done.
first_pass_sha: Optional[str]
# collection of input information
input: dict[str, Any]
# collection of generated output
output: dict[str, Any]
@record
| Session |
python | dask__dask | dask/array/core.py | {
"start": 44342,
"end": 198746
} | class ____(DaskMethodsMixin):
"""Parallel Dask Array
A parallel nd-array comprised of many numpy arrays arranged in a grid.
This constructor is for advanced uses only. For normal use see the
:func:`dask.array.from_array` function.
Parameters
----------
dask : dict
Task dependency graph
name : string
Name of array in dask
shape : tuple of ints
Shape of the entire array
chunks: iterable of tuples
block sizes along each dimension
dtype : str or dtype
Typecode or data-type for the new Dask Array
meta : empty ndarray
empty ndarray created with same NumPy backend, ndim and dtype as the
Dask Array being created (overrides dtype)
See Also
--------
dask.array.from_array
"""
__slots__ = "dask", "__name", "_cached_keys", "__chunks", "_meta", "__dict__"
def __new__(cls, dask, name, chunks, dtype=None, meta=None, shape=None):
self = super().__new__(cls)
assert isinstance(dask, Mapping)
if not isinstance(dask, HighLevelGraph):
dask = HighLevelGraph.from_collections(name, dask, dependencies=())
self.dask = dask
self._name = str(name)
meta = meta_from_array(meta, dtype=dtype)
if (
isinstance(chunks, str)
or isinstance(chunks, tuple)
and chunks
and any(isinstance(c, str) for c in chunks)
):
dt = meta.dtype
else:
dt = None
self._chunks = normalize_chunks(chunks, shape, dtype=dt)
if self.chunks is None:
raise ValueError(CHUNKS_NONE_ERROR_MESSAGE)
self._meta = meta_from_array(meta, ndim=self.ndim, dtype=dtype)
for plugin in config.get("array_plugins", ()):
result = plugin(self)
if result is not None:
self = result
try:
layer = self.dask.layers[name]
except (AttributeError, KeyError):
# self is no longer an Array after applying the plugins, OR
# a plugin replaced the HighLevelGraph with a plain dict, OR
# name is not the top layer's name (this can happen after the layer is
# manipulated, to avoid a collision)
pass
else:
if layer.collection_annotations is None:
layer.collection_annotations = {
"shape": self.shape,
"dtype": self.dtype,
"chunksize": self.chunksize,
"chunks": self.chunks,
"type": typename(type(self)),
"chunk_type": typename(type(self._meta)),
}
else:
layer.collection_annotations.update(
{
"shape": self.shape,
"dtype": self.dtype,
"chunksize": self.chunksize,
"chunks": self.chunks,
"type": typename(type(self)),
"chunk_type": typename(type(self._meta)),
}
)
return self
def __reduce__(self):
return (Array, (self.dask, self.name, self.chunks, self.dtype, self._meta))
def __dask_graph__(self) -> Graph:
return self.dask
def __dask_layers__(self) -> Sequence[str]:
return (self.name,)
def __dask_keys__(self) -> NestedKeys:
if self._cached_keys is not None:
return self._cached_keys
name, chunks, numblocks = self.name, self.chunks, self.numblocks
def keys(*args):
if not chunks:
return [(name,)]
ind = len(args)
if ind + 1 == len(numblocks):
result = [(name,) + args + (i,) for i in range(numblocks[ind])]
else:
result = [keys(*(args + (i,))) for i in range(numblocks[ind])]
return result
self._cached_keys = result = keys()
return result
def __dask_tokenize__(self):
return self.name
__dask_optimize__ = globalmethod(
optimize, key="array_optimize", falsey=dont_optimize
)
__dask_scheduler__ = staticmethod(DEFAULT_GET)
def __dask_postcompute__(self):
return finalize, ()
def __dask_postpersist__(self):
return self._rebuild, ()
def _rebuild(self, dsk, *, rename=None):
name = self._name
if rename:
name = rename.get(name, name)
return Array(dsk, name, self.chunks, self.dtype, self._meta)
def _reset_cache(self, key=None):
"""
Reset cached properties.
Parameters
----------
key : str, optional
Remove specified key. The default removes all items.
"""
if key is None:
self.__dict__.clear()
else:
self.__dict__.pop(key, None)
@cached_property
def _key_array(self):
return np.array(self.__dask_keys__(), dtype=object)
@cached_property
def numblocks(self):
return tuple(map(len, self.chunks))
@cached_property
def npartitions(self):
return reduce(mul, self.numblocks, 1)
def compute_chunk_sizes(self):
"""
Compute the chunk sizes for a Dask array. This is especially useful
when the chunk sizes are unknown (e.g., when indexing one Dask array
with another).
Notes
-----
This function modifies the Dask array in-place.
Examples
--------
>>> import dask.array as da
>>> import numpy as np
>>> x = da.from_array([-2, -1, 0, 1, 2], chunks=2)
>>> x.chunks
((2, 2, 1),)
>>> y = x[x <= 0]
>>> y.chunks
((nan, nan, nan),)
>>> y.compute_chunk_sizes() # in-place computation
dask.array<getitem, shape=(3,), dtype=int64, chunksize=(2,), chunktype=numpy.ndarray>
>>> y.chunks
((2, 1, 0),)
"""
x = self
chunk_shapes = x.map_blocks(
_get_chunk_shape,
dtype=int,
chunks=tuple(len(c) * (1,) for c in x.chunks) + ((x.ndim,),),
new_axis=x.ndim,
)
c = []
for i in range(x.ndim):
s = x.ndim * [0] + [i]
s[i] = slice(None)
s = tuple(s)
c.append(tuple(chunk_shapes[s]))
# `map_blocks` assigns numpy dtypes
# cast chunk dimensions back to python int before returning
x._chunks = tuple(
tuple(int(chunk) for chunk in chunks) for chunks in compute(tuple(c))[0]
)
return x
@cached_property
def shape(self) -> tuple[T_IntOrNaN, ...]:
return tuple(cached_cumsum(c, initial_zero=True)[-1] for c in self.chunks)
@property
def chunksize(self) -> tuple[T_IntOrNaN, ...]:
return tuple(cached_max(c) for c in self.chunks)
@property
def dtype(self):
if isinstance(self._meta, tuple):
dtype = self._meta[0].dtype
else:
dtype = self._meta.dtype
return dtype
@property
def _chunks(self):
"""Non-public chunks property. Allows setting a chunk value."""
return self.__chunks
@_chunks.setter
def _chunks(self, chunks):
self.__chunks = chunks
# When the chunks changes the cached properties that was
# dependent on it needs to be deleted:
for key in ["numblocks", "npartitions", "shape", "ndim", "size", "_key_array"]:
self._reset_cache(key)
@property
def chunks(self):
"""Chunks property."""
return self.__chunks
@chunks.setter
def chunks(self, chunks):
raise TypeError(
"Can not set chunks directly\n\n"
"Please use the rechunk method instead:\n"
f" x.rechunk({chunks})\n\n"
"If trying to avoid unknown chunks, use\n"
" x.compute_chunk_sizes()"
)
def __len__(self):
if not self.chunks:
raise TypeError("len() of unsized object")
if np.isnan(self.chunks[0]).any():
msg = (
"Cannot call len() on object with unknown chunk size."
f"{unknown_chunk_message}"
)
raise ValueError(msg)
return int(sum(self.chunks[0]))
def __array_ufunc__(self, numpy_ufunc, method, *inputs, **kwargs):
out = kwargs.get("out", ())
for x in inputs + out:
if _should_delegate(self, x):
return NotImplemented
if method == "__call__":
if numpy_ufunc is np.matmul:
from dask.array.routines import matmul
# special case until apply_gufunc handles optional dimensions
return matmul(*inputs, **kwargs)
if numpy_ufunc.signature is not None:
from dask.array.gufunc import apply_gufunc
return apply_gufunc(
numpy_ufunc, numpy_ufunc.signature, *inputs, **kwargs
)
if numpy_ufunc.nout > 1:
from dask.array import ufunc
try:
da_ufunc = getattr(ufunc, numpy_ufunc.__name__)
except AttributeError:
return NotImplemented
return da_ufunc(*inputs, **kwargs)
else:
return elemwise(numpy_ufunc, *inputs, **kwargs)
elif method == "outer":
from dask.array import ufunc
try:
da_ufunc = getattr(ufunc, numpy_ufunc.__name__)
except AttributeError:
return NotImplemented
return da_ufunc.outer(*inputs, **kwargs)
else:
return NotImplemented
def __repr__(self):
"""
>>> import dask.array as da
>>> da.ones((10, 10), chunks=(5, 5), dtype='i4')
dask.array<..., shape=(10, 10), dtype=int32, chunksize=(5, 5), chunktype=numpy.ndarray>
"""
name = self.name.rsplit("-", 1)[0]
return (
"dask.array<{}, shape={}, dtype={}, chunksize={}, chunktype={}.{}>".format(
name,
self.shape,
self.dtype,
self.chunksize,
type(self._meta).__module__.split(".")[0],
type(self._meta).__name__,
)
)
def _repr_html_(self):
if ARRAY_TEMPLATE is None:
# if the jinja template is not available, (e.g. because jinja2 is not installed)
# fall back to the textual representation
return repr(self)
try:
grid = self.to_svg(size=config.get("array.svg.size", 120))
except NotImplementedError:
grid = ""
if "sparse" in typename(type(self._meta)):
nbytes = None
cbytes = None
elif not math.isnan(self.nbytes):
nbytes = format_bytes(self.nbytes)
cbytes = format_bytes(math.prod(self.chunksize) * self.dtype.itemsize)
else:
nbytes = "unknown"
cbytes = "unknown"
return ARRAY_TEMPLATE.render(
array=self,
grid=grid,
nbytes=nbytes,
cbytes=cbytes,
layers=maybe_pluralize(len(self.dask.layers), "graph layer"),
)
@cached_property
def ndim(self) -> int:
return len(self.shape)
@cached_property
def size(self) -> T_IntOrNaN:
"""Number of elements in array"""
return reduce(mul, self.shape, 1)
@property
def nbytes(self) -> T_IntOrNaN:
"""Number of bytes in array"""
return self.size * self.dtype.itemsize
@property
def itemsize(self) -> int:
"""Length of one array element in bytes"""
return self.dtype.itemsize
@property
def _name(self):
return self.__name
@_name.setter
def _name(self, val):
self.__name = val
# Clear the key cache when the name is reset
self._cached_keys = None
self._reset_cache("_key_array")
@property
def name(self):
return self.__name
@name.setter
def name(self, val):
raise TypeError(
"Cannot set name directly\n\n"
"Name is used to relate the array to the task graph.\n"
"It is uncommon to need to change it, but if you do\n"
"please set ``._name``"
)
def __iter__(self):
for i in range(len(self)):
yield self[i]
__array_priority__ = 11 # higher than numpy.ndarray and numpy.matrix
def __array__(self, dtype=None, copy=None, **kwargs):
if kwargs:
warnings.warn(
f"Extra keyword arguments {kwargs} are ignored and won't be "
"accepted in the future",
FutureWarning,
)
if copy is False:
warnings.warn(
"Can't acquire a memory view of a Dask array. "
"This will raise in the future.",
FutureWarning,
)
x = self.compute()
# Apply requested dtype and convert non-numpy backends to numpy.
# If copy is True, numpy is going to perform its own deep copy
# after this method returns.
# If copy is None, finalize() ensures that the returned object
# does not share memory with an object stored in the graph or on a
# process-local Worker.
return np.asarray(x, dtype=dtype)
def __array_function__(self, func, types, args, kwargs):
import dask.array as module
def handle_nonmatching_names(func, args, kwargs):
if func not in _HANDLED_FUNCTIONS:
warnings.warn(
f"The `{func.__module__}.{func.__name__}` function "
"is not implemented by Dask array. "
"You may want to use the da.map_blocks function "
"or something similar to silence this warning. "
"Your code may stop working in a future release.",
FutureWarning,
)
# Need to convert to array object (e.g. numpy.ndarray or
# cupy.ndarray) as needed, so we can call the NumPy function
# again and it gets the chance to dispatch to the right
# implementation.
args, kwargs = compute(args, kwargs)
return func(*args, **kwargs)
return _HANDLED_FUNCTIONS[func](*args, **kwargs)
# First, verify that all types are handled by Dask. Otherwise, return NotImplemented.
if not all(
# Accept our own superclasses as recommended by NEP-13
# (https://numpy.org/neps/nep-0013-ufunc-overrides.html#subclass-hierarchies)
issubclass(type(self), type_) or is_valid_chunk_type(type_)
for type_ in types
):
return NotImplemented
# Now try to find a matching function name. If that doesn't work, we may
# be dealing with an alias or a function that's simply not in the Dask API.
# Handle aliases via the _HANDLED_FUNCTIONS dict mapping, and warn otherwise.
for submodule in func.__module__.split(".")[1:]:
try:
module = getattr(module, submodule)
except AttributeError:
return handle_nonmatching_names(func, args, kwargs)
if not hasattr(module, func.__name__):
return handle_nonmatching_names(func, args, kwargs)
da_func = getattr(module, func.__name__)
if da_func is func:
return handle_nonmatching_names(func, args, kwargs)
# If ``like`` is contained in ``da_func``'s signature, add ``like=self``
# to the kwargs dictionary.
if has_keyword(da_func, "like"):
kwargs["like"] = self
return da_func(*args, **kwargs)
@property
def _elemwise(self):
return elemwise
@wraps(store)
def store(self, target, **kwargs):
return store([self], [target], **kwargs)
def to_svg(self, size=500):
"""Convert chunks from Dask Array into an SVG Image
Parameters
----------
chunks: tuple
size: int
Rough size of the image
Examples
--------
>>> x.to_svg(size=500) # doctest: +SKIP
Returns
-------
text: An svg string depicting the array as a grid of chunks
"""
from dask.array.svg import svg
return svg(self.chunks, size=size)
def to_hdf5(self, filename, datapath, **kwargs):
"""Store array in HDF5 file
>>> x.to_hdf5('myfile.hdf5', '/x') # doctest: +SKIP
Optionally provide arguments as though to ``h5py.File.create_dataset``
>>> x.to_hdf5('myfile.hdf5', '/x', compression='lzf', shuffle=True) # doctest: +SKIP
See Also
--------
dask.array.store
h5py.File.create_dataset
"""
return to_hdf5(filename, datapath, self, **kwargs)
def to_dask_dataframe(self, columns=None, index=None, meta=None):
"""Convert dask Array to dask Dataframe
Parameters
----------
columns: list or string
list of column names if DataFrame, single string if Series
index : dask.dataframe.Index, optional
An optional *dask* Index to use for the output Series or DataFrame.
The default output index depends on whether the array has any unknown
chunks. If there are any unknown chunks, the output has ``None``
for all the divisions (one per chunk). If all the chunks are known,
a default index with known divisions is created.
Specifying ``index`` can be useful if you're conforming a Dask Array
to an existing dask Series or DataFrame, and you would like the
indices to match.
meta : object, optional
An optional `meta` parameter can be passed for dask
to specify the concrete dataframe type to use for partitions of
the Dask dataframe. By default, pandas DataFrame is used.
See Also
--------
dask.dataframe.from_dask_array
"""
from dask.dataframe import from_dask_array
return from_dask_array(self, columns=columns, index=index, meta=meta)
def to_backend(self, backend: str | None = None, **kwargs):
"""Move to a new Array backend
Parameters
----------
backend : str, Optional
The name of the new backend to move to. The default
is the current "array.backend" configuration.
Returns
-------
Array
"""
from dask.array.creation import to_backend
return to_backend(self, backend=backend, **kwargs)
def __bool__(self):
if self.size > 1:
raise ValueError(
f"The truth value of a {self.__class__.__name__} is ambiguous. "
"Use a.any() or a.all()."
)
else:
return bool(self.compute())
__nonzero__ = __bool__ # python 2
def _scalarfunc(self, cast_type):
if self.size > 1:
raise TypeError("Only length-1 arrays can be converted to Python scalars")
else:
return cast_type(self.compute().item())
def __int__(self):
return self._scalarfunc(int)
__long__ = __int__ # python 2
def __float__(self):
return self._scalarfunc(float)
def __complex__(self):
return self._scalarfunc(complex)
def __index__(self):
return self._scalarfunc(operator.index)
def __setitem__(self, key, value):
if value is np.ma.masked:
value = np.ma.masked_all((), dtype=self.dtype)
if not is_dask_collection(value) and self.dtype.kind in "iu":
if np.isnan(value).any():
raise ValueError("cannot convert float NaN to integer")
if np.isinf(value).any():
raise ValueError("cannot convert float infinity to integer")
# Suppress dtype broadcasting; __setitem__ can't change the dtype.
# Use asanyarray to retain e.g. np.ma objects.
value = asanyarray(value, dtype=self.dtype, like=self)
if isinstance(key, Array) and (
key.dtype.kind in "iu"
or (key.dtype == bool and key.ndim == 1 and self.ndim > 1)
):
key = (key,)
## Use the "where" method for cases when key is an Array of bools
if isinstance(key, Array):
from dask.array.routines import where
left_shape = np.array(key.shape)
right_shape = np.array(self.shape)
# We want to treat unknown shape on *either* sides as a match
match = left_shape == right_shape
match |= np.isnan(left_shape) | np.isnan(right_shape)
if not match.all():
raise IndexError(
f"boolean index shape {key.shape} must match indexed array's "
f"{self.shape}."
)
# If value has ndim > 0, they must be broadcastable to self.shape[idx].
# This raises when the bool mask causes the size to become unknown,
# e.g. this is valid in numpy but raises here:
# x = da.array([1,2,3])
# x[da.array([True, True, False])] = [4, 5]
if value.ndim:
value = broadcast_to(value, self[key].shape)
y = where(key, value, self)
# FIXME does any backend allow mixed ops vs. numpy?
# If yes, is it wise to let them change the meta?
self._meta = y._meta
self.dask = y.dask
self._name = y.name
self._chunks = y.chunks
return
if np.isnan(self.shape).any():
raise ValueError(f"Arrays chunk sizes are unknown. {unknown_chunk_message}")
# Still here? Then apply the assignment to other type of
# indices via the `setitem_array` function.
token = tokenize(self, key, value)
out = f"setitem-{token}"
dsk = setitem_array(out, self, key, value)
meta = meta_from_array(self._meta)
if np.isscalar(meta):
meta = np.array(meta)
graph = HighLevelGraph.from_collections(out, dsk, dependencies=[self])
y = Array(graph, out, chunks=self.chunks, dtype=self.dtype, meta=meta)
self._meta = y._meta
self.dask = y.dask
self._name = y.name
self._chunks = y.chunks
def __getitem__(self, index):
# Field access, e.g. x['a'] or x[['a', 'b']]
if isinstance(index, str) or (
isinstance(index, list) and index and all(isinstance(i, str) for i in index)
):
if isinstance(index, str):
dt = self.dtype[index]
else:
dt = np.dtype(
{
"names": index,
"formats": [self.dtype.fields[name][0] for name in index],
"offsets": [self.dtype.fields[name][1] for name in index],
"itemsize": self.dtype.itemsize,
}
)
if dt.shape:
new_axis = list(range(self.ndim, self.ndim + len(dt.shape)))
chunks = self.chunks + tuple((i,) for i in dt.shape)
return self.map_blocks(
getitem, index, dtype=dt.base, chunks=chunks, new_axis=new_axis
)
else:
return self.map_blocks(getitem, index, dtype=dt)
if not isinstance(index, tuple):
index = (index,)
from dask.array.slicing import (
normalize_index,
slice_with_bool_dask_array,
slice_with_int_dask_array,
)
index2 = normalize_index(index, self.shape)
dependencies = {self.name}
for i in index2:
if isinstance(i, Array):
dependencies.add(i.name)
if any(isinstance(i, Array) and i.dtype.kind in "iu" for i in index2):
self, index2 = slice_with_int_dask_array(self, index2)
if any(isinstance(i, Array) and i.dtype == bool for i in index2):
self, index2 = slice_with_bool_dask_array(self, index2)
if all(isinstance(i, slice) and i == slice(None) for i in index2):
return self
out = "getitem-" + tokenize(self, index2)
try:
dsk, chunks = slice_array(out, self.name, self.chunks, index2)
except SlicingNoop:
return self
graph = HighLevelGraph.from_collections(out, dsk, dependencies=[self])
meta = meta_from_array(self._meta, ndim=len(chunks))
if np.isscalar(meta):
meta = np.array(meta)
return Array(graph, out, chunks, meta=meta)
def _vindex(self, key):
if not isinstance(key, tuple):
key = (key,)
if any(k is None for k in key):
raise IndexError(
f"vindex does not support indexing with None (np.newaxis), got {key}"
)
if all(isinstance(k, slice) for k in key):
if all(
k.indices(d) == slice(0, d).indices(d) for k, d in zip(key, self.shape)
):
return self
raise IndexError(
"vindex requires at least one non-slice to vectorize over "
"when the slices are not over the entire array (i.e, x[:]). "
f"Use normal slicing instead when only using slices. Got: {key}"
)
elif any(is_dask_collection(k) for k in key):
if math.prod(self.numblocks) == 1 and len(key) == 1 and self.ndim == 1:
idxr = key[0]
# we can broadcast in this case
return idxr.map_blocks(
_numpy_vindex, self, dtype=self.dtype, chunks=idxr.chunks
)
else:
raise IndexError(
"vindex does not support indexing with dask objects. Call compute "
f"on the indexer first to get an evalurated array. Got: {key}"
)
return _vindex(self, *key)
@property
def vindex(self):
"""Vectorized indexing with broadcasting.
This is equivalent to numpy's advanced indexing, using arrays that are
broadcast against each other. This allows for pointwise indexing:
>>> import dask.array as da
>>> x = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
>>> x = da.from_array(x, chunks=2)
>>> x.vindex[[0, 1, 2], [0, 1, 2]].compute()
array([1, 5, 9])
Mixed basic/advanced indexing with slices/arrays is also supported. The
order of dimensions in the result follows those proposed for
`ndarray.vindex <https://github.com/numpy/numpy/pull/6256>`_:
the subspace spanned by arrays is followed by all slices.
Note: ``vindex`` provides more general functionality than standard
indexing, but it also has fewer optimizations and can be significantly
slower.
"""
return IndexCallable(self._vindex)
@property
def blocks(self):
"""An array-like interface to the blocks of an array.
This returns a ``Blockview`` object that provides an array-like interface
to the blocks of a dask array. Numpy-style indexing of a ``Blockview`` object
returns a selection of blocks as a new dask array.
You can index ``array.blocks`` like a numpy array of shape
equal to the number of blocks in each dimension, (available as
array.blocks.size). The dimensionality of the output array matches
the dimension of this array, even if integer indices are passed.
Slicing with ``np.newaxis`` or multiple lists is not supported.
Examples
--------
>>> import dask.array as da
>>> x = da.arange(8, chunks=2)
>>> x.blocks.shape # aliases x.numblocks
(4,)
>>> x.blocks[0].compute()
array([0, 1])
>>> x.blocks[:3].compute()
array([0, 1, 2, 3, 4, 5])
>>> x.blocks[::2].compute()
array([0, 1, 4, 5])
>>> x.blocks[[-1, 0]].compute()
array([6, 7, 0, 1])
>>> x.blocks.ravel() # doctest: +NORMALIZE_WHITESPACE
[dask.array<blocks, shape=(2,), dtype=int64, chunksize=(2,), chunktype=numpy.ndarray>,
dask.array<blocks, shape=(2,), dtype=int64, chunksize=(2,), chunktype=numpy.ndarray>,
dask.array<blocks, shape=(2,), dtype=int64, chunksize=(2,), chunktype=numpy.ndarray>,
dask.array<blocks, shape=(2,), dtype=int64, chunksize=(2,), chunktype=numpy.ndarray>]
Returns
-------
An instance of ``dask.array.Blockview``
"""
return BlockView(self)
@property
def partitions(self):
"""Slice an array by partitions. Alias of dask array .blocks attribute.
This alias allows you to write agnostic code that works with both
dask arrays and dask dataframes.
This returns a ``Blockview`` object that provides an array-like interface
to the blocks of a dask array. Numpy-style indexing of a ``Blockview`` object
returns a selection of blocks as a new dask array.
You can index ``array.blocks`` like a numpy array of shape
equal to the number of blocks in each dimension, (available as
array.blocks.size). The dimensionality of the output array matches
the dimension of this array, even if integer indices are passed.
Slicing with ``np.newaxis`` or multiple lists is not supported.
Examples
--------
>>> import dask.array as da
>>> x = da.arange(8, chunks=2)
>>> x.partitions.shape # aliases x.numblocks
(4,)
>>> x.partitions[0].compute()
array([0, 1])
>>> x.partitions[:3].compute()
array([0, 1, 2, 3, 4, 5])
>>> x.partitions[::2].compute()
array([0, 1, 4, 5])
>>> x.partitions[[-1, 0]].compute()
array([6, 7, 0, 1])
>>> x.partitions.ravel() # doctest: +NORMALIZE_WHITESPACE
[dask.array<blocks, shape=(2,), dtype=int64, chunksize=(2,), chunktype=numpy.ndarray>,
dask.array<blocks, shape=(2,), dtype=int64, chunksize=(2,), chunktype=numpy.ndarray>,
dask.array<blocks, shape=(2,), dtype=int64, chunksize=(2,), chunktype=numpy.ndarray>,
dask.array<blocks, shape=(2,), dtype=int64, chunksize=(2,), chunktype=numpy.ndarray>]
Returns
-------
An instance of ``da.array.Blockview``
"""
return self.blocks
def dot(self, other):
"""Dot product of self and other.
Refer to :func:`dask.array.tensordot` for full documentation.
See Also
--------
dask.array.dot : equivalent function
"""
from dask.array.routines import tensordot
return tensordot(self, other, axes=((self.ndim - 1,), (other.ndim - 2,)))
@property
def A(self):
return self
@property
def T(self):
return self.transpose()
def transpose(self, *axes):
"""Reverse or permute the axes of an array. Return the modified array.
Refer to :func:`dask.array.transpose` for full documentation.
See Also
--------
dask.array.transpose : equivalent function
"""
from dask.array.routines import transpose
if not axes:
axes = None
elif len(axes) == 1 and isinstance(axes[0], Iterable):
axes = axes[0]
if (axes == tuple(range(self.ndim))) or (axes == tuple(range(-self.ndim, 0))):
# no transpose necessary
return self
else:
return transpose(self, axes=axes)
def ravel(self):
"""Return a flattened array.
Refer to :func:`dask.array.ravel` for full documentation.
See Also
--------
dask.array.ravel : equivalent function
"""
from dask.array.routines import ravel
return ravel(self)
flatten = ravel
def choose(self, choices):
"""Use an index array to construct a new array from a set of choices.
Refer to :func:`dask.array.choose` for full documentation.
See Also
--------
dask.array.choose : equivalent function
"""
from dask.array.routines import choose
return choose(self, choices)
def reshape(self, *shape, merge_chunks=True, limit=None):
"""Reshape array to new shape
Refer to :func:`dask.array.reshape` for full documentation.
See Also
--------
dask.array.reshape : equivalent function
"""
from dask.array.reshape import reshape
if len(shape) == 1 and not isinstance(shape[0], Number):
shape = shape[0]
return reshape(self, shape, merge_chunks=merge_chunks, limit=limit)
def topk(self, k, axis=-1, split_every=None):
"""The top k elements of an array.
Refer to :func:`dask.array.topk` for full documentation.
See Also
--------
dask.array.topk : equivalent function
"""
from dask.array.reductions import topk
return topk(self, k, axis=axis, split_every=split_every)
def argtopk(self, k, axis=-1, split_every=None):
"""The indices of the top k elements of an array.
Refer to :func:`dask.array.argtopk` for full documentation.
See Also
--------
dask.array.argtopk : equivalent function
"""
from dask.array.reductions import argtopk
return argtopk(self, k, axis=axis, split_every=split_every)
def astype(self, dtype, **kwargs):
"""Copy of the array, cast to a specified type.
Parameters
----------
dtype : str or dtype
Typecode or data-type to which the array is cast.
casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
Controls what kind of data casting may occur. Defaults to 'unsafe'
for backwards compatibility.
* 'no' means the data types should not be cast at all.
* 'equiv' means only byte-order changes are allowed.
* 'safe' means only casts which can preserve values are allowed.
* 'same_kind' means only safe casts or casts within a kind,
like float64 to float32, are allowed.
* 'unsafe' means any data conversions may be done.
copy : bool, optional
By default, astype always returns a newly allocated array. If this
is set to False and the `dtype` requirement is satisfied, the input
array is returned instead of a copy.
.. note::
Dask does not respect the contiguous memory layout of the array,
and will ignore the ``order`` keyword argument.
The default order is 'C' contiguous.
"""
kwargs.pop("order", None) # `order` is not respected, so we remove this kwarg
# Scalars don't take `casting` or `copy` kwargs - as such we only pass
# them to `map_blocks` if specified by user (different than defaults).
extra = set(kwargs) - {"casting", "copy"}
if extra:
raise TypeError(
f"astype does not take the following keyword arguments: {list(extra)}"
)
casting = kwargs.get("casting", "unsafe")
dtype = np.dtype(dtype)
if self.dtype == dtype:
return self
elif not np.can_cast(self.dtype, dtype, casting=casting):
raise TypeError(
f"Cannot cast array from {self.dtype!r} to {dtype!r} "
f"according to the rule {casting!r}"
)
return self.map_blocks(chunk.astype, dtype=dtype, astype_dtype=dtype, **kwargs)
def __abs__(self):
return elemwise(operator.abs, self)
@check_if_handled_given_other
def __add__(self, other):
return elemwise(operator.add, self, other)
@check_if_handled_given_other
def __radd__(self, other):
return elemwise(operator.add, other, self)
@check_if_handled_given_other
def __and__(self, other):
return elemwise(operator.and_, self, other)
@check_if_handled_given_other
def __rand__(self, other):
return elemwise(operator.and_, other, self)
@check_if_handled_given_other
def __div__(self, other):
return elemwise(operator.div, self, other)
@check_if_handled_given_other
def __rdiv__(self, other):
return elemwise(operator.div, other, self)
@check_if_handled_given_other
def __eq__(self, other):
return elemwise(operator.eq, self, other)
@check_if_handled_given_other
def __gt__(self, other):
return elemwise(operator.gt, self, other)
@check_if_handled_given_other
def __ge__(self, other):
return elemwise(operator.ge, self, other)
def __invert__(self):
return elemwise(operator.invert, self)
@check_if_handled_given_other
def __lshift__(self, other):
return elemwise(operator.lshift, self, other)
@check_if_handled_given_other
def __rlshift__(self, other):
return elemwise(operator.lshift, other, self)
@check_if_handled_given_other
def __lt__(self, other):
return elemwise(operator.lt, self, other)
@check_if_handled_given_other
def __le__(self, other):
return elemwise(operator.le, self, other)
@check_if_handled_given_other
def __mod__(self, other):
return elemwise(operator.mod, self, other)
@check_if_handled_given_other
def __rmod__(self, other):
return elemwise(operator.mod, other, self)
@check_if_handled_given_other
def __mul__(self, other):
return elemwise(operator.mul, self, other)
@check_if_handled_given_other
def __rmul__(self, other):
return elemwise(operator.mul, other, self)
@check_if_handled_given_other
def __ne__(self, other):
return elemwise(operator.ne, self, other)
def __neg__(self):
return elemwise(operator.neg, self)
@check_if_handled_given_other
def __or__(self, other):
return elemwise(operator.or_, self, other)
def __pos__(self):
return self
@check_if_handled_given_other
def __ror__(self, other):
return elemwise(operator.or_, other, self)
@check_if_handled_given_other
def __pow__(self, other):
return elemwise(operator.pow, self, other)
@check_if_handled_given_other
def __rpow__(self, other):
return elemwise(operator.pow, other, self)
@check_if_handled_given_other
def __rshift__(self, other):
return elemwise(operator.rshift, self, other)
@check_if_handled_given_other
def __rrshift__(self, other):
return elemwise(operator.rshift, other, self)
@check_if_handled_given_other
def __sub__(self, other):
return elemwise(operator.sub, self, other)
@check_if_handled_given_other
def __rsub__(self, other):
return elemwise(operator.sub, other, self)
@check_if_handled_given_other
def __truediv__(self, other):
return elemwise(operator.truediv, self, other)
@check_if_handled_given_other
def __rtruediv__(self, other):
return elemwise(operator.truediv, other, self)
@check_if_handled_given_other
def __floordiv__(self, other):
return elemwise(operator.floordiv, self, other)
@check_if_handled_given_other
def __rfloordiv__(self, other):
return elemwise(operator.floordiv, other, self)
@check_if_handled_given_other
def __xor__(self, other):
return elemwise(operator.xor, self, other)
@check_if_handled_given_other
def __rxor__(self, other):
return elemwise(operator.xor, other, self)
@check_if_handled_given_other
def __matmul__(self, other):
from dask.array.routines import matmul
return matmul(self, other)
@check_if_handled_given_other
def __rmatmul__(self, other):
from dask.array.routines import matmul
return matmul(other, self)
@check_if_handled_given_other
def __divmod__(self, other):
from dask.array.ufunc import divmod
return divmod(self, other)
@check_if_handled_given_other
def __rdivmod__(self, other):
from dask.array.ufunc import divmod
return divmod(other, self)
def any(self, axis=None, keepdims=False, split_every=None, out=None):
"""Returns True if any of the elements evaluate to True.
Refer to :func:`dask.array.any` for full documentation.
See Also
--------
dask.array.any : equivalent function
"""
from dask.array.reductions import any
return any(self, axis=axis, keepdims=keepdims, split_every=split_every, out=out)
def all(self, axis=None, keepdims=False, split_every=None, out=None):
"""Returns True if all elements evaluate to True.
Refer to :func:`dask.array.all` for full documentation.
See Also
--------
dask.array.all : equivalent function
"""
from dask.array.reductions import all
return all(self, axis=axis, keepdims=keepdims, split_every=split_every, out=out)
def min(self, axis=None, keepdims=False, split_every=None, out=None):
"""Return the minimum along a given axis.
Refer to :func:`dask.array.min` for full documentation.
See Also
--------
dask.array.min : equivalent function
"""
from dask.array.reductions import min
return min(self, axis=axis, keepdims=keepdims, split_every=split_every, out=out)
def max(self, axis=None, keepdims=False, split_every=None, out=None):
"""Return the maximum along a given axis.
Refer to :func:`dask.array.max` for full documentation.
See Also
--------
dask.array.max : equivalent function
"""
from dask.array.reductions import max
return max(self, axis=axis, keepdims=keepdims, split_every=split_every, out=out)
def argmin(self, axis=None, *, keepdims=False, split_every=None, out=None):
"""Return indices of the minimum values along the given axis.
Refer to :func:`dask.array.argmin` for full documentation.
See Also
--------
dask.array.argmin : equivalent function
"""
from dask.array.reductions import argmin
return argmin(
self, axis=axis, keepdims=keepdims, split_every=split_every, out=out
)
def argmax(self, axis=None, *, keepdims=False, split_every=None, out=None):
"""Return indices of the maximum values along the given axis.
Refer to :func:`dask.array.argmax` for full documentation.
See Also
--------
dask.array.argmax : equivalent function
"""
from dask.array.reductions import argmax
return argmax(
self, axis=axis, keepdims=keepdims, split_every=split_every, out=out
)
def sum(self, axis=None, dtype=None, keepdims=False, split_every=None, out=None):
"""
Return the sum of the array elements over the given axis.
Refer to :func:`dask.array.sum` for full documentation.
See Also
--------
dask.array.sum : equivalent function
"""
from dask.array.reductions import sum
return sum(
self,
axis=axis,
dtype=dtype,
keepdims=keepdims,
split_every=split_every,
out=out,
)
def trace(self, offset=0, axis1=0, axis2=1, dtype=None):
"""Return the sum along diagonals of the array.
Refer to :func:`dask.array.trace` for full documentation.
See Also
--------
dask.array.trace : equivalent function
"""
from dask.array.reductions import trace
return trace(self, offset=offset, axis1=axis1, axis2=axis2, dtype=dtype)
def prod(self, axis=None, dtype=None, keepdims=False, split_every=None, out=None):
"""Return the product of the array elements over the given axis
Refer to :func:`dask.array.prod` for full documentation.
See Also
--------
dask.array.prod : equivalent function
"""
from dask.array.reductions import prod
return prod(
self,
axis=axis,
dtype=dtype,
keepdims=keepdims,
split_every=split_every,
out=out,
)
def mean(self, axis=None, dtype=None, keepdims=False, split_every=None, out=None):
"""Returns the average of the array elements along given axis.
Refer to :func:`dask.array.mean` for full documentation.
See Also
--------
dask.array.mean : equivalent function
"""
from dask.array.reductions import mean
return mean(
self,
axis=axis,
dtype=dtype,
keepdims=keepdims,
split_every=split_every,
out=out,
)
def std(
self, axis=None, dtype=None, keepdims=False, ddof=0, split_every=None, out=None
):
"""Returns the standard deviation of the array elements along given axis.
Refer to :func:`dask.array.std` for full documentation.
See Also
--------
dask.array.std : equivalent function
"""
from dask.array.reductions import std
return std(
self,
axis=axis,
dtype=dtype,
keepdims=keepdims,
ddof=ddof,
split_every=split_every,
out=out,
)
def var(
self, axis=None, dtype=None, keepdims=False, ddof=0, split_every=None, out=None
):
"""Returns the variance of the array elements, along given axis.
Refer to :func:`dask.array.var` for full documentation.
See Also
--------
dask.array.var : equivalent function
"""
from dask.array.reductions import var
return var(
self,
axis=axis,
dtype=dtype,
keepdims=keepdims,
ddof=ddof,
split_every=split_every,
out=out,
)
def moment(
self,
order,
axis=None,
dtype=None,
keepdims=False,
ddof=0,
split_every=None,
out=None,
):
"""Calculate the nth centralized moment.
Refer to :func:`dask.array.moment` for the full documentation.
See Also
--------
dask.array.moment : equivalent function
"""
from dask.array.reductions import moment
return moment(
self,
order,
axis=axis,
dtype=dtype,
keepdims=keepdims,
ddof=ddof,
split_every=split_every,
out=out,
)
@wraps(map_blocks)
def map_blocks(self, func, *args, **kwargs):
return map_blocks(func, self, *args, **kwargs)
def map_overlap(self, func, depth, boundary=None, trim=True, **kwargs):
"""Map a function over blocks of the array with some overlap
Refer to :func:`dask.array.map_overlap` for full documentation.
See Also
--------
dask.array.map_overlap : equivalent function
"""
from dask.array.overlap import map_overlap
return map_overlap(
func, self, depth=depth, boundary=boundary, trim=trim, **kwargs
)
def cumsum(self, axis, dtype=None, out=None, *, method="sequential"):
"""Return the cumulative sum of the elements along the given axis.
Refer to :func:`dask.array.cumsum` for full documentation.
See Also
--------
dask.array.cumsum : equivalent function
"""
from dask.array.reductions import cumsum
return cumsum(self, axis, dtype, out=out, method=method)
def cumprod(self, axis, dtype=None, out=None, *, method="sequential"):
"""Return the cumulative product of the elements along the given axis.
Refer to :func:`dask.array.cumprod` for full documentation.
See Also
--------
dask.array.cumprod : equivalent function
"""
from dask.array.reductions import cumprod
return cumprod(self, axis, dtype, out=out, method=method)
def squeeze(self, axis=None):
"""Remove axes of length one from array.
Refer to :func:`dask.array.squeeze` for full documentation.
See Also
--------
dask.array.squeeze : equivalent function
"""
from dask.array.routines import squeeze
return squeeze(self, axis)
def rechunk(
self,
chunks="auto",
threshold=None,
block_size_limit=None,
balance=False,
method=None,
):
"""Convert blocks in dask array x for new chunks.
Refer to :func:`dask.array.rechunk` for full documentation.
See Also
--------
dask.array.rechunk : equivalent function
"""
from dask.array.rechunk import rechunk # avoid circular import
return rechunk(self, chunks, threshold, block_size_limit, balance, method)
def shuffle(
self,
indexer: list[list[int]],
axis: int,
chunks: Literal["auto"] = "auto",
):
"""Reorders one dimensions of a Dask Array based on an indexer.
Refer to :func:`dask.array.shuffle` for full documentation.
See Also
--------
dask.array.shuffle : equivalent function
"""
from dask.array._shuffle import shuffle
return shuffle(self, indexer, axis, chunks)
@property
def real(self):
from dask.array.ufunc import real
return real(self)
@property
def imag(self):
from dask.array.ufunc import imag
return imag(self)
def conj(self):
"""Complex-conjugate all elements.
Refer to :func:`dask.array.conj` for full documentation.
See Also
--------
dask.array.conj : equivalent function
"""
from dask.array.ufunc import conj
return conj(self)
def clip(self, min=None, max=None):
"""Return an array whose values are limited to ``[min, max]``.
One of max or min must be given.
Refer to :func:`dask.array.clip` for full documentation.
See Also
--------
dask.array.clip : equivalent function
"""
from dask.array.ufunc import clip
return clip(self, min, max)
def view(self, dtype=None, order="C"):
"""Get a view of the array as a new data type
Parameters
----------
dtype:
The dtype by which to view the array.
The default, None, results in the view having the same data-type
as the original array.
order: string
'C' or 'F' (Fortran) ordering
This reinterprets the bytes of the array under a new dtype. If that
dtype does not have the same size as the original array then the shape
will change.
Beware that both numpy and dask.array can behave oddly when taking
shape-changing views of arrays under Fortran ordering. Under some
versions of NumPy this function will fail when taking shape-changing
views of Fortran ordered arrays if the first dimension has chunks of
size one.
"""
if dtype is None:
dtype = self.dtype
else:
dtype = np.dtype(dtype)
mult = self.dtype.itemsize / dtype.itemsize
if order == "C":
chunks = self.chunks[:-1] + (
tuple(ensure_int(c * mult) for c in self.chunks[-1]),
)
elif order == "F":
chunks = (
tuple(ensure_int(c * mult) for c in self.chunks[0]),
) + self.chunks[1:]
else:
raise ValueError("Order must be one of 'C' or 'F'")
return self.map_blocks(
chunk.view, dtype, order=order, dtype=dtype, chunks=chunks
)
def swapaxes(self, axis1, axis2):
"""Return a view of the array with ``axis1`` and ``axis2`` interchanged.
Refer to :func:`dask.array.swapaxes` for full documentation.
See Also
--------
dask.array.swapaxes : equivalent function
"""
from dask.array.routines import swapaxes
return swapaxes(self, axis1, axis2)
def round(self, decimals=0):
"""Return array with each element rounded to the given number of decimals.
Refer to :func:`dask.array.round` for full documentation.
See Also
--------
dask.array.round : equivalent function
"""
from dask.array.routines import round
return round(self, decimals=decimals)
def copy(self):
"""
Copy array. This is a no-op for dask.arrays, which are immutable
"""
return Array(self.dask, self.name, self.chunks, meta=self)
def __deepcopy__(self, memo):
c = self.copy()
memo[id(self)] = c
return c
def to_delayed(self, optimize_graph=True):
"""Convert into an array of :class:`dask.delayed.Delayed` objects, one per chunk.
Parameters
----------
optimize_graph : bool, optional
If True [default], the graph is optimized before converting into
:class:`dask.delayed.Delayed` objects.
See Also
--------
dask.array.from_delayed
"""
keys = self.__dask_keys__()
graph = self.__dask_graph__()
layer = self.__dask_layers__()[0]
if optimize_graph:
graph = self.__dask_optimize__(graph, keys) # TODO, don't collapse graph
layer = f"delayed-{self.name}"
graph = HighLevelGraph.from_collections(layer, graph, dependencies=())
L = ndeepmap(self.ndim, lambda k: Delayed(k, graph, layer=layer), keys)
return np.array(L, dtype=object)
def repeat(self, repeats, axis=None):
"""Repeat elements of an array.
Refer to :func:`dask.array.repeat` for full documentation.
See Also
--------
dask.array.repeat : equivalent function
"""
from dask.array.creation import repeat
return repeat(self, repeats, axis=axis)
def nonzero(self):
"""Return the indices of the elements that are non-zero.
Refer to :func:`dask.array.nonzero` for full documentation.
See Also
--------
dask.array.nonzero : equivalent function
"""
from dask.array.routines import nonzero
return nonzero(self)
def to_zarr(self, *args, **kwargs):
"""Save array to the zarr storage format
See https://zarr.readthedocs.io for details about the format.
Refer to :func:`dask.array.to_zarr` for full documentation.
See also
--------
dask.array.to_zarr : equivalent function
"""
return to_zarr(self, *args, **kwargs)
def to_tiledb(self, uri, *args, **kwargs):
"""Save array to the TileDB storage manager
See https://docs.tiledb.io for details about the format and engine.
See function :func:`dask.array.to_tiledb` for argument documentation.
See also
--------
dask.array.to_tiledb : equivalent function
"""
from dask.array.tiledb_io import to_tiledb
return to_tiledb(self, uri, *args, **kwargs)
def ensure_int(f):
i = int(f)
if i != f:
raise ValueError(f"Could not coerce {f:f} to integer")
return i
@functools.lru_cache
def normalize_chunks_cached(
chunks, shape=None, limit=None, dtype=None, previous_chunks=None
):
"""Cached version of normalize_chunks.
.. note::
chunks and previous_chunks are expected to be hashable. Dicts and lists aren't
allowed for this function.
See :func:`normalize_chunks` for further documentation.
"""
return normalize_chunks(
chunks, shape=shape, limit=limit, dtype=dtype, previous_chunks=previous_chunks
)
def normalize_chunks(chunks, shape=None, limit=None, dtype=None, previous_chunks=None):
"""Normalize chunks to tuple of tuples
This takes in a variety of input types and information and produces a full
tuple-of-tuples result for chunks, suitable to be passed to Array or
rechunk or any other operation that creates a Dask array.
Parameters
----------
chunks: tuple, int, dict, or string
The chunks to be normalized. See examples below for more details
shape: Tuple[int]
The shape of the array
limit: int (optional)
The maximum block size to target in bytes,
if freedom is given to choose
dtype: np.dtype
previous_chunks: Tuple[Tuple[int]] optional
Chunks from a previous array that we should use for inspiration when
rechunking auto dimensions. If not provided but auto-chunking exists
then auto-dimensions will prefer square-like chunk shapes.
Examples
--------
Fully explicit tuple-of-tuples
>>> from dask.array.core import normalize_chunks
>>> normalize_chunks(((2, 2, 1), (2, 2, 2)), shape=(5, 6))
((2, 2, 1), (2, 2, 2))
Specify uniform chunk sizes
>>> normalize_chunks((2, 2), shape=(5, 6))
((2, 2, 1), (2, 2, 2))
Cleans up missing outer tuple
>>> normalize_chunks((3, 2), (5,))
((3, 2),)
Cleans up lists to tuples
>>> normalize_chunks([[2, 2], [3, 3]])
((2, 2), (3, 3))
Expands integer inputs 10 -> (10, 10)
>>> normalize_chunks(10, shape=(30, 5))
((10, 10, 10), (5,))
Expands dict inputs
>>> normalize_chunks({0: 2, 1: 3}, shape=(6, 6))
((2, 2, 2), (3, 3))
The values -1 and None get mapped to full size
>>> normalize_chunks((5, -1), shape=(10, 10))
((5, 5), (10,))
>>> normalize_chunks((5, None), shape=(10, 10))
((5, 5), (10,))
Use the value "auto" to automatically determine chunk sizes along certain
dimensions. This uses the ``limit=`` and ``dtype=`` keywords to
determine how large to make the chunks. The term "auto" can be used
anywhere an integer can be used. See array chunking documentation for more
information.
>>> normalize_chunks(("auto",), shape=(20,), limit=5, dtype='uint8')
((5, 5, 5, 5),)
>>> normalize_chunks("auto", (2, 3), dtype=np.int32)
((2,), (3,))
You can also use byte sizes (see :func:`dask.utils.parse_bytes`) in place of
"auto" to ask for a particular size
>>> normalize_chunks("1kiB", shape=(2000,), dtype='float32')
((256, 256, 256, 256, 256, 256, 256, 208),)
Respects null dimensions
>>> normalize_chunks(())
()
>>> normalize_chunks((), ())
()
>>> normalize_chunks((1,), ())
()
>>> normalize_chunks((), shape=(0, 0))
((0,), (0,))
Handles NaNs
>>> normalize_chunks((1, (np.nan,)), (1, np.nan))
((1,), (nan,))
"""
if dtype and not isinstance(dtype, np.dtype):
dtype = np.dtype(dtype)
if chunks is None:
raise ValueError(CHUNKS_NONE_ERROR_MESSAGE)
if isinstance(chunks, list):
chunks = tuple(chunks)
if isinstance(chunks, (Number, str)):
chunks = (chunks,) * len(shape)
if isinstance(chunks, dict):
chunks = tuple(chunks.get(i, None) for i in range(len(shape)))
if isinstance(chunks, np.ndarray):
chunks = chunks.tolist()
if not chunks and shape and all(s == 0 for s in shape):
chunks = ((0,),) * len(shape)
if (
shape
and len(shape) == 1
and len(chunks) > 1
and all(isinstance(c, (Number, str)) for c in chunks)
):
chunks = (chunks,)
if shape and len(chunks) != len(shape):
raise ValueError(
"Chunks and shape must be of the same length/dimension. "
f"Got chunks={chunks}, shape={shape}"
)
if -1 in chunks or None in chunks:
chunks = tuple(s if c == -1 or c is None else c for c, s in zip(chunks, shape))
# If specifying chunk size in bytes, use that value to set the limit.
# Verify there is only one consistent value of limit or chunk-bytes used.
for c in chunks:
if isinstance(c, str) and c != "auto":
parsed = parse_bytes(c)
if limit is None:
limit = parsed
elif parsed != limit:
raise ValueError(
"Only one consistent value of limit or chunk is allowed."
f"Used {parsed} != {limit}"
)
# Substitute byte limits with 'auto' now that limit is set.
chunks = tuple("auto" if isinstance(c, str) and c != "auto" else c for c in chunks)
if any(c == "auto" for c in chunks):
chunks = auto_chunks(chunks, shape, limit, dtype, previous_chunks)
allints = None
if chunks and shape is not None:
# allints: did we start with chunks as a simple tuple of ints?
allints = all(isinstance(c, int) for c in chunks)
chunks = _convert_int_chunk_to_tuple(shape, chunks)
for c in chunks:
if not c:
raise ValueError(
"Empty tuples are not allowed in chunks. Express "
"zero length dimensions with 0(s) in chunks"
)
if not allints and shape is not None:
if not all(
c == s or (math.isnan(c) or math.isnan(s))
for c, s in zip(map(sum, chunks), shape)
):
raise ValueError(
f"Chunks do not add up to shape. Got chunks={chunks}, shape={shape}"
)
if allints or isinstance(sum(sum(_) for _ in chunks), int):
# Fastpath for when we already know chunks contains only integers
return tuple(tuple(ch) for ch in chunks)
return tuple(
tuple(int(x) if not math.isnan(x) else np.nan for x in c) for c in chunks
)
def _convert_int_chunk_to_tuple(shape, chunks):
return sum(
(
(
blockdims_from_blockshape((s,), (c,))
if not isinstance(c, (tuple, list))
else (c,)
)
for s, c in zip(shape, chunks)
),
(),
)
def _compute_multiplier(limit: int, dtype, largest_block: int, result):
"""
Utility function for auto_chunk, to fin how much larger or smaller the ideal
chunk size is relative to what we have now.
"""
return (
limit
/ dtype.itemsize
/ largest_block
/ math.prod(max(r) if isinstance(r, tuple) else r for r in result.values() if r)
)
def auto_chunks(chunks, shape, limit, dtype, previous_chunks=None):
"""Determine automatic chunks
This takes in a chunks value that contains ``"auto"`` values in certain
dimensions and replaces those values with concrete dimension sizes that try
to get chunks to be of a certain size in bytes, provided by the ``limit=``
keyword. If multiple dimensions are marked as ``"auto"`` then they will
all respond to meet the desired byte limit, trying to respect the aspect
ratio of their dimensions in ``previous_chunks=``, if given.
Parameters
----------
chunks: Tuple
A tuple of either dimensions or tuples of explicit chunk dimensions
Some entries should be "auto"
shape: Tuple[int]
limit: int, str
The maximum allowable size of a chunk in bytes
previous_chunks: Tuple[Tuple[int]]
See also
--------
normalize_chunks: for full docstring and parameters
"""
if previous_chunks is not None:
# rioxarray is passing ((1, ), (x,)) for shapes like (100, 5x),
# so add this compat code for now
# https://github.com/corteva/rioxarray/pull/820
previous_chunks = (
c[0] if isinstance(c, tuple) and len(c) == 1 else c for c in previous_chunks
)
previous_chunks = _convert_int_chunk_to_tuple(shape, previous_chunks)
chunks = list(chunks)
autos = {i for i, c in enumerate(chunks) if c == "auto"}
if not autos:
return tuple(chunks)
if limit is None:
limit = config.get("array.chunk-size")
if isinstance(limit, str):
limit = parse_bytes(limit)
if dtype is None:
raise TypeError("dtype must be known for auto-chunking")
if dtype.hasobject:
raise NotImplementedError(
"Can not use auto rechunking with object dtype. "
"We are unable to estimate the size in bytes of object data"
)
for x in tuple(chunks) + tuple(shape):
if (
isinstance(x, Number)
and np.isnan(x)
or isinstance(x, tuple)
and np.isnan(x).any()
):
raise ValueError(
"Can not perform automatic rechunking with unknown "
f"(nan) chunk sizes.{unknown_chunk_message}"
)
limit = max(1, limit)
chunksize_tolerance = config.get("array.chunk-size-tolerance")
largest_block = math.prod(
cs if isinstance(cs, Number) else max(cs) for cs in chunks if cs != "auto"
)
if previous_chunks:
# Base ideal ratio on the median chunk size of the previous chunks
median_chunks = {a: np.median(previous_chunks[a]) for a in autos}
result = {}
# How much larger or smaller the ideal chunk size is relative to what we have now
multiplier = _compute_multiplier(limit, dtype, largest_block, median_chunks)
if multiplier < 1:
# we want to update inplace, algorithm relies on it in this case
result = median_chunks
ideal_shape = []
for i, s in enumerate(shape):
chunk_frequencies = frequencies(previous_chunks[i])
mode, count = max(chunk_frequencies.items(), key=lambda kv: kv[1])
if mode > 1 and count >= len(previous_chunks[i]) / 2:
ideal_shape.append(mode)
else:
ideal_shape.append(s)
def _trivial_aggregate(a):
autos.remove(a)
del median_chunks[a]
return True
multiplier_remaining = True
reduce_case = multiplier < 1
while multiplier_remaining: # while things change
last_autos = set(autos) # record previous values
multiplier_remaining = False
# Expand or contract each of the dimensions appropriately
for a in sorted(autos):
this_multiplier = multiplier ** (1 / len(last_autos))
proposed = median_chunks[a] * this_multiplier
this_chunksize_tolerance = chunksize_tolerance ** (1 / len(last_autos))
max_chunk_size = proposed * this_chunksize_tolerance
if proposed > shape[a]: # we've hit the shape boundary
chunks[a] = shape[a]
multiplier_remaining = _trivial_aggregate(a)
largest_block *= shape[a]
result[a] = (shape[a],)
continue
elif reduce_case or max(previous_chunks[a]) > max_chunk_size:
result[a] = round_to(proposed, ideal_shape[a])
if proposed < 1:
multiplier_remaining = True
autos.discard(a)
continue
else:
dimension_result, new_chunk = [], 0
for c in previous_chunks[a]:
if c + new_chunk <= proposed:
# keep increasing the chunk
new_chunk += c
else:
# We reach the boundary so start a new chunk
if new_chunk > 0:
dimension_result.append(new_chunk)
new_chunk = c
if new_chunk > 0:
dimension_result.append(new_chunk)
result[a] = tuple(dimension_result)
# recompute how much multiplier we have left, repeat
if multiplier_remaining or reduce_case:
last_multiplier = multiplier
multiplier = _compute_multiplier(
limit, dtype, largest_block, median_chunks
)
if multiplier != last_multiplier:
multiplier_remaining = True
for k, v in result.items():
chunks[k] = v if v else 0
return tuple(chunks)
else:
# Check if dtype.itemsize is greater than 0
if dtype.itemsize == 0:
raise ValueError(
"auto-chunking with dtype.itemsize == 0 is not supported, please pass in `chunks` explicitly"
)
size = (limit / dtype.itemsize / largest_block) ** (1 / len(autos))
small = [i for i in autos if shape[i] < size]
if small:
for i in small:
chunks[i] = (shape[i],)
return auto_chunks(chunks, shape, limit, dtype)
for i in autos:
chunks[i] = round_to(size, shape[i])
return tuple(chunks)
def _split_up_single_chunk(
c: int, this_chunksize_tolerance: float, max_chunk_size: int, proposed: int
) -> list[int]:
# Calculate by what factor we have to split this chunk
m = c / proposed
if math.ceil(m) / m > this_chunksize_tolerance:
# We want to smooth things potentially if rounding up would change the result
# by a lot
m = math.ceil(c / max_chunk_size)
else:
m = math.ceil(m)
# split the chunk
new_c, remainder = divmod(c, min(m, c))
x = [new_c] * min(m, c)
for i in range(remainder):
x[i] += 1
return x
def round_to(c, s):
"""Return a chunk dimension that is close to an even multiple or factor
We want values for c that are nicely aligned with s.
If c is smaller than s we use the original chunk size and accept an
uneven chunk at the end.
If c is larger than s then we want the largest multiple of s that is still
smaller than c.
"""
if c <= s:
return max(1, int(c))
else:
return c // s * s
def _get_chunk_shape(a):
s = np.asarray(a.shape, dtype=int)
return s[len(s) * (None,) + (slice(None),)]
def from_array(
x,
chunks="auto",
name=None,
lock=False,
asarray=None,
fancy=True,
getitem=None,
meta=None,
inline_array=False,
):
"""Create dask array from something that looks like an array.
Input must have a ``.shape``, ``.ndim``, ``.dtype`` and support numpy-style slicing.
Parameters
----------
x : array_like
chunks : int, tuple
How to chunk the array. Must be one of the following forms:
- A blocksize like 1000.
- A blockshape like (1000, 1000).
- Explicit sizes of all blocks along all dimensions like
((1000, 1000, 500), (400, 400)).
- A size in bytes, like "100 MiB" which will choose a uniform
block-like shape
- The word "auto" which acts like the above, but uses a configuration
value ``array.chunk-size`` for the chunk size
-1 or None as a blocksize indicate the size of the corresponding
dimension.
name : str or bool, optional
The key name to use for the array. Defaults to a hash of ``x``.
Hashing is useful if the same value of ``x`` is used to create multiple
arrays, as Dask can then recognise that they're the same and
avoid duplicate computations. However, it can also be slow, and if the
array is not contiguous it is copied for hashing. If the array uses
stride tricks (such as :func:`numpy.broadcast_to` or
:func:`skimage.util.view_as_windows`) to have a larger logical
than physical size, this copy can cause excessive memory usage.
If you don't need the deduplication provided by hashing, use
``name=False`` to generate a random name instead of hashing, which
avoids the pitfalls described above. Using ``name=True`` is
equivalent to the default.
By default, hashing uses python's standard sha1. This behaviour can be
changed by installing cityhash, xxhash or murmurhash. If installed,
a large-factor speedup can be obtained in the tokenisation step.
.. note::
Because this ``name`` is used as the key in task graphs, you should
ensure that it uniquely identifies the data contained within. If
you'd like to provide a descriptive name that is still unique, combine
the descriptive name with :func:`dask.base.tokenize` of the
``array_like``. See :ref:`graphs` for more.
lock : bool or Lock, optional
If ``x`` doesn't support concurrent reads then provide a lock here, or
pass in True to have dask.array create one for you.
asarray : bool, optional
If True then call np.asarray on chunks to convert them to numpy arrays.
If False then chunks are passed through unchanged.
If None (default) then we use True if the ``__array_function__`` method
is undefined.
.. note::
Dask does not preserve the memory layout of the original array when
the array is created using Fortran rather than C ordering.
fancy : bool, optional
If ``x`` doesn't support fancy indexing (e.g. indexing with lists or
arrays) then set to False. Default is True.
meta : Array-like, optional
The metadata for the resulting dask array. This is the kind of array
that will result from slicing the input array.
Defaults to the input array.
inline_array : bool, default False
How to include the array in the task graph. By default
(``inline_array=False``) the array is included in a task by itself,
and each chunk refers to that task by its key.
.. code-block:: python
>>> x = h5py.File("data.h5")["/x"] # doctest: +SKIP
>>> a = da.from_array(x, chunks=500) # doctest: +SKIP
>>> dict(a.dask) # doctest: +SKIP
{
'array-original-<name>': <HDF5 dataset ...>,
('array-<name>', 0): (getitem, "array-original-<name>", ...),
('array-<name>', 1): (getitem, "array-original-<name>", ...)
}
With ``inline_array=True``, Dask will instead inline the array directly
in the values of the task graph.
.. code-block:: python
>>> a = da.from_array(x, chunks=500, inline_array=True) # doctest: +SKIP
>>> dict(a.dask) # doctest: +SKIP
{
('array-<name>', 0): (getitem, <HDF5 dataset ...>, ...),
('array-<name>', 1): (getitem, <HDF5 dataset ...>, ...)
}
Note that there's no key in the task graph with just the array `x`
anymore. Instead it's placed directly in the values.
The right choice for ``inline_array`` depends on several factors,
including the size of ``x``, how expensive it is to create, which
scheduler you're using, and the pattern of downstream computations.
As a heuristic, ``inline_array=True`` may be the right choice when
the array ``x`` is cheap to serialize and deserialize (since it's
included in the graph many times) and if you're experiencing ordering
issues (see :ref:`order` for more).
This has no effect when ``x`` is a NumPy array.
Examples
--------
>>> x = h5py.File('...')['/data/path'] # doctest: +SKIP
>>> a = da.from_array(x, chunks=(1000, 1000)) # doctest: +SKIP
If your underlying datastore does not support concurrent reads then include
the ``lock=True`` keyword argument or ``lock=mylock`` if you want multiple
arrays to coordinate around the same lock.
>>> a = da.from_array(x, chunks=(1000, 1000), lock=True) # doctest: +SKIP
If your underlying datastore has a ``.chunks`` attribute (as h5py and zarr
datasets do) then a multiple of that chunk shape will be used if you
do not provide a chunk shape.
>>> a = da.from_array(x, chunks='auto') # doctest: +SKIP
>>> a = da.from_array(x, chunks='100 MiB') # doctest: +SKIP
>>> a = da.from_array(x) # doctest: +SKIP
If providing a name, ensure that it is unique
>>> import dask.base
>>> token = dask.base.tokenize(x) # doctest: +SKIP
>>> a = da.from_array('myarray-' + token) # doctest: +SKIP
NumPy ndarrays are eagerly sliced and then embedded in the graph.
>>> import dask.array
>>> a = dask.array.from_array(np.array([[1, 2], [3, 4]]), chunks=(1,1))
>>> a.dask[a.name, 0, 0][0]
array([1])
Chunks with exactly-specified, different sizes can be created.
>>> import numpy as np
>>> import dask.array as da
>>> rng = np.random.default_rng()
>>> x = rng.random((100, 6))
>>> a = da.from_array(x, chunks=((67, 33), (6,)))
"""
if isinstance(x, Array):
raise ValueError(
"Array is already a dask array. Use 'asarray' or 'rechunk' instead."
)
if xr is not None and isinstance(x, xr.DataArray) and x.chunks is not None:
if isinstance(x.data, Array):
return x.data
elif is_dask_collection(x):
warnings.warn(
"Passing an object to dask.array.from_array which is already a "
"Dask collection. This can lead to unexpected behavior."
)
if isinstance(x, (list, tuple, memoryview) + np.ScalarType):
x = np.array(x)
if is_arraylike(x) and hasattr(x, "copy"):
x = x.copy()
if asarray is None:
asarray = not hasattr(x, "__array_function__")
previous_chunks = getattr(x, "chunks", None)
# As of Zarr 3.x, arrays can have a shards attribute. If present,
# this defines the smallest array region that is safe to write, and
# thus this is a better starting point than the chunks attribute.
# We check for chunks AND shards to be somewhat specific to Zarr 3.x arrays
if (
hasattr(x, "chunks")
and hasattr(x, "shards")
and (x.shards is not None)
and chunks == "auto"
):
previous_chunks = x.shards
chunks = normalize_chunks(
chunks, x.shape, dtype=x.dtype, previous_chunks=previous_chunks
)
if name in (None, True):
token = tokenize(x, chunks, lock, asarray, fancy, getitem, inline_array)
name = name or f"array-{token}"
elif name is False:
name = f"array-{uuid.uuid1()}"
if lock is True:
lock = SerializableLock()
is_ndarray = type(x) in (np.ndarray, np.ma.core.MaskedArray)
is_single_block = all(len(c) == 1 for c in chunks)
# Always use the getter for h5py etc. Not using isinstance(x, np.ndarray)
# because np.matrix is a subclass of np.ndarray.
if is_ndarray and not is_single_block and not lock:
# eagerly slice numpy arrays to prevent memory blowup
# GH5367, GH5601
slices = slices_from_chunks(chunks)
keys = product([name], *(range(len(bds)) for bds in chunks))
values = [x[slc] for slc in slices]
dsk = dict(zip(keys, values))
elif is_ndarray and is_single_block:
# No slicing needed
dsk = {(name,) + (0,) * x.ndim: x}
else:
if getitem is None:
if fancy:
getitem = getter
else:
getitem = getter_nofancy
dsk = graph_from_arraylike(
x,
chunks,
x.shape,
name,
getitem=getitem,
lock=lock,
asarray=asarray,
dtype=x.dtype,
inline_array=inline_array,
)
# Workaround for TileDB, its indexing is 1-based,
# and doesn't seems to support 0-length slicing
if x.__class__.__module__.split(".")[0] == "tiledb" and hasattr(x, "_ctx_"):
return Array(dsk, name, chunks, dtype=x.dtype)
if meta is None:
meta = x
return Array(dsk, name, chunks, meta=meta, dtype=getattr(x, "dtype", None))
@lru_cache
def _zarr_v3() -> bool:
try:
import zarr
except ImportError:
return False
else:
return Version(zarr.__version__).major >= 3
def from_zarr(
url,
component=None,
storage_options=None,
chunks=None,
name=None,
inline_array=False,
**kwargs,
):
"""Load array from the zarr storage format
See https://zarr.readthedocs.io for details about the format.
Parameters
----------
url: Zarr Array or str or MutableMapping
Location of the data. A URL can include a protocol specifier like s3://
for remote data. Can also be any MutableMapping instance, which should
be serializable if used in multiple processes.
component: str or None
If the location is a zarr group rather than an array, this is the
subcomponent that should be loaded, something like ``'foo/bar'``.
storage_options: dict
Any additional parameters for the storage backend (ignored for local
paths)
chunks: tuple of ints or tuples of ints
Passed to :func:`dask.array.from_array`, allows setting the chunks on
initialisation, if the chunking scheme in the on-disc dataset is not
optimal for the calculations to follow.
name : str, optional
An optional keyname for the array. Defaults to hashing the input
kwargs:
Passed to :class:`zarr.core.Array`.
inline_array : bool, default False
Whether to inline the zarr Array in the values of the task graph.
See :meth:`dask.array.from_array` for an explanation.
See Also
--------
from_array
"""
import zarr
storage_options = storage_options or {}
if isinstance(url, zarr.Array):
z = url
elif isinstance(url, (str, os.PathLike)):
if isinstance(url, os.PathLike):
url = os.fspath(url)
if storage_options:
if _zarr_v3():
store = zarr.storage.FsspecStore.from_url(
url, storage_options=storage_options
)
else:
store = zarr.storage.FSStore(url, **storage_options)
else:
store = url
z = zarr.open_array(store=store, path=component, **kwargs)
else:
z = zarr.open_array(store=url, path=component, **kwargs)
chunks = chunks if chunks is not None else z.chunks
if name is None:
name = "from-zarr-" + tokenize(z, component, storage_options, chunks, **kwargs)
return from_array(z, chunks, name=name, inline_array=inline_array)
def to_zarr(
arr,
url,
component=None,
storage_options=None,
overwrite=False,
region=None,
compute=True,
return_stored=False,
**kwargs,
):
"""Save array to the zarr storage format
See https://zarr.readthedocs.io for details about the format.
Parameters
----------
arr: dask.array
Data to store
url: Zarr Array or str or MutableMapping
Location of the data. A URL can include a protocol specifier like s3://
for remote data. Can also be any MutableMapping instance, which should
be serializable if used in multiple processes.
component: str or None
If the location is a zarr group rather than an array, this is the
subcomponent that should be created/over-written.
storage_options: dict
Any additional parameters for the storage backend (ignored for local
paths)
overwrite: bool
If given array already exists, overwrite=False will cause an error,
where overwrite=True will replace the existing data.
region: tuple of slices or None
The region of data that should be written if ``url`` is a zarr.Array.
Not to be used with other types of ``url``.
compute: bool
See :func:`~dask.array.store` for more details.
return_stored: bool
See :func:`~dask.array.store` for more details.
**kwargs:
Passed to the :func:`zarr.creation.create` function, e.g., compression options.
Raises
------
ValueError
If ``arr`` has unknown chunk sizes, which is not supported by Zarr.
If ``region`` is specified and ``url`` is not a zarr.Array
See Also
--------
dask.array.store
dask.array.Array.compute_chunk_sizes
"""
import zarr
if np.isnan(arr.shape).any():
raise ValueError(
"Saving a dask array with unknown chunk sizes is not "
f"currently supported by Zarr.{unknown_chunk_message}"
)
if _zarr_v3():
zarr_mem_store_types = (zarr.storage.MemoryStore,)
else:
zarr_mem_store_types = (dict, zarr.storage.MemoryStore, zarr.storage.KVStore)
if isinstance(url, zarr.Array):
z = url
if isinstance(z.store, zarr_mem_store_types):
try:
from distributed import default_client
default_client()
except (ImportError, ValueError):
pass
else:
raise RuntimeError(
"Cannot store into in memory Zarr Array using "
"the distributed scheduler."
)
zarr_write_chunks = _get_zarr_write_chunks(z)
dask_write_chunks = normalize_chunks(
chunks="auto",
shape=z.shape,
dtype=z.dtype,
previous_chunks=zarr_write_chunks,
)
if region is not None:
from dask.array.slicing import new_blockdim, normalize_index
index = normalize_index(region, z.shape)
dask_write_chunks = tuple(
tuple(new_blockdim(s, c, r))
for s, c, r in zip(z.shape, dask_write_chunks, index)
)
for ax, (dw, zw) in enumerate(
zip(dask_write_chunks, zarr_write_chunks, strict=True)
):
if len(dw) >= 1:
nominal_dask_chunk_size = dw[0]
if not nominal_dask_chunk_size % zw == 0:
safe_chunk_size = np.prod(zarr_write_chunks) * max(
1, z.dtype.itemsize
)
msg = (
f"The input Dask array will be rechunked along axis {ax} with chunk size "
f"{nominal_dask_chunk_size}, but a chunk size divisible by {zw} is "
f"required for Dask to write safely to the Zarr array {z}. "
"To avoid risk of data loss when writing to this Zarr array, set the "
'"array.chunk-size" configuration parameter to at least the size in'
" bytes of a single on-disk "
f"chunk (or shard) of the Zarr array, which in this case is "
f"{safe_chunk_size} bytes. "
f'E.g., dask.config.set({{"array.chunk-size": {safe_chunk_size}}})'
)
warnings.warn(
msg,
PerformanceWarning,
stacklevel=3,
)
break
arr = arr.rechunk(dask_write_chunks)
if region is not None:
regions = [region]
else:
regions = None
return arr.store(
z, lock=False, regions=regions, compute=compute, return_stored=return_stored
)
elif not _check_regular_chunks(arr.chunks):
# We almost certainly get here because auto chunking has been used
# on irregular chunks. The max will then be smaller than auto, so using
# max is a safe choice
arr = arr.rechunk(tuple(map(max, arr.chunks)))
if region is not None:
raise ValueError("Cannot use `region` keyword when url is not a `zarr.Array`.")
if not _check_regular_chunks(arr.chunks):
raise ValueError(
"Attempt to save array to zarr with irregular "
"chunking, please call `arr.rechunk(...)` first."
)
storage_options = storage_options or {}
if storage_options:
if _zarr_v3():
read_only = (
kwargs["read_only"]
if "read_only" in kwargs
else kwargs.pop("mode", "a") == "r"
)
store = zarr.storage.FsspecStore.from_url(
url, read_only=read_only, storage_options=storage_options
)
else:
store = zarr.storage.FSStore(url, **storage_options)
else:
store = url
chunks = [c[0] for c in arr.chunks]
z = zarr.create(
shape=arr.shape,
chunks=chunks,
dtype=arr.dtype,
store=store,
path=component,
overwrite=overwrite,
**kwargs,
)
return arr.store(z, lock=False, compute=compute, return_stored=return_stored)
def _get_zarr_write_chunks(zarr_array) -> tuple[int, ...]:
"""Get the appropriate chunk shape for writing to a Zarr array.
For Zarr v3 arrays with sharding, returns the shard shape.
For arrays without sharding, returns the chunk shape.
For Zarr v2 arrays, returns the chunk shape.
Parameters
----------
zarr_array : zarr.Array
The target zarr array
Returns
-------
tuple
The chunk shape to use for rechunking the dask array
"""
# Zarr V3 array with shards
if hasattr(zarr_array, "shards") and zarr_array.shards is not None:
return zarr_array.shards
# Zarr V3 array without shards, or Zarr V2 array
return zarr_array.chunks
def _check_regular_chunks(chunkset):
"""Check if the chunks are regular
"Regular" in this context means that along every axis, the chunks all
have the same size, except the last one, which may be smaller
Parameters
----------
chunkset: tuple of tuples of ints
From the ``.chunks`` attribute of an ``Array``
Returns
-------
True if chunkset passes, else False
Examples
--------
>>> import dask.array as da
>>> arr = da.zeros(10, chunks=(5, ))
>>> _check_regular_chunks(arr.chunks)
True
>>> arr = da.zeros(10, chunks=((3, 3, 3, 1), ))
>>> _check_regular_chunks(arr.chunks)
True
>>> arr = da.zeros(10, chunks=((3, 1, 3, 3), ))
>>> _check_regular_chunks(arr.chunks)
False
"""
for chunks in chunkset:
if len(chunks) == 1:
continue
if len(set(chunks[:-1])) > 1:
return False
if chunks[-1] > chunks[0]:
return False
return True
def from_delayed(value, shape, dtype=None, meta=None, name=None):
"""Create a dask array from a dask delayed value
This routine is useful for constructing dask arrays in an ad-hoc fashion
using dask delayed, particularly when combined with stack and concatenate.
The dask array will consist of a single chunk.
Examples
--------
>>> import dask
>>> import dask.array as da
>>> import numpy as np
>>> value = dask.delayed(np.ones)(5)
>>> array = da.from_delayed(value, (5,), dtype=float)
>>> array
dask.array<from-value, shape=(5,), dtype=float64, chunksize=(5,), chunktype=numpy.ndarray>
>>> array.compute()
array([1., 1., 1., 1., 1.])
"""
from dask.delayed import Delayed, delayed
is_future = False
name = name or "from-value-" + tokenize(value, shape, dtype, meta)
if isinstance(value, TaskRef):
is_future = True
elif not isinstance(value, Delayed) and hasattr(value, "key"):
value = delayed(value)
task = Alias(
key=(name,) + (0,) * len(shape),
target=value.key,
)
dsk = {task.key: task}
if is_future:
dsk[value.key] = value
dependencies = []
else:
dependencies = [value]
chunks = tuple((d,) for d in shape)
# TODO: value._key may not be the name of the layer in value.dask
# This should be fixed after we build full expression graphs
graph = HighLevelGraph.from_collections(name, dsk, dependencies=dependencies)
return Array(graph, name, chunks, dtype=dtype, meta=meta)
def from_func(func, shape, dtype=None, name=None, args=(), kwargs=None):
"""Create dask array in a single block by calling a function
Calling the provided function with func(*args, **kwargs) should return a
NumPy array of the indicated shape and dtype.
Examples
--------
>>> a = from_func(np.arange, (3,), dtype='i8', args=(3,))
>>> a.compute()
array([0, 1, 2])
This works particularly well when coupled with dask.array functions like
concatenate and stack:
>>> arrays = [from_func(np.array, (), dtype='i8', args=(n,)) for n in range(5)]
>>> stack(arrays).compute()
array([0, 1, 2, 3, 4])
"""
if kwargs is None:
kwargs = {}
name = name or "from_func-" + tokenize(func, shape, dtype, args, kwargs)
if args or kwargs:
func = partial(func, *args, **kwargs)
dsk = {(name,) + (0,) * len(shape): (func,)}
chunks = tuple((i,) for i in shape)
return Array(dsk, name, chunks, dtype)
def common_blockdim(blockdims):
"""Find the common block dimensions from the list of block dimensions
Currently only implements the simplest possible heuristic: the common
block-dimension is the only one that does not span fully span a dimension.
This is a conservative choice that allows us to avoid potentially very
expensive rechunking.
Assumes that each element of the input block dimensions has all the same
sum (i.e., that they correspond to dimensions of the same size).
Examples
--------
>>> common_blockdim([(3,), (2, 1)])
(2, 1)
>>> common_blockdim([(1, 2), (2, 1)])
(1, 1, 1)
>>> common_blockdim([(2, 2), (3, 1)]) # doctest: +SKIP
Traceback (most recent call last):
...
ValueError: Chunks do not align
"""
if not any(blockdims):
return ()
non_trivial_dims = {d for d in blockdims if len(d) > 1}
if len(non_trivial_dims) == 1:
return first(non_trivial_dims)
if len(non_trivial_dims) == 0:
return max(blockdims, key=first)
if np.isnan(sum(map(sum, blockdims))):
raise ValueError(
f"Arrays' chunk sizes ({blockdims}) are unknown.\n\n"
"A possible solution:\n"
" x.compute_chunk_sizes()"
)
if len(set(map(sum, non_trivial_dims))) > 1:
raise ValueError("Chunks do not add up to same value", blockdims)
# We have multiple non-trivial chunks on this axis
# e.g. (5, 2) and (4, 3)
# We create a single chunk tuple with the same total length
# that evenly divides both, e.g. (4, 1, 2)
# To accomplish this we walk down all chunk tuples together, finding the
# smallest element, adding it to the output, and subtracting it from all
# other elements and remove the element itself. We stop once we have
# burned through all of the chunk tuples.
# For efficiency's sake we reverse the lists so that we can pop off the end
rchunks = [list(ntd)[::-1] for ntd in non_trivial_dims]
total = sum(first(non_trivial_dims))
i = 0
out = []
while i < total:
m = min(c[-1] for c in rchunks)
out.append(m)
for c in rchunks:
c[-1] -= m
if c[-1] == 0:
c.pop()
i += m
return tuple(out)
def unify_chunks(*args, **kwargs):
"""
Unify chunks across a sequence of arrays
This utility function is used within other common operations like
:func:`dask.array.core.map_blocks` and :func:`dask.array.core.blockwise`.
It is not commonly used by end-users directly.
Parameters
----------
*args: sequence of Array, index pairs
Sequence like (x, 'ij', y, 'jk', z, 'i')
Examples
--------
>>> import dask.array as da
>>> x = da.ones(10, chunks=((5, 2, 3),))
>>> y = da.ones(10, chunks=((2, 3, 5),))
>>> chunkss, arrays = unify_chunks(x, 'i', y, 'i')
>>> chunkss
{'i': (2, 3, 2, 3)}
>>> x = da.ones((100, 10), chunks=(20, 5))
>>> y = da.ones((10, 100), chunks=(4, 50))
>>> chunkss, arrays = unify_chunks(x, 'ij', y, 'jk', 'constant', None)
>>> chunkss # doctest: +SKIP
{'k': (50, 50), 'i': (20, 20, 20, 20, 20), 'j': (4, 1, 3, 2)}
>>> unify_chunks(0, None)
({}, [0])
Returns
-------
chunkss : dict
Map like {index: chunks}.
arrays : list
List of rechunked arrays.
See Also
--------
common_blockdim
"""
if not args:
return {}, []
arginds = [
(asanyarray(a) if ind is not None else a, ind) for a, ind in partition(2, args)
] # [x, ij, y, jk]
warn = kwargs.get("warn", True)
arrays, inds = zip(*arginds)
if all(ind is None for ind in inds):
return {}, list(arrays)
if all(ind == inds[0] for ind in inds) and all(
a.chunks == arrays[0].chunks for a in arrays
):
return dict(zip(inds[0], arrays[0].chunks)), arrays
nameinds = []
blockdim_dict = dict()
max_parts = 0
for a, ind in arginds:
if ind is not None:
nameinds.append((a.name, ind))
blockdim_dict[a.name] = a.chunks
max_parts = max(max_parts, a.npartitions)
else:
nameinds.append((a, ind))
chunkss = broadcast_dimensions(nameinds, blockdim_dict, consolidate=common_blockdim)
nparts = math.prod(map(len, chunkss.values()))
if warn and nparts and nparts >= max_parts * 10:
warnings.warn(
f"Increasing number of chunks by factor of {int(nparts / max_parts)}",
PerformanceWarning,
stacklevel=3,
)
arrays = []
for a, i in arginds:
if i is None:
arrays.append(a)
else:
chunks = tuple(
(
chunkss[j]
if a.shape[n] > 1
else a.shape[n] if not np.isnan(sum(chunkss[j])) else None
)
for n, j in enumerate(i)
)
if chunks != a.chunks and all(a.chunks):
arrays.append(a.rechunk(chunks))
else:
arrays.append(a)
return chunkss, arrays
def unpack_singleton(x):
"""
>>> unpack_singleton([[[[1]]]])
1
>>> unpack_singleton(np.array(np.datetime64('2000-01-01')))
array('2000-01-01', dtype='datetime64[D]')
"""
while isinstance(x, (list, tuple)):
try:
x = x[0]
except (IndexError, TypeError, KeyError):
break
return x
def block(arrays, allow_unknown_chunksizes=False):
"""
Assemble an nd-array from nested lists of blocks.
Blocks in the innermost lists are concatenated along the last
dimension (-1), then these are concatenated along the second-last
dimension (-2), and so on until the outermost list is reached
Blocks can be of any dimension, but will not be broadcasted using the normal
rules. Instead, leading axes of size 1 are inserted, to make ``block.ndim``
the same for all blocks. This is primarily useful for working with scalars,
and means that code like ``block([v, 1])`` is valid, where
``v.ndim == 1``.
When the nested list is two levels deep, this allows block matrices to be
constructed from their components.
Parameters
----------
arrays : nested list of array_like or scalars (but not tuples)
If passed a single ndarray or scalar (a nested list of depth 0), this
is returned unmodified (and not copied).
Elements shapes must match along the appropriate axes (without
broadcasting), but leading 1s will be prepended to the shape as
necessary to make the dimensions match.
allow_unknown_chunksizes: bool
Allow unknown chunksizes, such as come from converting from dask
dataframes. Dask.array is unable to verify that chunks line up. If
data comes from differently aligned sources then this can cause
unexpected results.
Returns
-------
block_array : ndarray
The array assembled from the given blocks.
The dimensionality of the output is equal to the greatest of:
* the dimensionality of all the inputs
* the depth to which the input list is nested
Raises
------
ValueError
* If list depths are mismatched - for instance, ``[[a, b], c]`` is
illegal, and should be spelt ``[[a, b], [c]]``
* If lists are empty - for instance, ``[[a, b], []]``
See Also
--------
concatenate : Join a sequence of arrays together.
stack : Stack arrays in sequence along a new dimension.
hstack : Stack arrays in sequence horizontally (column wise).
vstack : Stack arrays in sequence vertically (row wise).
dstack : Stack arrays in sequence depth wise (along third dimension).
vsplit : Split array into a list of multiple sub-arrays vertically.
Notes
-----
When called with only scalars, ``block`` is equivalent to an ndarray
call. So ``block([[1, 2], [3, 4]])`` is equivalent to
``array([[1, 2], [3, 4]])``.
This function does not enforce that the blocks lie on a fixed grid.
``block([[a, b], [c, d]])`` is not restricted to arrays of the form::
AAAbb
AAAbb
cccDD
But is also allowed to produce, for some ``a, b, c, d``::
AAAbb
AAAbb
cDDDD
Since concatenation happens along the last axis first, `block` is _not_
capable of producing the following directly::
AAAbb
cccbb
cccDD
Matlab's "square bracket stacking", ``[A, B, ...; p, q, ...]``, is
equivalent to ``block([[A, B, ...], [p, q, ...]])``.
"""
# This was copied almost verbatim from numpy.core.shape_base.block
# See numpy license at https://github.com/numpy/numpy/blob/master/LICENSE.txt
# or NUMPY_LICENSE.txt within this directory
def atleast_nd(x, ndim):
x = asanyarray(x)
diff = max(ndim - x.ndim, 0)
if diff == 0:
return x
else:
return x[(None,) * diff + (Ellipsis,)]
def format_index(index):
return "arrays" + "".join(f"[{i}]" for i in index)
rec = _Recurser(recurse_if=lambda x: type(x) is list)
# ensure that the lists are all matched in depth
list_ndim = None
any_empty = False
for index, value, entering in rec.walk(arrays):
if type(value) is tuple:
# not strictly necessary, but saves us from:
# - more than one way to do things - no point treating tuples like
# lists
# - horribly confusing behaviour that results when tuples are
# treated like ndarray
raise TypeError(
f"{format_index(index)} is a tuple. "
"Only lists can be used to arrange blocks, and np.block does "
"not allow implicit conversion from tuple to ndarray."
)
if not entering:
curr_depth = len(index)
elif len(value) == 0:
curr_depth = len(index) + 1
any_empty = True
else:
continue
if list_ndim is not None and list_ndim != curr_depth:
raise ValueError(
f"List depths are mismatched. First element was at depth {list_ndim}, "
f"but there is an element at depth {curr_depth} ({format_index(index)})"
)
list_ndim = curr_depth
# do this here so we catch depth mismatches first
if any_empty:
raise ValueError("Lists cannot be empty")
# convert all the arrays to ndarrays
arrays = rec.map_reduce(arrays, f_map=asanyarray, f_reduce=list)
# determine the maximum dimension of the elements
elem_ndim = rec.map_reduce(arrays, f_map=lambda xi: xi.ndim, f_reduce=max)
ndim = max(list_ndim, elem_ndim)
# first axis to concatenate along
first_axis = ndim - list_ndim
# Make all the elements the same dimension
arrays = rec.map_reduce(
arrays, f_map=lambda xi: atleast_nd(xi, ndim), f_reduce=list
)
# concatenate innermost lists on the right, outermost on the left
return rec.map_reduce(
arrays,
f_reduce=lambda xs, axis: concatenate(
list(xs), axis=axis, allow_unknown_chunksizes=allow_unknown_chunksizes
),
f_kwargs=lambda axis: dict(axis=(axis + 1)),
axis=first_axis,
)
def concatenate(seq, axis=0, allow_unknown_chunksizes=False):
"""
Concatenate arrays along an existing axis
Given a sequence of dask Arrays form a new dask Array by stacking them
along an existing dimension (axis=0 by default)
Parameters
----------
seq: list of dask.arrays
axis: int
Dimension along which to align all of the arrays. If axis is None,
arrays are flattened before use.
allow_unknown_chunksizes: bool
Allow unknown chunksizes, such as come from converting from dask
dataframes. Dask.array is unable to verify that chunks line up. If
data comes from differently aligned sources then this can cause
unexpected results.
Examples
--------
Create slices
>>> import dask.array as da
>>> import numpy as np
>>> data = [da.from_array(np.ones((4, 4)), chunks=(2, 2))
... for i in range(3)]
>>> x = da.concatenate(data, axis=0)
>>> x.shape
(12, 4)
>>> da.concatenate(data, axis=1).shape
(4, 12)
Result is a new dask Array
See Also
--------
stack
"""
from dask.array import wrap
seq = [asarray(a, allow_unknown_chunksizes=allow_unknown_chunksizes) for a in seq]
if not seq:
raise ValueError("Need array(s) to concatenate")
if axis is None:
seq = [a.flatten() for a in seq]
axis = 0
seq_metas = [meta_from_array(s) for s in seq]
_concatenate = concatenate_lookup.dispatch(
type(max(seq_metas, key=lambda x: getattr(x, "__array_priority__", 0)))
)
meta = _concatenate(seq_metas, axis=axis)
# Promote types to match meta
seq = [a.astype(meta.dtype) for a in seq]
# Find output array shape
ndim = len(seq[0].shape)
shape = tuple(
sum(a.shape[i] for a in seq) if i == axis else seq[0].shape[i]
for i in range(ndim)
)
# Drop empty arrays
seq2 = [a for a in seq if a.size]
if not seq2:
seq2 = seq
if axis < 0:
axis = ndim + axis
if axis >= ndim:
msg = (
"Axis must be less than than number of dimensions"
"\nData has %d dimensions, but got axis=%d"
)
raise ValueError(msg % (ndim, axis))
n = len(seq2)
if n == 0:
try:
return wrap.empty_like(meta, shape=shape, chunks=shape, dtype=meta.dtype)
except TypeError:
return wrap.empty(shape, chunks=shape, dtype=meta.dtype)
elif n == 1:
return seq2[0]
if not allow_unknown_chunksizes and not all(
i == axis or all(x.shape[i] == seq2[0].shape[i] for x in seq2)
for i in range(ndim)
):
if any(map(np.isnan, seq2[0].shape)):
raise ValueError(
"Tried to concatenate arrays with unknown"
f" shape {seq2[0].shape}.\n\nTwo solutions:\n"
" 1. Force concatenation pass"
" allow_unknown_chunksizes=True.\n"
" 2. Compute shapes with "
"[x.compute_chunk_sizes() for x in seq]"
)
raise ValueError("Shapes do not align: %s", [x.shape for x in seq2])
inds = [list(range(ndim)) for i in range(n)]
for i, ind in enumerate(inds):
ind[axis] = -(i + 1)
uc_args = list(concat(zip(seq2, inds)))
_, seq2 = unify_chunks(*uc_args, warn=False)
bds = [a.chunks for a in seq2]
chunks = (
seq2[0].chunks[:axis]
+ (sum((bd[axis] for bd in bds), ()),)
+ seq2[0].chunks[axis + 1 :]
)
cum_dims = [0] + list(accumulate(add, [len(a.chunks[axis]) for a in seq2]))
names = [a.name for a in seq2]
name = "concatenate-" + tokenize(names, axis)
keys = list(product([name], *[range(len(bd)) for bd in chunks]))
values = [
(names[bisect(cum_dims, key[axis + 1]) - 1],)
+ key[1 : axis + 1]
+ (key[axis + 1] - cum_dims[bisect(cum_dims, key[axis + 1]) - 1],)
+ key[axis + 2 :]
for key in keys
]
dsk = dict(zip(keys, values))
graph = HighLevelGraph.from_collections(name, dsk, dependencies=seq2)
return Array(graph, name, chunks, meta=meta)
def load_store_chunk(
x: Any,
out: Any,
index: slice | None,
region: slice | None,
lock: Any,
return_stored: bool,
load_stored: bool,
) -> Any:
"""
A function inserted in a Dask graph for storing a chunk.
Parameters
----------
x: array-like
An array (potentially a NumPy one)
out: array-like
Where to store results.
index: slice-like
Where to store result from ``x`` in ``out``.
lock: Lock-like or False
Lock to use before writing to ``out``.
return_stored: bool
Whether to return ``out``.
load_stored: bool
Whether to return the array stored in ``out``.
Ignored if ``return_stored`` is not ``True``.
Returns
-------
If return_stored=True and load_stored=False
out
If return_stored=True and load_stored=True
out[index]
If return_stored=False and compute=False
None
Examples
--------
>>> a = np.ones((5, 6))
>>> b = np.empty(a.shape)
>>> load_store_chunk(a, b, (slice(None), slice(None)), None, False, False, False)
"""
if region:
# Equivalent to `out[region][index]`
if index:
index = fuse_slice(region, index)
else:
index = region
if lock:
lock.acquire()
try:
if x is not None and x.size != 0:
if is_arraylike(x):
out[index] = x
else:
out[index] = np.asanyarray(x)
if return_stored and load_stored:
return out[index]
elif return_stored and not load_stored:
return out
else:
return None
finally:
if lock:
lock.release()
A = TypeVar("A", bound=ArrayLike)
def load_chunk(out: A, index: slice, lock: Any, region: slice | None) -> A:
return load_store_chunk(
None,
out=out,
region=region,
index=index,
lock=lock,
return_stored=True,
load_stored=True,
)
def _as_dtype(a, dtype):
if dtype is None:
return a
else:
return a.astype(dtype)
def asarray(
a, allow_unknown_chunksizes=False, dtype=None, order=None, *, like=None, **kwargs
):
"""Convert the input to a dask array.
Parameters
----------
a : array-like
Input data, in any form that can be converted to a dask array. This
includes lists, lists of tuples, tuples, tuples of tuples, tuples of
lists and ndarrays.
allow_unknown_chunksizes: bool
Allow unknown chunksizes, such as come from converting from dask
dataframes. Dask.array is unable to verify that chunks line up. If
data comes from differently aligned sources then this can cause
unexpected results.
dtype : data-type, optional
By default, the data-type is inferred from the input data.
order : {‘C’, ‘F’, ‘A’, ‘K’}, optional
Memory layout. ‘A’ and ‘K’ depend on the order of input array a.
‘C’ row-major (C-style), ‘F’ column-major (Fortran-style) memory
representation. ‘A’ (any) means ‘F’ if a is Fortran contiguous, ‘C’
otherwise ‘K’ (keep) preserve input order. Defaults to ‘C’.
like: array-like
Reference object to allow the creation of Dask arrays with chunks
that are not NumPy arrays. If an array-like passed in as ``like``
supports the ``__array_function__`` protocol, the chunk type of the
resulting array will be defined by it. In this case, it ensures the
creation of a Dask array compatible with that passed in via this
argument. If ``like`` is a Dask array, the chunk type of the
resulting array will be defined by the chunk type of ``like``.
Requires NumPy 1.20.0 or higher.
Returns
-------
out : dask array
Dask array interpretation of a.
Examples
--------
>>> import dask.array as da
>>> import numpy as np
>>> x = np.arange(3)
>>> da.asarray(x)
dask.array<array, shape=(3,), dtype=int64, chunksize=(3,), chunktype=numpy.ndarray>
>>> y = [[1, 2, 3], [4, 5, 6]]
>>> da.asarray(y)
dask.array<array, shape=(2, 3), dtype=int64, chunksize=(2, 3), chunktype=numpy.ndarray>
.. warning::
`order` is ignored if `a` is an `Array`, has the attribute ``to_dask_array``,
or is a list or tuple of `Array`'s.
"""
if like is None:
if isinstance(a, Array):
return _as_dtype(a, dtype)
elif hasattr(a, "to_dask_array"):
return _as_dtype(a.to_dask_array(), dtype)
elif type(a).__module__.split(".")[0] == "xarray" and hasattr(a, "data"):
return _as_dtype(asarray(a.data, order=order), dtype)
elif isinstance(a, (list, tuple)) and any(isinstance(i, Array) for i in a):
return _as_dtype(
stack(a, allow_unknown_chunksizes=allow_unknown_chunksizes), dtype
)
elif not isinstance(getattr(a, "shape", None), Iterable):
a = np.asarray(a, dtype=dtype, order=order)
else:
like_meta = meta_from_array(like)
if isinstance(a, Array):
return a.map_blocks(
# Pass the dtype parameter to np.asarray, not to map_blocks
partial(asarray_safe, like=like_meta, dtype=dtype, order=order)
)
else:
a = asarray_safe(a, like=like_meta, dtype=dtype, order=order)
a = from_array(a, getitem=getter_inline, **kwargs)
return _as_dtype(a, dtype)
def asanyarray(a, dtype=None, order=None, *, like=None, inline_array=False):
"""Convert the input to a dask array.
Subclasses of ``np.ndarray`` will be passed through as chunks unchanged.
Parameters
----------
a : array-like
Input data, in any form that can be converted to a dask array. This
includes lists, lists of tuples, tuples, tuples of tuples, tuples of
lists and ndarrays.
dtype : data-type, optional
By default, the data-type is inferred from the input data.
order : {‘C’, ‘F’, ‘A’, ‘K’}, optional
Memory layout. ‘A’ and ‘K’ depend on the order of input array a.
‘C’ row-major (C-style), ‘F’ column-major (Fortran-style) memory
representation. ‘A’ (any) means ‘F’ if a is Fortran contiguous, ‘C’
otherwise ‘K’ (keep) preserve input order. Defaults to ‘C’.
like: array-like
Reference object to allow the creation of Dask arrays with chunks
that are not NumPy arrays. If an array-like passed in as ``like``
supports the ``__array_function__`` protocol, the chunk type of the
resulting array will be defined by it. In this case, it ensures the
creation of a Dask array compatible with that passed in via this
argument. If ``like`` is a Dask array, the chunk type of the
resulting array will be defined by the chunk type of ``like``.
Requires NumPy 1.20.0 or higher.
inline_array:
Whether to inline the array in the resulting dask graph. For more information,
see the documentation for ``dask.array.from_array()``.
Returns
-------
out : dask array
Dask array interpretation of a.
Examples
--------
>>> import dask.array as da
>>> import numpy as np
>>> x = np.arange(3)
>>> da.asanyarray(x)
dask.array<array, shape=(3,), dtype=int64, chunksize=(3,), chunktype=numpy.ndarray>
>>> y = [[1, 2, 3], [4, 5, 6]]
>>> da.asanyarray(y)
dask.array<array, shape=(2, 3), dtype=int64, chunksize=(2, 3), chunktype=numpy.ndarray>
.. warning::
`order` is ignored if `a` is an `Array`, has the attribute ``to_dask_array``,
or is a list or tuple of `Array`'s.
"""
if like is None:
if isinstance(a, Array):
return _as_dtype(a, dtype)
elif hasattr(a, "to_dask_array"):
return _as_dtype(a.to_dask_array(), dtype)
elif type(a).__module__.split(".")[0] == "xarray" and hasattr(a, "data"):
return _as_dtype(asarray(a.data, order=order), dtype)
elif isinstance(a, (list, tuple)) and any(isinstance(i, Array) for i in a):
return _as_dtype(stack(a), dtype)
elif not isinstance(getattr(a, "shape", None), Iterable):
a = np.asanyarray(a, dtype=dtype, order=order)
else:
like_meta = meta_from_array(like)
if isinstance(a, Array):
return a.map_blocks(
# Pass the dtype parameter to np.asanyarray, not to map_blocks
partial(asanyarray_safe, like=like_meta, dtype=dtype, order=order)
)
else:
a = asanyarray_safe(a, like=like_meta, dtype=dtype, order=order)
a = from_array(
a,
chunks=a.shape,
getitem=getter_inline,
asarray=False,
inline_array=inline_array,
)
return _as_dtype(a, dtype)
def is_scalar_for_elemwise(arg):
"""
>>> is_scalar_for_elemwise(42)
True
>>> is_scalar_for_elemwise('foo')
True
>>> is_scalar_for_elemwise(True)
True
>>> is_scalar_for_elemwise(np.array(42))
True
>>> is_scalar_for_elemwise([1, 2, 3])
True
>>> is_scalar_for_elemwise(np.array([1, 2, 3]))
False
>>> is_scalar_for_elemwise(from_array(np.array(0), chunks=()))
False
>>> is_scalar_for_elemwise(np.dtype('i4'))
True
"""
# the second half of shape_condition is essentially just to ensure that
# dask series / frame are treated as scalars in elemwise.
maybe_shape = getattr(arg, "shape", None)
shape_condition = not isinstance(maybe_shape, Iterable) or any(
is_dask_collection(x) for x in maybe_shape
)
return (
np.isscalar(arg)
or shape_condition
or isinstance(arg, np.dtype)
or (isinstance(arg, np.ndarray) and arg.ndim == 0)
)
def broadcast_shapes(*shapes):
"""
Determines output shape from broadcasting arrays.
Parameters
----------
shapes : tuples
The shapes of the arguments.
Returns
-------
output_shape : tuple
Raises
------
ValueError
If the input shapes cannot be successfully broadcast together.
"""
if len(shapes) == 1:
return shapes[0]
out = []
for sizes in zip_longest(*map(reversed, shapes), fillvalue=-1):
if np.isnan(sizes).any():
dim = np.nan
else:
dim = 0 if 0 in sizes else np.max(sizes).item()
if any(i not in [-1, 0, 1, dim] and not np.isnan(i) for i in sizes):
raise ValueError(
"operands could not be broadcast together with "
"shapes {}".format(" ".join(map(str, shapes)))
)
out.append(dim)
return tuple(reversed(out))
def elemwise(op, *args, out=None, where=True, dtype=None, name=None, **kwargs):
"""Apply an elementwise ufunc-like function blockwise across arguments.
Like numpy ufuncs, broadcasting rules are respected.
Parameters
----------
op : callable
The function to apply. Should be numpy ufunc-like in the parameters
that it accepts.
*args : Any
Arguments to pass to `op`. Non-dask array-like objects are first
converted to dask arrays, then all arrays are broadcast together before
applying the function blockwise across all arguments. Any scalar
arguments are passed as-is following normal numpy ufunc behavior.
out : dask array, optional
If out is a dask.array then this overwrites the contents of that array
with the result.
where : array_like, optional
An optional boolean mask marking locations where the ufunc should be
applied. Can be a scalar, dask array, or any other array-like object.
Mirrors the ``where`` argument to numpy ufuncs, see e.g. ``numpy.add``
for more information.
dtype : dtype, optional
If provided, overrides the output array dtype.
name : str, optional
A unique key name to use when building the backing dask graph. If not
provided, one will be automatically generated based on the input
arguments.
Examples
--------
>>> elemwise(add, x, y) # doctest: +SKIP
>>> elemwise(sin, x) # doctest: +SKIP
>>> elemwise(sin, x, out=dask_array) # doctest: +SKIP
See Also
--------
blockwise
"""
if kwargs:
raise TypeError(
f"{op.__name__} does not take the following keyword arguments "
f"{sorted(kwargs)}"
)
out = _elemwise_normalize_out(out)
where = _elemwise_normalize_where(where)
args = [np.asarray(a) if isinstance(a, (list, tuple)) else a for a in args]
shapes = []
for arg in args:
shape = getattr(arg, "shape", ())
if any(is_dask_collection(x) for x in shape):
# Want to exclude Delayed shapes and dd.Scalar
shape = ()
shapes.append(shape)
if isinstance(where, Array):
shapes.append(where.shape)
if isinstance(out, Array):
shapes.append(out.shape)
shapes = [s if isinstance(s, Iterable) else () for s in shapes]
out_ndim = len(
broadcast_shapes(*shapes)
) # Raises ValueError if dimensions mismatch
expr_inds = tuple(range(out_ndim))[::-1]
if dtype is not None:
need_enforce_dtype = True
else:
# We follow NumPy's rules for dtype promotion, which special cases
# scalars and 0d ndarrays (which it considers equivalent) by using
# their values to compute the result dtype:
# https://github.com/numpy/numpy/issues/6240
# We don't inspect the values of 0d dask arrays, because these could
# hold potentially very expensive calculations. Instead, we treat
# them just like other arrays, and if necessary cast the result of op
# to match.
vals = [
(
np.empty((1,) * max(1, a.ndim), dtype=a.dtype)
if not is_scalar_for_elemwise(a)
else a
)
for a in args
]
try:
dtype = apply_infer_dtype(op, vals, {}, "elemwise", suggest_dtype=False)
except Exception:
return NotImplemented
need_enforce_dtype = any(
not is_scalar_for_elemwise(a) and a.ndim == 0 for a in args
)
if not name:
name = f"{funcname(op)}-{tokenize(op, dtype, *args, where)}"
blockwise_kwargs = dict(dtype=dtype, name=name, token=funcname(op).strip("_"))
if where is not True:
blockwise_kwargs["elemwise_where_function"] = op
op = _elemwise_handle_where
args.extend([where, out])
if need_enforce_dtype:
blockwise_kwargs["enforce_dtype"] = dtype
blockwise_kwargs["enforce_dtype_function"] = op
op = _enforce_dtype
result = blockwise(
op,
expr_inds,
*concat(
(a, tuple(range(a.ndim)[::-1]) if not is_scalar_for_elemwise(a) else None)
for a in args
),
**blockwise_kwargs,
)
return handle_out(out, result)
def _elemwise_normalize_where(where):
if where is True:
return True
elif where is False or where is None:
return False
return asarray(where)
def _elemwise_handle_where(*args, **kwargs):
function = kwargs.pop("elemwise_where_function")
*args, where, out = args
if hasattr(out, "copy"):
out = out.copy()
return function(*args, where=where, out=out, **kwargs)
def _elemwise_normalize_out(out):
if isinstance(out, tuple):
if len(out) == 1:
out = out[0]
elif len(out) > 1:
raise NotImplementedError("The out parameter is not fully supported")
else:
out = None
if not (out is None or isinstance(out, Array)):
raise NotImplementedError(
f"The out parameter is not fully supported."
f" Received type {type(out).__name__}, expected Dask Array"
)
return out
def handle_out(out, result):
"""Handle out parameters
If out is a dask.array then this overwrites the contents of that array with
the result
"""
out = _elemwise_normalize_out(out)
if isinstance(out, Array):
if out.shape != result.shape:
raise ValueError(
"Mismatched shapes between result and out parameter. "
f"out={out.shape}, result={result.shape}"
)
out._chunks = result.chunks
out.dask = result.dask
out._meta = result._meta
out._name = result.name
return out
else:
return result
def _enforce_dtype(*args, **kwargs):
"""Calls a function and converts its result to the given dtype.
The parameters have deliberately been given unwieldy names to avoid
clashes with keyword arguments consumed by blockwise
A dtype of `object` is treated as a special case and not enforced,
because it is used as a dummy value in some places when the result will
not be a block in an Array.
Parameters
----------
enforce_dtype : dtype
Result dtype
enforce_dtype_function : callable
The wrapped function, which will be passed the remaining arguments
"""
dtype = kwargs.pop("enforce_dtype")
function = kwargs.pop("enforce_dtype_function")
result = function(*args, **kwargs)
if hasattr(result, "dtype") and dtype != result.dtype and dtype != object:
if not np.can_cast(result, dtype, casting="same_kind"):
raise ValueError(
f"Inferred dtype from function {funcname(function)!r} was {str(dtype)!r} "
f"but got {str(result.dtype)!r}, which can't be cast using "
"casting='same_kind'"
)
if np.isscalar(result):
# scalar astype method doesn't take the keyword arguments, so
# have to convert via 0-dimensional array and back.
result = result.astype(dtype)
else:
try:
result = result.astype(dtype, copy=False)
except TypeError:
# Missing copy kwarg
result = result.astype(dtype)
return result
def broadcast_to(x, shape, chunks=None, meta=None):
"""Broadcast an array to a new shape.
Parameters
----------
x : array_like
The array to broadcast.
shape : tuple
The shape of the desired array.
chunks : tuple, optional
If provided, then the result will use these chunks instead of the same
chunks as the source array. Setting chunks explicitly as part of
broadcast_to is more efficient than rechunking afterwards. Chunks are
only allowed to differ from the original shape along dimensions that
are new on the result or have size 1 the input array.
meta : empty ndarray
empty ndarray created with same NumPy backend, ndim and dtype as the
Dask Array being created (overrides dtype)
Returns
-------
broadcast : dask array
See Also
--------
:func:`numpy.broadcast_to`
"""
x = asarray(x)
shape = tuple(shape)
if meta is None:
meta = meta_from_array(x)
if x.shape == shape and (chunks is None or chunks == x.chunks):
return x
ndim_new = len(shape) - x.ndim
if ndim_new < 0 or any(
new != old for new, old in zip(shape[ndim_new:], x.shape) if old != 1
):
raise ValueError(f"cannot broadcast shape {x.shape} to shape {shape}")
if chunks is None:
chunks = tuple((s,) for s in shape[:ndim_new]) + tuple(
bd if old > 1 else (new,)
for bd, old, new in zip(x.chunks, x.shape, shape[ndim_new:])
)
else:
chunks = normalize_chunks(
chunks, shape, dtype=x.dtype, previous_chunks=x.chunks
)
for old_bd, new_bd in zip(x.chunks, chunks[ndim_new:]):
if old_bd != new_bd and old_bd != (1,):
raise ValueError(
f"cannot broadcast chunks {x.chunks} to chunks {chunks}: "
"new chunks must either be along a new "
"dimension or a dimension of size 1"
)
name = "broadcast_to-" + tokenize(x, shape, chunks)
dsk = {}
enumerated_chunks = product(*(enumerate(bds) for bds in chunks))
for new_index, chunk_shape in (zip(*ec) for ec in enumerated_chunks):
old_index = tuple(
0 if bd == (1,) else i for bd, i in zip(x.chunks, new_index[ndim_new:])
)
old_key = (x.name,) + old_index
new_key = (name,) + new_index
dsk[new_key] = (np.broadcast_to, old_key, quote(chunk_shape))
graph = HighLevelGraph.from_collections(name, dsk, dependencies=[x])
return Array(graph, name, chunks, dtype=x.dtype, meta=meta)
@derived_from(np)
def broadcast_arrays(*args, subok=False):
subok = bool(subok)
to_array = asanyarray if subok else asarray
args = tuple(to_array(e) for e in args)
# Unify uneven chunking
inds = [list(reversed(range(x.ndim))) for x in args]
uc_args = concat(zip(args, inds))
_, args = unify_chunks(*uc_args, warn=False)
shape = broadcast_shapes(*(e.shape for e in args))
chunks = broadcast_chunks(*(e.chunks for e in args))
if NUMPY_GE_200:
result = tuple(broadcast_to(e, shape=shape, chunks=chunks) for e in args)
else:
result = [broadcast_to(e, shape=shape, chunks=chunks) for e in args]
return result
def offset_func(func, offset, *args):
"""Offsets inputs by offset
>>> double = lambda x: x * 2
>>> f = offset_func(double, (10,))
>>> f(1)
22
>>> f(300)
620
"""
def _offset(*args):
args2 = list(map(add, args, offset))
return func(*args2)
with contextlib.suppress(Exception):
_offset.__name__ = f"offset_{func.__name__}"
return _offset
def chunks_from_arrays(arrays):
"""Chunks tuple from nested list of arrays
>>> x = np.array([1, 2])
>>> chunks_from_arrays([x, x])
((2, 2),)
>>> x = np.array([[1, 2]])
>>> chunks_from_arrays([[x], [x]])
((1, 1), (2,))
>>> x = np.array([[1, 2]])
>>> chunks_from_arrays([[x, x]])
((1,), (2, 2))
>>> chunks_from_arrays([1, 1])
((1, 1),)
"""
if not arrays:
return ()
result = []
dim = 0
def shape(x):
try:
return x.shape if x.shape else (1,)
except AttributeError:
return (1,)
while isinstance(arrays, (list, tuple)):
result.append(tuple(shape(deepfirst(a))[dim] for a in arrays))
arrays = arrays[0]
dim += 1
return tuple(result)
def deepfirst(seq):
"""First element in a nested list
>>> deepfirst([[[1, 2], [3, 4]], [5, 6], [7, 8]])
1
"""
if not isinstance(seq, (list, tuple)):
return seq
else:
return deepfirst(seq[0])
def shapelist(a):
"""Get the shape of nested list"""
if type(a) is list:
return tuple([len(a)] + list(shapelist(a[0])))
else:
return ()
def transposelist(arrays, axes, extradims=0):
"""Permute axes of nested list
>>> transposelist([[1,1,1],[1,1,1]], [2,1])
[[[1, 1], [1, 1], [1, 1]]]
>>> transposelist([[1,1,1],[1,1,1]], [2,1], extradims=1)
[[[[1], [1]], [[1], [1]], [[1], [1]]]]
"""
if len(axes) != ndimlist(arrays):
raise ValueError("Length of axes should equal depth of nested arrays")
if extradims < 0:
raise ValueError("`newdims` should be positive")
if len(axes) > len(set(axes)):
raise ValueError("`axes` should be unique")
ndim = max(axes) + 1
shape = shapelist(arrays)
newshape = [
shape[axes.index(i)] if i in axes else 1 for i in range(ndim + extradims)
]
result = list(core.flatten(arrays))
return reshapelist(newshape, result)
def stack(seq, axis=0, allow_unknown_chunksizes=False):
"""
Stack arrays along a new axis
Given a sequence of dask arrays, form a new dask array by stacking them
along a new dimension (axis=0 by default)
Parameters
----------
seq: list of dask.arrays
axis: int
Dimension along which to align all of the arrays
allow_unknown_chunksizes: bool
Allow unknown chunksizes, such as come from converting from dask
dataframes. Dask.array is unable to verify that chunks line up. If
data comes from differently aligned sources then this can cause
unexpected results.
Examples
--------
Create slices
>>> import dask.array as da
>>> import numpy as np
>>> data = [da.from_array(np.ones((4, 4)), chunks=(2, 2))
... for i in range(3)]
>>> x = da.stack(data, axis=0)
>>> x.shape
(3, 4, 4)
>>> da.stack(data, axis=1).shape
(4, 3, 4)
>>> da.stack(data, axis=-1).shape
(4, 4, 3)
Result is a new dask Array
See Also
--------
concatenate
"""
from dask.array import wrap
seq = [asarray(a, allow_unknown_chunksizes=allow_unknown_chunksizes) for a in seq]
if not seq:
raise ValueError("Need array(s) to stack")
if not allow_unknown_chunksizes and not all(x.shape == seq[0].shape for x in seq):
idx = first(i for i in enumerate(seq) if i[1].shape != seq[0].shape)
raise ValueError(
"Stacked arrays must have the same shape. The first array had shape "
f"{seq[0].shape}, while array {idx[0] + 1} has shape {idx[1].shape}."
)
meta = np.stack([meta_from_array(a) for a in seq], axis=axis)
seq = [x.astype(meta.dtype) for x in seq]
ndim = meta.ndim - 1
if axis < 0:
axis = ndim + axis + 1
shape = tuple(
(
len(seq)
if i == axis
else (seq[0].shape[i] if i < axis else seq[0].shape[i - 1])
)
for i in range(meta.ndim)
)
seq2 = [a for a in seq if a.size]
if not seq2:
seq2 = seq
n = len(seq2)
if n == 0:
try:
return wrap.empty_like(meta, shape=shape, chunks=shape, dtype=meta.dtype)
except TypeError:
return wrap.empty(shape, chunks=shape, dtype=meta.dtype)
ind = list(range(ndim))
uc_args = list(concat((x, ind) for x in seq2))
_, seq2 = unify_chunks(*uc_args)
assert len({a.chunks for a in seq2}) == 1 # same chunks
chunks = seq2[0].chunks[:axis] + ((1,) * n,) + seq2[0].chunks[axis:]
names = [a.name for a in seq2]
name = "stack-" + tokenize(names, axis)
keys = list(product([name], *[range(len(bd)) for bd in chunks]))
inputs = [
(names[key[axis + 1]],) + key[1 : axis + 1] + key[axis + 2 :] for key in keys
]
values = [
(
getitem,
inp,
(slice(None, None, None),) * axis
+ (None,)
+ (slice(None, None, None),) * (ndim - axis),
)
for inp in inputs
]
layer = dict(zip(keys, values))
graph = HighLevelGraph.from_collections(name, layer, dependencies=seq2)
return Array(graph, name, chunks, meta=meta)
def concatenate_shaped(arrays, shape):
shaped = reshapelist(shape, arrays)
return concatenate3(shaped)
def concatenate3(arrays):
"""Recursive np.concatenate
Input should be a nested list of numpy arrays arranged in the order they
should appear in the array itself. Each array should have the same number
of dimensions as the desired output and the nesting of the lists.
>>> x = np.array([[1, 2]])
>>> concatenate3([[x, x, x], [x, x, x]])
array([[1, 2, 1, 2, 1, 2],
[1, 2, 1, 2, 1, 2]])
>>> concatenate3([[x, x], [x, x], [x, x]])
array([[1, 2, 1, 2],
[1, 2, 1, 2],
[1, 2, 1, 2]])
"""
# We need this as __array_function__ may not exist on older NumPy versions.
# And to reduce verbosity.
NDARRAY_ARRAY_FUNCTION = getattr(np.ndarray, "__array_function__", None)
arrays = concrete(arrays)
if not arrays or all(el is None for el in flatten(arrays)):
return np.empty(0)
advanced = max(
core.flatten(arrays, container=(list, tuple)),
key=lambda x: getattr(x, "__array_priority__", 0),
)
if not all(
NDARRAY_ARRAY_FUNCTION
is getattr(type(arr), "__array_function__", NDARRAY_ARRAY_FUNCTION)
for arr in core.flatten(arrays, container=(list, tuple))
):
try:
x = unpack_singleton(arrays)
return _concatenate2(arrays, axes=tuple(range(x.ndim)))
except TypeError:
pass
if concatenate_lookup.dispatch(type(advanced)) is not np.concatenate:
x = unpack_singleton(arrays)
return _concatenate2(arrays, axes=list(range(x.ndim)))
ndim = ndimlist(arrays)
if not ndim:
return arrays
chunks = chunks_from_arrays(arrays)
shape = tuple(map(sum, chunks))
def dtype(x):
try:
return x.dtype
except AttributeError:
return type(x)
result = np.empty(shape=shape, dtype=dtype(deepfirst(arrays)))
for idx, arr in zip(
slices_from_chunks(chunks), core.flatten(arrays, container=(list, tuple))
):
if hasattr(arr, "ndim"):
while arr.ndim < ndim:
arr = arr[None, ...]
result[idx] = arr
return result
def concatenate_axes(arrays, axes):
"""Recursively call np.concatenate along axes"""
if len(axes) != ndimlist(arrays):
raise ValueError("Length of axes should equal depth of nested arrays")
extradims = max(0, deepfirst(arrays).ndim - (max(axes) + 1))
return concatenate3(transposelist(arrays, axes, extradims=extradims))
def to_hdf5(filename, *args, chunks=True, **kwargs):
"""Store arrays in HDF5 file
This saves several dask arrays into several datapaths in an HDF5 file.
It creates the necessary datasets and handles clean file opening/closing.
Parameters
----------
chunks: tuple or ``True``
Chunk shape, or ``True`` to pass the chunks from the dask array.
Defaults to ``True``.
Examples
--------
>>> da.to_hdf5('myfile.hdf5', '/x', x) # doctest: +SKIP
or
>>> da.to_hdf5('myfile.hdf5', {'/x': x, '/y': y}) # doctest: +SKIP
Optionally provide arguments as though to ``h5py.File.create_dataset``
>>> da.to_hdf5('myfile.hdf5', '/x', x, compression='lzf', shuffle=True) # doctest: +SKIP
>>> da.to_hdf5('myfile.hdf5', '/x', x, chunks=(10,20,30)) # doctest: +SKIP
This can also be used as a method on a single Array
>>> x.to_hdf5('myfile.hdf5', '/x') # doctest: +SKIP
See Also
--------
da.store
h5py.File.create_dataset
"""
if len(args) == 1 and isinstance(args[0], dict):
data = args[0]
elif len(args) == 2 and isinstance(args[0], str) and isinstance(args[1], Array):
data = {args[0]: args[1]}
else:
raise ValueError("Please provide {'/data/path': array} dictionary")
import h5py
with h5py.File(filename, mode="a") as f:
dsets = [
f.require_dataset(
dp,
shape=x.shape,
dtype=x.dtype,
chunks=tuple(c[0] for c in x.chunks) if chunks is True else chunks,
**kwargs,
)
for dp, x in data.items()
]
store(list(data.values()), dsets)
def interleave_none(a, b):
"""
>>> interleave_none([0, None, 2, None], [1, 3])
(0, 1, 2, 3)
"""
result = []
i = j = 0
n = len(a) + len(b)
while i + j < n:
if a[i] is not None:
result.append(a[i])
i += 1
else:
result.append(b[j])
i += 1
j += 1
return tuple(result)
def keyname(name, i, okey):
"""
>>> keyname('x', 3, [None, None, 0, 2])
('x', 3, 0, 2)
"""
return (name, i) + tuple(k for k in okey if k is not None)
def _vindex(x, *indexes):
"""Point wise indexing with broadcasting.
>>> x = np.arange(56).reshape((7, 8))
>>> x
array([[ 0, 1, 2, 3, 4, 5, 6, 7],
[ 8, 9, 10, 11, 12, 13, 14, 15],
[16, 17, 18, 19, 20, 21, 22, 23],
[24, 25, 26, 27, 28, 29, 30, 31],
[32, 33, 34, 35, 36, 37, 38, 39],
[40, 41, 42, 43, 44, 45, 46, 47],
[48, 49, 50, 51, 52, 53, 54, 55]])
>>> d = from_array(x, chunks=(3, 4))
>>> result = _vindex(d, [0, 1, 6, 0], [0, 1, 0, 7])
>>> result.compute()
array([ 0, 9, 48, 7])
"""
indexes = replace_ellipsis(x.ndim, indexes)
nonfancy_indexes = []
reduced_indexes = []
for ind in indexes:
if isinstance(ind, Number):
nonfancy_indexes.append(ind)
elif isinstance(ind, slice):
nonfancy_indexes.append(ind)
reduced_indexes.append(slice(None))
else:
nonfancy_indexes.append(slice(None))
reduced_indexes.append(ind)
nonfancy_indexes = tuple(nonfancy_indexes)
reduced_indexes = tuple(reduced_indexes)
x = x[nonfancy_indexes]
array_indexes = {}
for i, (ind, size) in enumerate(zip(reduced_indexes, x.shape)):
if not isinstance(ind, slice):
ind = np.array(ind, copy=True)
if ind.dtype.kind == "b":
raise IndexError("vindex does not support indexing with boolean arrays")
if ((ind >= size) | (ind < -size)).any():
raise IndexError(
"vindex key has entries out of bounds for "
f"indexing along axis {i} of size {size}: {ind!r}"
)
ind %= size
array_indexes[i] = ind
if array_indexes:
x = _vindex_array(x, array_indexes)
return x
def _vindex_array(x, dict_indexes):
"""Point wise indexing with only NumPy Arrays."""
token = tokenize(x, dict_indexes)
try:
broadcast_shape = np.broadcast_shapes(
*(arr.shape for arr in dict_indexes.values())
)
except ValueError as e:
# note: error message exactly matches numpy
shapes_str = " ".join(str(a.shape) for a in dict_indexes.values())
raise IndexError(
"shape mismatch: indexing arrays could not be "
f"broadcast together with shapes {shapes_str}"
) from e
npoints = math.prod(broadcast_shape)
axes = [i for i in range(x.ndim) if i in dict_indexes]
def _subset_to_indexed_axes(iterable):
for i, elem in enumerate(iterable):
if i in axes:
yield elem
bounds2 = tuple(
np.array(cached_cumsum(c, initial_zero=True))
for c in _subset_to_indexed_axes(x.chunks)
)
axis = _get_axis(tuple(i if i in axes else None for i in range(x.ndim)))
out_name = "vindex-merge-" + token
# Now compute indices of each output element within each input block
# The index is relative to the block, not the array.
block_idxs = tuple(
np.searchsorted(b, ind, side="right") - 1
for b, ind in zip(bounds2, dict_indexes.values())
)
starts = (b[i] for i, b in zip(block_idxs, bounds2))
inblock_idxs = []
for idx, start in zip(dict_indexes.values(), starts):
a = idx - start
if len(a) > 0:
dtype = np.min_scalar_type(np.max(a, axis=None))
inblock_idxs.append(a.astype(dtype, copy=False))
else:
inblock_idxs.append(a)
inblock_idxs = np.broadcast_arrays(*inblock_idxs)
chunks = [c for i, c in enumerate(x.chunks) if i not in axes]
# determine number of points in one single output block.
# Use the input chunk size to determine this.
max_chunk_point_dimensions = reduce(
mul, map(cached_max, _subset_to_indexed_axes(x.chunks))
)
n_chunks, remainder = divmod(npoints, max_chunk_point_dimensions)
chunks.insert(
0,
(
(max_chunk_point_dimensions,) * n_chunks
+ ((remainder,) if remainder > 0 else ())
if npoints > 0
else (0,)
),
)
chunks = tuple(chunks)
if npoints > 0:
other_blocks = product(
*[
range(len(c)) if i not in axes else [None]
for i, c in enumerate(x.chunks)
]
)
full_slices = [
slice(None, None) if i not in axes else None for i in range(x.ndim)
]
# The output is constructed as a new dimension and then reshaped
# So the index of the output point is simply an `arange`
outinds = np.arange(npoints).reshape(broadcast_shape)
# Which output block is the point going to, and what is the index within that block?
outblocks, outblock_idx = np.divmod(outinds, max_chunk_point_dimensions)
# Now we try to be clever. We need to construct a graph where
# if input chunk (0,0) contributes to output chunks 0 and 2 then
# (0,0) => (0, 0, 0) and (2, 0, 0).
# The following is a groupby over output key by using ravel_multi_index to convert
# the (output_block, *input_block) tuple to a unique code.
ravel_shape = (n_chunks + 1, *_subset_to_indexed_axes(x.numblocks))
keys = np.ravel_multi_index([outblocks, *block_idxs], ravel_shape)
# by sorting the data that needs to be inserted in the graph here,
# we can slice in the hot loop below instead of using fancy indexing which will
# always copy inside the hot loop.
sortidx = np.argsort(keys, axis=None)
sorted_keys = keys.flat[sortidx] # flattens
sorted_inblock_idxs = [_.flat[sortidx] for _ in inblock_idxs]
sorted_outblock_idx = outblock_idx.flat[sortidx]
dtype = np.min_scalar_type(max_chunk_point_dimensions)
sorted_outblock_idx = sorted_outblock_idx.astype(dtype, copy=False)
# Determine the start and end of each unique key. We will loop over this
flag = np.concatenate([[True], sorted_keys[1:] != sorted_keys[:-1], [True]])
(key_bounds,) = flag.nonzero()
name = "vindex-slice-" + token
vindex_merge_name = "vindex-merge-" + token
dsk = {}
for okey in other_blocks:
merge_inputs = defaultdict(list)
merge_indexer = defaultdict(list)
for i, (start, stop) in enumerate(
zip(key_bounds[:-1], key_bounds[1:], strict=True)
):
slicer = slice(start, stop)
key = sorted_keys[start]
outblock, *input_blocks = np.unravel_index(key, ravel_shape)
inblock = [_[slicer] for _ in sorted_inblock_idxs]
k = keyname(name, i, okey)
dsk[k] = Task(
k,
_vindex_slice_and_transpose,
TaskRef((x.name,) + interleave_none(okey, input_blocks)),
interleave_none(full_slices, inblock),
axis,
)
merge_inputs[outblock].append(TaskRef(keyname(name, i, okey)))
merge_indexer[outblock].append(sorted_outblock_idx[slicer])
for i in merge_inputs.keys():
k = keyname(vindex_merge_name, i, okey)
dsk[k] = Task(
k,
_vindex_merge,
merge_indexer[i],
List(merge_inputs[i]),
)
result_1d = Array(
HighLevelGraph.from_collections(out_name, dsk, dependencies=[x]),
out_name,
chunks,
x.dtype,
meta=x._meta,
)
return result_1d.reshape(broadcast_shape + result_1d.shape[1:])
# output has a zero dimension, just create a new zero-shape array with the
# same dtype
from dask.array.wrap import empty
result_1d = empty(
tuple(map(sum, chunks)), chunks=chunks, dtype=x.dtype, name=out_name
)
return result_1d.reshape(broadcast_shape + result_1d.shape[1:])
def _get_axis(indexes):
"""Get axis along which point-wise slicing results lie
This is mostly a hack because I can't figure out NumPy's rule on this and
can't be bothered to go reading.
>>> _get_axis([[1, 2], None, [1, 2], None])
0
>>> _get_axis([None, [1, 2], [1, 2], None])
1
>>> _get_axis([None, None, [1, 2], [1, 2]])
2
"""
ndim = len(indexes)
indexes = [slice(None, None) if i is None else [0] for i in indexes]
x = np.empty((2,) * ndim)
x2 = x[tuple(indexes)]
return x2.shape.index(1)
def _vindex_slice_and_transpose(block, points, axis):
"""Pull out point-wise slices from block and rotate block so that
points are on the first dimension"""
points = [p if isinstance(p, slice) else list(p) for p in points]
block = block[tuple(points)]
axes = [axis] + list(range(axis)) + list(range(axis + 1, block.ndim))
return block.transpose(axes)
def _vindex_merge(locations, values):
"""
>>> locations = [0], [2, 1]
>>> values = [np.array([[1, 2, 3]]),
... np.array([[10, 20, 30], [40, 50, 60]])]
>>> _vindex_merge(locations, values)
array([[ 1, 2, 3],
[40, 50, 60],
[10, 20, 30]])
"""
locations = list(map(list, locations))
values = list(values)
n = sum(map(len, locations))
shape = list(values[0].shape)
shape[0] = n
shape = tuple(shape)
dtype = values[0].dtype
x = np.empty_like(values[0], dtype=dtype, shape=shape)
ind = [slice(None, None) for i in range(x.ndim)]
for loc, val in zip(locations, values):
ind[0] = loc
x[tuple(ind)] = val
return x
def to_npy_stack(dirname, x, axis=0):
"""Write dask array to a stack of .npy files
This partitions the dask.array along one axis and stores each block along
that axis as a single .npy file in the specified directory
Examples
--------
>>> x = da.ones((5, 10, 10), chunks=(2, 4, 4)) # doctest: +SKIP
>>> da.to_npy_stack('data/', x, axis=0) # doctest: +SKIP
The ``.npy`` files store numpy arrays for ``x[0:2], x[2:4], and x[4:5]``
respectively, as is specified by the chunk size along the zeroth axis::
$ tree data/
data/
|-- 0.npy
|-- 1.npy
|-- 2.npy
|-- info
The ``info`` file stores the dtype, chunks, and axis information of the array.
You can load these stacks with the :func:`dask.array.from_npy_stack` function.
>>> y = da.from_npy_stack('data/') # doctest: +SKIP
See Also
--------
from_npy_stack
"""
chunks = tuple((c if i == axis else (sum(c),)) for i, c in enumerate(x.chunks))
xx = x.rechunk(chunks)
if not os.path.exists(dirname):
os.mkdir(dirname)
meta = {"chunks": chunks, "dtype": x.dtype, "axis": axis}
with open(os.path.join(dirname, "info"), "wb") as f:
pickle.dump(meta, f)
name = f"to-npy-stack-{uuid.uuid1()}"
dsk = {
(name, i): (np.save, os.path.join(dirname, f"{i}.npy"), key)
for i, key in enumerate(core.flatten(xx.__dask_keys__()))
}
graph = HighLevelGraph.from_collections(name, dsk, dependencies=[xx])
compute_as_if_collection(Array, graph, list(dsk))
def from_npy_stack(dirname, mmap_mode="r"):
"""Load dask array from stack of npy files
Parameters
----------
dirname: string
Directory of .npy files
mmap_mode: (None or 'r')
Read data in memory map mode
See Also
--------
to_npy_stack
"""
with open(os.path.join(dirname, "info"), "rb") as f:
info = pickle.load(f)
dtype = info["dtype"]
chunks = info["chunks"]
axis = info["axis"]
name = f"from-npy-stack-{dirname}"
keys = list(product([name], *[range(len(c)) for c in chunks]))
values = [
(np.load, os.path.join(dirname, f"{i}.npy"), mmap_mode)
for i in range(len(chunks[axis]))
]
dsk = dict(zip(keys, values))
return Array(dsk, name, chunks, dtype)
def new_da_object(dsk, name, chunks, meta=None, dtype=None):
"""Generic constructor for dask.array or dask.dataframe objects.
Decides the appropriate output class based on the type of `meta` provided.
"""
if is_dataframe_like(meta) or is_series_like(meta) or is_index_like(meta):
from dask.dataframe import from_graph
assert all(len(c) == 1 for c in chunks[1:])
divisions = [None] * (len(chunks[0]) + 1)
return from_graph(dict(dsk), meta, divisions, dsk.layers[name].keys(), name)
else:
return Array(dsk, name=name, chunks=chunks, meta=meta, dtype=dtype)
| Array |
python | psf__black | src/black/rusty.py | {
"start": 251,
"end": 396
} | class ____(Generic[T]):
def __init__(self, value: T) -> None:
self._value = value
def ok(self) -> T:
return self._value
| Ok |
python | PrefectHQ__prefect | src/prefect/serializers.py | {
"start": 9512,
"end": 9789
} | class ____(CompressedSerializer[D]):
"""
A compressed serializer preconfigured to use the json serializer.
"""
type: str = Field(default="compressed/json", frozen=True)
serializer: Serializer[D] = Field(default_factory=JSONSerializer)
| CompressedJSONSerializer |
python | fluentpython__example-code-2e | 21-async/mojifinder/bottle.py | {
"start": 115734,
"end": 115952
} | class ____(ServerAdapter):
""" Untested. """
def run(self, handler):
from diesel.protocols.wsgi import WSGIApplication
app = WSGIApplication(handler, port=self.port)
app.run()
| DieselServer |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 55831,
"end": 56188
} | class ____(sgqlc.types.Input):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("subject_id", "client_mutation_id")
subject_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="subjectId")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
| AddUpvoteInput |
python | chroma-core__chroma | sample_apps/generative_benchmarking/functions/types.py | {
"start": 76,
"end": 156
} | class ____:
doc_relevances: Dict[str, Dict[str, int]]
@dataclass
| QueryRelevance |
python | kamyu104__LeetCode-Solutions | Python/find-the-key-of-the-numbers.py | {
"start": 43,
"end": 443
} | class ____(object):
def generateKey(self, num1, num2, num3):
"""
:type num1: int
:type num2: int
:type num3: int
:rtype: int
"""
L = 4
result = 0
base = pow(10, L-1)
for _ in xrange(L):
result = result*10+min(num1//base%10, num2//base%10, num3//base%10)
base //= 10
return result
| Solution |
python | pytorch__pytorch | test/distributed/checkpoint/test_state_dict_stager.py | {
"start": 7171,
"end": 7242
} | class ____:
tensor: torch.Tensor
value: int = 100
| FrozenDataClass |
python | pytorch__pytorch | torch/autograd/profiler.py | {
"start": 2556,
"end": 29580
} | class ____:
"""Context manager that manages autograd profiler state and holds a summary of results.
.. note::
This is the backend, most people should use :mod:`torch.profiler` instead.
Under the hood it just records events of functions being executed in C++ and
exposes those events to Python. You can wrap any code into it and it will
only report runtime of PyTorch functions.
Note: profiler is thread local and is automatically propagated into the async tasks
Args:
enabled (bool, optional): Setting this to False makes this context manager a no-op.
use_cuda (bool, optional): Enables timing of CUDA events as well
using the cudaEvent API. (will be deprecated)
use_device (str, optional): Enables timing of device events.
Adds approximately 4us of overhead to each tensor operation when use cuda.
The valid devices options are 'cuda', 'xpu', 'mtia' and 'privateuseone'.
record_shapes (bool, optional): If shapes recording is set, information
about input dimensions will be collected. This allows one to see which
dimensions have been used under the hood and further group by them
using prof.key_averages(group_by_input_shape=True). Please note that
shape recording might skew your profiling data. It is recommended to
use separate runs with and without shape recording to validate the timing.
Most likely the skew will be negligible for bottom most events (in a case
of nested function calls). But for higher level functions the total
self cpu time might be artificially increased because of the shape
collection.
with_flops (bool, optional): If with_flops is set, the profiler will estimate
the FLOPs (floating point operations) value using the operator's input shape.
This allows one to estimate the hardware performance. Currently,
this option only works for the matrix multiplication and 2D convolution operators.
profile_memory (bool, optional): track tensor memory allocation/deallocation.
with_stack (bool, optional): record source information (file and line number) for the ops.
with_modules (bool): record module hierarchy (including function names)
corresponding to the callstack of the op. e.g. If module A's forward call's
module B's forward which contains an aten::add op,
then aten::add's module hierarchy is A.B
Note that this support exist, at the moment, only for TorchScript models
and not eager mode models.
use_kineto (bool, optional): experimental, enable profiling with Kineto profiler.
use_cpu (bool, optional): profile CPU events; setting to ``False`` requires
``use_kineto=True`` and can be used to lower the overhead for GPU-only profiling.
experimental_config (_ExperimentalConfig) : A set of experimental options
used by profiler libraries like Kineto. Note, backward compatibility is not guaranteed.
acc_events (bool): Enable the accumulation of FunctionEvents across multiple profiling cycles
.. warning::
Enabling memory profiling or source attribution incurs additional profiler
overhead
.. warning::
This context managers should not be called recursively, i.e. no nested
instances are allowed
.. warning::
Due to some CUDA multiprocessing limitations (see :ref:`multiprocessing-cuda-note`),
one cannot use the profiler with ``use_device = 'cuda'`` to benchmark
DataLoaders with ``num_workers > 0``. If you wish to benchmark data loading,
please use ``use_device = None`` or ``num_workers = 0``.
Example:
>>> # xdoctest: +SKIP
>>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_AUTOGRAD_PROFILER)
>>> x = torch.randn((1, 1), requires_grad=True)
>>> with torch.autograd.profiler.profile() as prof:
>>> for _ in range(100): # any normal python code, really!
>>> y = x ** 2
>>> y.backward()
>>> # NOTE: some columns were removed for brevity
>>> print(prof.key_averages().table(sort_by="self_cpu_time_total"))
----------------------------------- --------------- --------------- ---------------
Name Self CPU total CPU time avg Number of Calls
----------------------------------- --------------- --------------- ---------------
mul 32.048ms 32.048ms 200
pow 27.041ms 27.041ms 200
PowBackward0 9.727ms 55.483ms 100
torch::autograd::AccumulateGrad 9.148ms 9.148ms 100
torch::autograd::GraphRoot 691.816us 691.816us 100
----------------------------------- --------------- --------------- ---------------
"""
def __init__(
self,
enabled=True,
*,
use_cuda=False, # Deprecated
use_device=None,
record_shapes=False,
with_flops=False,
profile_memory=False,
with_stack=False,
with_modules=False,
use_kineto=False,
use_cpu=True,
experimental_config=None,
acc_events=False,
custom_trace_id_callback=None,
):
self.enabled: bool = enabled
if not self.enabled:
return
self.use_cuda = use_cuda
if self.use_cuda:
warn(
"The attribute `use_cuda` will be deprecated soon, "
"please use ``use_device = 'cuda'`` instead.",
FutureWarning,
stacklevel=2,
)
self.use_device: Optional[str] = "cuda"
else:
self.use_device = use_device
# TODO Consider changing _function_events into data structure with size cap
self._function_events: Optional[EventList] = None
self._old_function_events: Optional[EventList] = None
# Function event processing is done lazily
self._needs_processing = False
self.entered = False
self.record_shapes = record_shapes
self.with_flops = with_flops
self.record_shapes |= self.with_flops
self.profile_memory = profile_memory
self.with_stack = with_stack
self.with_modules = with_modules
self.use_cpu = use_cpu
self.acc_events = acc_events
if experimental_config is None:
experimental_config = _ExperimentalConfig()
self.experimental_config = experimental_config
self.kineto_results: Optional[_ProfilerResult] = None
self.profiling_start_time_ns = 0
self.profiling_end_time_ns = 0
self._stats = _ProfilerStats()
self.custom_trace_id_callback = custom_trace_id_callback
self.trace_id = ""
if not self.use_cpu:
if not use_kineto:
raise AssertionError(
"Device-only events supported only with Kineto (use_kineto=True)"
)
if self.use_device is not None:
VALID_DEVICE_OPTIONS = ["cuda", "xpu", "mtia", "hpu"]
if _get_privateuse1_backend_name() != "privateuseone":
VALID_DEVICE_OPTIONS.append(_get_privateuse1_backend_name())
if self.use_device not in VALID_DEVICE_OPTIONS:
warn(
f"The {self.use_device} is not a valid device option.", stacklevel=2
)
self.use_device = None
if self.use_device == "cuda" and not torch.cuda.is_available():
warn("CUDA is not available, disabling CUDA profiling", stacklevel=2)
self.use_cuda = False
self.use_device = None
if self.use_device == "xpu" and not torch.xpu.is_available():
warn("XPU is not available, disabling XPU profiling", stacklevel=2)
self.use_device = None
if self.use_device == "hpu" and not (
hasattr(torch, "hpu") and torch.hpu.is_available()
):
warn("HPU is not available, disabling HPU profiling", stacklevel=2)
self.use_device = None
self.kineto_activities = set()
if self.use_cpu:
self.kineto_activities.add(ProfilerActivity.CPU)
self.profiler_kind = ProfilerState.KINETO
if self.use_device == "cuda":
if not use_kineto or ProfilerActivity.CUDA not in _supported_activities():
if not self.use_cpu:
raise AssertionError("Legacy CUDA profiling requires use_cpu=True")
self.profiler_kind = ProfilerState.KINETO_GPU_FALLBACK
else:
self.kineto_activities.add(ProfilerActivity.CUDA)
elif self.use_device == "xpu":
if not (use_kineto and ProfilerActivity.XPU in _supported_activities()):
raise AssertionError(
"Legacy XPU profiling is not supported. Requires use_kineto=True on XPU devices."
)
self.kineto_activities.add(ProfilerActivity.XPU)
elif self.use_device == "mtia":
if not (use_kineto and ProfilerActivity.MTIA in _supported_activities()):
raise AssertionError(
"Legacy MTIA profiling is not supported. Requires use_kineto=True on MTIA devices."
)
self.kineto_activities.add(ProfilerActivity.MTIA)
elif self.use_device == "hpu":
if not (use_kineto and ProfilerActivity.HPU in _supported_activities()):
raise AssertionError(
"Legacy HPU profiling is not supported. Requires use_kineto=True on HPU devices."
)
self.kineto_activities.add(ProfilerActivity.HPU)
elif self.use_device is not None and self.use_device != "privateuseone":
if (
not use_kineto
or ProfilerActivity.PrivateUse1 not in _supported_activities()
):
if not self.use_cpu:
raise AssertionError(
"Legacy custombackend profiling requires use_cpu=True"
)
self.profiler_kind = ProfilerState.KINETO_PRIVATEUSE1_FALLBACK
else:
self.kineto_activities.add(ProfilerActivity.PrivateUse1)
if len(self.kineto_activities) == 0:
raise AssertionError("No activities specified for the profiler")
def default_trace_id(self):
# Generate a UUID
uuid_raw = uuid.uuid4()
return f"{uuid_raw.int:032X}"
def create_trace_id(self):
if self.custom_trace_id_callback:
return self.custom_trace_id_callback()
return self.default_trace_id()
def config(self, create_trace_id=False):
# only need to generate new trace id upon prepare trace not start trace
if create_trace_id:
trace_id = self.create_trace_id()
self.trace_id = trace_id
return ProfilerConfig(
self.profiler_kind,
self.record_shapes,
self.profile_memory,
self.with_stack,
self.with_flops,
self.with_modules,
self.experimental_config,
self.trace_id,
)
def __enter__(self):
if not self.enabled:
return
if self.entered:
raise RuntimeError("Profiler context manager is not reentrant")
self._prepare_trace()
self._start_trace()
return self
def _prepare_trace(self):
self.entered = True
t0 = perf_counter_ns()
_prepare_profiler(self.config(create_trace_id=True), self.kineto_activities)
t1 = perf_counter_ns()
self._stats.profiler_prepare_call_duration_us = int((t1 - t0) / 1000)
def _start_trace(self):
self.entered = True
_run_on_profiler_start()
t0 = perf_counter_ns()
_enable_profiler(self.config(create_trace_id=False), self.kineto_activities)
t1 = perf_counter_ns()
self._stats.profiler_enable_call_duration_us = int((t1 - t0) / 1000)
self.profiling_start_time_ns = t1
def __exit__(self, exc_type, exc_val, exc_tb):
if not self.enabled:
return
if self.use_device and hasattr(torch, self.use_device):
device_module = getattr(torch, self.use_device)
if hasattr(device_module, "synchronize"):
device_module.synchronize()
if self._function_events and self.acc_events:
self._old_function_events = self._function_events
self._function_events = None
self._needs_processing = True
t0 = perf_counter_ns()
self.kineto_results = _disable_profiler()
t1 = perf_counter_ns()
self._stats.profiler_disable_call_duration_us = int((t1 - t0) / 1000)
self.profiling_end_time_ns = t0
_run_on_profiler_stop()
self._stats.profiling_window_duration_sec = (
(self.profiling_end_time_ns - self.profiling_start_time_ns) * 1.0 / 1e9
)
# If we plan to accumulate events we should post process the function events
# right away to retain the state across multiple start/stop calls
if self.acc_events:
self._ensure_function_events()
return False
def __repr__(self):
if self._needs_processing:
self._ensure_function_events()
if self._function_events is None:
return "<unfinished torch.autograd.profile>"
return repr(self._function_events)
def __str__(self):
if self._needs_processing:
self._ensure_function_events()
if self._function_events is None:
return "<unfinished torch.autograd.profile>"
return str(self._function_events)
def _ensure_function_events(self):
"""Process function events lazily if required"""
if self._function_events is not None:
return
self._needs_processing = False
t0 = perf_counter_ns()
parsed_results = []
if self.kineto_results:
parsed_results = self._parse_kineto_results(self.kineto_results)
t1 = perf_counter_ns()
self._stats.parse_kineto_call_duration_us = int((t1 - t0) / 1000)
self._function_events = EventList(
parsed_results,
use_device=self.use_device,
profile_memory=self.profile_memory,
with_flops=self.with_flops,
)
t0 = perf_counter_ns()
self._function_events._build_tree()
t1 = perf_counter_ns()
self._stats.function_events_build_tree_call_duration_us = int((t1 - t0) / 1000)
self._stats.number_of_events = len(self._function_events)
if self._old_function_events and self.acc_events:
for evt in self._old_function_events:
self._function_events.append(evt)
self._old_function_events = None
if self._function_events is None:
raise RuntimeError("Profiler didn't finish running")
@property
def function_events(self):
if self._function_events is None or self._needs_processing:
self._ensure_function_events()
return self._function_events
def table(
self,
sort_by=None,
row_limit=100,
max_src_column_width=75,
max_name_column_width=55,
max_shapes_column_width=80,
header=None,
top_level_events_only=False,
):
self._ensure_function_events()
if self._function_events is None:
raise AssertionError("Expected profiling results")
return self._function_events.table(
sort_by=sort_by,
row_limit=row_limit,
max_src_column_width=max_src_column_width,
max_name_column_width=max_name_column_width,
max_shapes_column_width=max_shapes_column_width,
header=header,
top_level_events_only=top_level_events_only,
)
table.__doc__ = EventList.table.__doc__
def export_chrome_trace(self, path):
"""
Exports the collected trace in Chrome JSON format. If kineto is enabled, only
last cycle in schedule is exported.
"""
if kineto_available():
self.kineto_results.save(path) # type: ignore[union-attr]
else:
self._ensure_function_events()
return self._function_events.export_chrome_trace(path) # type: ignore[union-attr]
export_chrome_trace.__doc__ = EventList.export_chrome_trace.__doc__
def export_stacks(self, path: str, metric: str = "self_cpu_time_total"):
self._ensure_function_events()
if self._function_events is None:
raise AssertionError("Expected profiling results")
if not self.with_stack:
raise AssertionError("export_stacks() requires with_stack=True")
return self._function_events.export_stacks(path, metric)
def toggle_collection_dynamic(
self, enabled: bool, activities: Iterable[ProfilerActivity]
):
"""
Toggles the collection of activities for the current profiler instance.
"""
return _toggle_collection_dynamic(enabled, set(activities))
def key_averages(
self,
group_by_input_shape=False,
group_by_stack_n=0,
group_by_overload_name=False,
):
self._ensure_function_events()
if self._function_events is None:
raise AssertionError("Expected profiling results")
return self._function_events.key_averages(
group_by_input_shape, group_by_stack_n, group_by_overload_name
)
key_averages.__doc__ = EventList.key_averages.__doc__
def total_average(self):
self._ensure_function_events()
if self._function_events is None:
raise AssertionError("Expected profiling results")
return self._function_events.total_average()
total_average.__doc__ = EventList.total_average.__doc__
@property
def self_cpu_time_total(self):
"""Returns total time spent on CPU.
The total time is a sum of all self times across all the events.
"""
self._ensure_function_events()
if self._function_events is None:
raise AssertionError("Expected profiling results")
return self._function_events.self_cpu_time_total
def _parse_kineto_results(self, result: _ProfilerResult):
# result.events() has most of the events - PyTorch op-level and device-level events
trace_start_ns = result.trace_start_ns()
mem_records = [
[evt, False] for evt in result.events() if evt.name() == MEMORY_EVENT_NAME
]
oom_records = [
evt for evt in result.events() if evt.name() == OUT_OF_MEMORY_EVENT_NAME
]
mem_records_acc = MemRecordsAcc(mem_records)
def _cpu_memory_usage(mem_record):
return (
mem_record.nbytes()
if mem_record.device_type()
in [DeviceType.CPU, DeviceType.MKLDNN, DeviceType.IDEEP]
else 0
)
def _device_memory_usage(mem_record):
return (
mem_record.nbytes()
if mem_record.device_type()
in [
DeviceType.CUDA,
DeviceType.PrivateUse1,
DeviceType.HIP,
DeviceType.XPU,
]
else 0
)
# Create and return FunctionEvent list, which contains all function events
# Here 2 function events are created:
# all_function_events contains all events associated with each kineto event from result
all_function_events = []
# frontend_function_events contains the events in aten or torch frontend level,
# whose correlation id is 0
frontend_function_events = []
device_corr_map: dict[int, list[FunctionEvent]] = {}
max_evt_id = 0
for kineto_event in result.events():
if (
_filter_name(kineto_event.name())
or getattr(kineto_event, "is_hidden_event", lambda: False)()
):
continue
rel_start_ns = kineto_event.start_ns() - trace_start_ns
rel_end_ns = kineto_event.end_ns() - trace_start_ns
abs_end_ns = kineto_event.end_ns()
cpu_memory_usage = 0
device_memory_usage = 0
if kineto_event.device_type() == DeviceType.CPU:
# find the corresponding memory allocation events
for mem_record in mem_records_acc.in_interval(
kineto_event.start_ns() / 1000, abs_end_ns / 1000
):
cpu_memory_usage += _cpu_memory_usage(mem_record[0])
device_memory_usage += _device_memory_usage(mem_record[0])
mem_record[1] = True
is_async = kineto_event.is_async() or (
kineto_event.start_thread_id() != kineto_event.end_thread_id()
)
fe = FunctionEvent(
id=kineto_event.correlation_id(),
name=_rewrite_name(name=kineto_event.name(), with_wildcard=True),
overload_name=kineto_event.overload_name(),
trace_name=_rewrite_name(name=kineto_event.name(), with_wildcard=False),
thread=kineto_event.start_thread_id(),
start_us=rel_start_ns / 1000,
end_us=rel_end_ns / 1000,
fwd_thread=kineto_event.fwd_thread_id(),
input_shapes=kineto_event.shapes(),
concrete_inputs=kineto_event.concrete_inputs(),
kwinputs=kineto_event.kwinputs(),
stack=[
entry
for entry in kineto_event.stack()
if _filter_stack_entry(entry)
],
scope=kineto_event.scope(),
use_device=self.use_device,
cpu_memory_usage=cpu_memory_usage,
device_memory_usage=device_memory_usage,
is_async=is_async,
sequence_nr=kineto_event.sequence_nr(),
device_type=kineto_event.device_type(),
device_index=kineto_event.device_index(),
device_resource_id=kineto_event.device_resource_id(),
flops=kineto_event.flops(),
is_user_annotation=kineto_event.is_user_annotation(),
metadata_json=kineto_event.metadata_json(),
)
max_evt_id = max(max_evt_id, fe.id)
if fe.device_type == DeviceType.CPU and not fe.is_async:
if self.use_device == _get_privateuse1_backend_name():
privateuse1_time = kineto_event.privateuse1_elapsed_us()
if privateuse1_time > 0:
fe.append_kernel(fe.name, fe.device_index, privateuse1_time)
fe.is_legacy = True
elif self.use_device == "cuda":
# Check if we have CUDA time as a fallback
cuda_time = kineto_event.cuda_elapsed_us()
if cuda_time > 0:
fe.append_kernel(fe.name, fe.device_index, cuda_time)
fe.is_legacy = True
all_function_events.append(fe)
corr_id = kineto_event.linked_correlation_id()
if corr_id > 0:
if corr_id not in device_corr_map:
device_corr_map[corr_id] = []
device_corr_map[corr_id].append(fe)
elif corr_id == 0:
frontend_function_events.append(fe)
else:
raise RuntimeError(
f"Got negative correlation id {corr_id} in profiler post processing"
)
# associate device kernels and device runtime (CPU) with CPU events
for fe in frontend_function_events:
if (
fe.device_type == DeviceType.CPU
and not fe.is_async
and fe.id in device_corr_map
):
for f_evt in device_corr_map[fe.id]:
if (
f_evt.device_type == DeviceType.CUDA
or f_evt.device_type == DeviceType.PrivateUse1
):
fe.append_kernel(
f_evt.name,
f_evt.device_index,
f_evt.time_range.end - f_evt.time_range.start,
)
elif f_evt.device_type == DeviceType.CPU:
# make sure that 'thread' of a CPU Kineto (e.g. Device Runtime) event is associated
# with the 'thread' of the corresponding linked PyTorch event to properly track
# parents and children
f_evt.thread = fe.thread
def createFunctionEventForMemoryEvents(evt):
rel_start_ns = evt.start_ns() - trace_start_ns
fe = FunctionEvent(
id=max_evt_id,
name=evt.name(),
overload_name="",
trace_name=None, # not outputting in the trace
thread=evt.start_thread_id(),
start_us=rel_start_ns / 1000,
end_us=rel_start_ns / 1000, # no duration
fwd_thread=evt.start_thread_id(),
input_shapes=[],
stack=[],
scope=0, # RecordScope::FUNCTION
use_device=self.use_device,
cpu_memory_usage=_cpu_memory_usage(evt),
device_memory_usage=_device_memory_usage(evt),
is_async=False,
sequence_nr=-1,
device_type=DeviceType.CPU,
device_index=0,
)
return fe
# output top-level memory events
for mem_record in mem_records:
if not mem_record[1]:
max_evt_id += 1
fe = createFunctionEventForMemoryEvents(mem_record[0])
all_function_events.append(fe)
for oom_record in oom_records:
max_evt_id += 1
fe = createFunctionEventForMemoryEvents(oom_record)
all_function_events.append(fe)
all_function_events.sort(
key=lambda evt: [evt.time_range.start, -evt.time_range.end]
)
return all_function_events
# pyrefly: ignore [invalid-inheritance]
| profile |
python | getsentry__sentry | tests/sentry/middleware/integrations/parsers/test_github_enterprise.py | {
"start": 979,
"end": 6855
} | class ____(TestCase):
factory = RequestFactory()
path = reverse("sentry-integration-github-enterprise-webhook")
external_host = "12.345.678.901"
external_identifier = "github_enterprise:1"
external_id = f"{external_host}:{external_identifier}"
def get_response(self, req: HttpRequest) -> HttpResponse:
return HttpResponse(status=200, content="passthrough")
def get_integration(self) -> Integration:
return self.create_integration(
organization=self.organization,
external_id=self.external_id,
provider="github_enterprise",
)
@override_settings(SILO_MODE=SiloMode.CONTROL)
@override_regions(region_config)
def test_invalid_webhook(self) -> None:
self.get_integration()
request = self.factory.post(
self.path, data=b"invalid-data", content_type="application/x-www-form-urlencoded"
)
parser = GithubEnterpriseRequestParser(request=request, response_handler=self.get_response)
response = parser.get_response()
assert response.status_code == 400
@override_settings(SILO_MODE=SiloMode.CONTROL)
@override_regions(region_config)
@responses.activate
def test_routing_no_organization_integrations_found(self) -> None:
integration = self.get_integration()
with outbox_context(transaction.atomic(using=router.db_for_write(OrganizationIntegration))):
# Remove all organizations from integration
OrganizationIntegration.objects.filter(integration=integration).delete()
request = self.factory.post(
self.path,
data={"installation": {"id": self.external_identifier}},
content_type="application/json",
HTTP_X_GITHUB_ENTERPRISE_HOST=self.external_host,
)
parser = GithubEnterpriseRequestParser(request=request, response_handler=self.get_response)
response = parser.get_response()
assert isinstance(response, HttpResponse)
assert response.status_code == 400
assert len(responses.calls) == 0
assert_no_webhook_payloads()
@override_settings(SILO_MODE=SiloMode.CONTROL)
@override_regions(region_config)
@responses.activate
def test_routing_no_integrations_found(self) -> None:
self.get_integration()
request = self.factory.post(self.path, data={}, content_type="application/json")
parser = GithubEnterpriseRequestParser(request=request, response_handler=self.get_response)
response = parser.get_response()
assert isinstance(response, HttpResponse)
assert response.status_code == 400
assert len(responses.calls) == 0
assert_no_webhook_payloads()
@override_settings(SILO_MODE=SiloMode.CONTROL)
@override_regions(region_config)
def test_get_integration_from_request_no_host(self) -> None:
# No host header
request = self.factory.post(
self.path,
data={"installation": {"id": self.external_identifier}},
content_type="application/json",
)
self.get_integration()
parser = GithubEnterpriseRequestParser(request=request, response_handler=self.get_response)
result = parser.get_integration_from_request()
assert result is None
@override_settings(SILO_MODE=SiloMode.CONTROL)
@override_regions(region_config)
def test_get_integration_from_request_with_host(self) -> None:
# With host header
request = self.factory.post(
self.path,
data={"installation": {"id": self.external_identifier}},
content_type="application/json",
HTTP_X_GITHUB_ENTERPRISE_HOST=self.external_host,
)
integration = self.get_integration()
parser = GithubEnterpriseRequestParser(request=request, response_handler=self.get_response)
result = parser.get_integration_from_request()
assert result == integration
@override_settings(SILO_MODE=SiloMode.CONTROL)
@override_regions(region_config)
@responses.activate
def test_installation_hook_handled_in_control(self) -> None:
self.get_integration()
request = self.factory.post(
self.path,
data={"installation": {"id": self.external_identifier}, "action": "created"},
content_type="application/json",
headers={
"X-GITHUB-EVENT": "installation",
},
HTTP_X_GITHUB_ENTERPRISE_HOST=self.external_host,
)
parser = GithubEnterpriseRequestParser(request=request, response_handler=self.get_response)
response = parser.get_response()
assert isinstance(response, HttpResponse)
assert response.status_code == 200
assert response.content == b"passthrough"
assert len(responses.calls) == 0
assert_no_webhook_payloads()
@override_settings(SILO_MODE=SiloMode.CONTROL)
@override_regions(region_config)
@responses.activate
def test_webhook_outbox_creation(self) -> None:
integration = self.get_integration()
request = self.factory.post(
self.path,
data={"installation": {"id": self.external_identifier}, "action": "opened"},
content_type="application/json",
HTTP_X_GITHUB_ENTERPRISE_HOST=self.external_host,
)
parser = GithubEnterpriseRequestParser(request=request, response_handler=self.get_response)
response = parser.get_response()
assert isinstance(response, HttpResponse)
assert response.status_code == 202
assert response.content == b""
assert_webhook_payloads_for_mailbox(
request=request,
mailbox_name=f"github_enterprise:{integration.id}",
region_names=[region.name],
)
| GithubEnterpriseRequestParserTest |
python | getsentry__sentry | tests/sentry/incidents/test_logic.py | {
"start": 77728,
"end": 90099
} | class ____(TestCase, BaseIncidentsTest):
def setUp(self) -> None:
super().setUp()
class _DynamicMetricAlertSettings(TypedDict):
name: str
query: str
aggregate: str
time_window: int
threshold_type: AlertRuleThresholdType
threshold_period: int
event_types: list[SnubaQueryEventType.EventType]
detection_type: AlertRuleDetectionType
sensitivity: AlertRuleSensitivity
seasonality: AlertRuleSeasonality
self.dynamic_metric_alert_settings: _DynamicMetricAlertSettings = {
"name": "hello",
"query": "level:error",
"aggregate": "count(*)",
"time_window": 30,
"threshold_type": AlertRuleThresholdType.ABOVE,
"threshold_period": 1,
"event_types": [SnubaQueryEventType.EventType.ERROR],
"detection_type": AlertRuleDetectionType.DYNAMIC,
"sensitivity": AlertRuleSensitivity.LOW,
"seasonality": AlertRuleSeasonality.AUTO,
}
@cached_property
def alert_rule(self):
return self.create_alert_rule()
@cached_property
@patch(
"sentry.seer.anomaly_detection.store_data.seer_anomaly_detection_connection_pool.urlopen"
)
def dynamic_alert_rule(self, mock_seer_request):
seer_return_value: StoreDataResponse = {"success": True}
mock_seer_request.return_value = HTTPResponse(orjson.dumps(seer_return_value), status=200)
return self.create_alert_rule(
self.organization,
[self.project],
**self.dynamic_metric_alert_settings,
)
def test(self) -> None:
alert_rule_id = self.alert_rule.id
with self.tasks():
delete_alert_rule(self.alert_rule)
assert not AlertRule.objects.filter(id=alert_rule_id).exists()
assert AlertRule.objects_with_snapshots.filter(id=alert_rule_id).exists()
with self.tasks():
run_scheduled_deletions()
assert not AlertRule.objects.filter(id=alert_rule_id).exists()
assert not AlertRule.objects_with_snapshots.filter(id=alert_rule_id).exists()
def test_with_incident(self) -> None:
incident = self.create_incident()
incident.update(alert_rule=self.alert_rule)
alert_rule_id = self.alert_rule.id
with self.tasks():
delete_alert_rule(self.alert_rule)
assert AlertRule.objects_with_snapshots.filter(id=alert_rule_id).exists()
assert not AlertRule.objects.filter(id=alert_rule_id).exists()
incident = Incident.objects.get(id=incident.id)
assert Incident.objects.filter(id=incident.id, alert_rule=self.alert_rule).exists()
@with_feature("organizations:anomaly-detection-alerts")
@patch(
"sentry.seer.anomaly_detection.delete_rule.seer_anomaly_detection_connection_pool.urlopen"
)
def test_with_incident_anomaly_detection_rule(self, mock_seer_request: MagicMock) -> None:
alert_rule = self.dynamic_alert_rule
alert_rule_id = alert_rule.id
incident = self.create_incident()
incident.update(alert_rule=alert_rule)
seer_return_value: StoreDataResponse = {"success": True}
mock_seer_request.return_value = HTTPResponse(orjson.dumps(seer_return_value), status=200)
with self.tasks():
delete_alert_rule(alert_rule)
assert AlertRule.objects_with_snapshots.filter(id=alert_rule_id).exists()
assert not AlertRule.objects.filter(id=alert_rule_id).exists()
incident = Incident.objects.get(id=incident.id)
assert Incident.objects.filter(id=incident.id, alert_rule=alert_rule).exists()
with self.tasks():
run_scheduled_deletions()
assert not AlertRule.objects.filter(id=alert_rule_id).exists()
assert AlertRule.objects_with_snapshots.filter(id=alert_rule_id).exists()
assert mock_seer_request.call_count == 1
@with_feature("organizations:anomaly-detection-alerts")
@patch(
"sentry.seer.anomaly_detection.delete_rule.seer_anomaly_detection_connection_pool.urlopen"
)
@patch("sentry.seer.anomaly_detection.delete_rule.logger")
@patch("sentry.incidents.logic.logger")
def test_with_incident_anomaly_detection_rule_error(
self, mock_model_logger, mock_seer_logger, mock_seer_request
):
alert_rule = self.dynamic_alert_rule
alert_rule_id = alert_rule.id
incident = self.create_incident()
incident.update(alert_rule=alert_rule)
query_sub = QuerySubscription.objects.get(snuba_query_id=alert_rule.snuba_query.id)
mock_seer_request.return_value = HTTPResponse("Bad request", status=500)
with self.tasks():
delete_alert_rule(alert_rule)
assert AlertRule.objects_with_snapshots.filter(id=alert_rule_id).exists()
assert not AlertRule.objects.filter(id=alert_rule_id).exists()
incident = Incident.objects.get(id=incident.id)
assert Incident.objects.filter(id=incident.id, alert_rule=alert_rule).exists()
mock_seer_logger.error.assert_called_with(
"Error when hitting Seer delete rule data endpoint",
extra={"response_data": "Bad request", "source_id": query_sub.id},
)
mock_model_logger.error.assert_called_with(
"Call to delete rule data in Seer failed",
extra={"source_id": query_sub.id},
)
assert mock_seer_request.call_count == 1
@patch("sentry.incidents.logic.schedule_update_project_config")
def test_on_demand_metric_alert(self, mocked_schedule_update_project_config: MagicMock) -> None:
alert_rule = self.create_alert_rule(query="transaction.duration:>=100")
with self.tasks():
delete_alert_rule(alert_rule)
mocked_schedule_update_project_config.assert_called_with(alert_rule, [self.project])
@with_feature("organizations:anomaly-detection-alerts")
@patch(
"sentry.seer.anomaly_detection.delete_rule.seer_anomaly_detection_connection_pool.urlopen"
)
def test_delete_anomaly_detection_rule(self, mock_seer_request: MagicMock) -> None:
alert_rule = self.dynamic_alert_rule
alert_rule_id = alert_rule.id
seer_return_value: StoreDataResponse = {"success": True}
mock_seer_request.return_value = HTTPResponse(orjson.dumps(seer_return_value), status=200)
with self.tasks():
delete_alert_rule(alert_rule)
assert AlertRule.objects_with_snapshots.filter(id=alert_rule_id).exists()
with self.tasks():
run_scheduled_deletions()
assert not AlertRule.objects.filter(id=alert_rule_id).exists()
assert not AlertRule.objects_with_snapshots.filter(id=alert_rule_id).exists()
assert mock_seer_request.call_count == 1
@with_feature("organizations:anomaly-detection-alerts")
@patch(
"sentry.seer.anomaly_detection.delete_rule.seer_anomaly_detection_connection_pool.urlopen"
)
@patch("sentry.seer.anomaly_detection.delete_rule.logger")
@patch("sentry.incidents.logic.logger")
def test_delete_anomaly_detection_rule_timeout(
self, mock_model_logger, mock_seer_logger, mock_seer_request
):
alert_rule = self.dynamic_alert_rule
alert_rule_id = alert_rule.id
query_sub = QuerySubscription.objects.get(snuba_query_id=alert_rule.snuba_query.id)
mock_seer_request.side_effect = TimeoutError
with self.tasks():
delete_alert_rule(alert_rule)
run_scheduled_deletions()
assert not AlertRule.objects.filter(id=alert_rule_id).exists()
assert not AlertRule.objects_with_snapshots.filter(id=alert_rule_id).exists()
mock_seer_logger.warning.assert_called_with(
"Timeout error when hitting Seer delete rule data endpoint",
extra={"source_id": query_sub.id},
)
mock_model_logger.error.assert_called_with(
"Call to delete rule data in Seer failed",
extra={"source_id": query_sub.id},
)
assert mock_seer_request.call_count == 1
@with_feature("organizations:anomaly-detection-alerts")
@patch(
"sentry.seer.anomaly_detection.delete_rule.seer_anomaly_detection_connection_pool.urlopen"
)
@patch("sentry.seer.anomaly_detection.delete_rule.logger")
@patch("sentry.incidents.logic.logger")
def test_delete_anomaly_detection_rule_error(
self, mock_model_logger, mock_seer_logger, mock_seer_request
):
alert_rule = self.dynamic_alert_rule
alert_rule_id = alert_rule.id
query_sub = QuerySubscription.objects.get(snuba_query_id=alert_rule.snuba_query.id)
mock_seer_request.return_value = HTTPResponse("Bad request", status=500)
with self.tasks():
delete_alert_rule(alert_rule)
run_scheduled_deletions()
assert not AlertRule.objects.filter(id=alert_rule_id).exists()
assert not AlertRule.objects_with_snapshots.filter(id=alert_rule_id).exists()
mock_seer_logger.error.assert_called_with(
"Error when hitting Seer delete rule data endpoint",
extra={"response_data": "Bad request", "source_id": query_sub.id},
)
mock_model_logger.error.assert_called_with(
"Call to delete rule data in Seer failed",
extra={"source_id": query_sub.id},
)
assert mock_seer_request.call_count == 1
@with_feature("organizations:anomaly-detection-alerts")
@patch(
"sentry.seer.anomaly_detection.delete_rule.seer_anomaly_detection_connection_pool.urlopen"
)
@patch("sentry.seer.anomaly_detection.delete_rule.logger")
@patch("sentry.incidents.logic.logger")
def test_delete_anomaly_detection_rule_attribute_error(
self, mock_model_logger, mock_seer_logger, mock_seer_request
):
alert_rule = self.dynamic_alert_rule
alert_rule_id = alert_rule.id
query_sub = QuerySubscription.objects.get(snuba_query_id=alert_rule.snuba_query.id)
mock_seer_request.return_value = HTTPResponse(None, status=200) # type:ignore[arg-type]
with self.tasks():
delete_alert_rule(alert_rule)
run_scheduled_deletions()
assert not AlertRule.objects.filter(id=alert_rule_id).exists()
assert not AlertRule.objects_with_snapshots.filter(id=alert_rule_id).exists()
mock_seer_logger.exception.assert_called_with(
"Failed to parse Seer delete rule data response",
extra={"source_id": query_sub.id},
)
mock_model_logger.error.assert_called_with(
"Call to delete rule data in Seer failed",
extra={"source_id": query_sub.id},
)
assert mock_seer_request.call_count == 1
@with_feature("organizations:anomaly-detection-alerts")
@patch(
"sentry.seer.anomaly_detection.delete_rule.seer_anomaly_detection_connection_pool.urlopen"
)
@patch("sentry.seer.anomaly_detection.delete_rule.logger")
@patch("sentry.incidents.logic.logger")
def test_delete_anomaly_detection_rule_failure(
self, mock_model_logger, mock_seer_logger, mock_seer_request
):
alert_rule = self.dynamic_alert_rule
alert_rule_id = alert_rule.id
query_sub = QuerySubscription.objects.get(snuba_query_id=alert_rule.snuba_query.id)
seer_return_value: StoreDataResponse = {"success": False}
mock_seer_request.return_value = HTTPResponse(orjson.dumps(seer_return_value), status=200)
with self.tasks():
delete_alert_rule(alert_rule)
run_scheduled_deletions()
assert not AlertRule.objects.filter(id=alert_rule_id).exists()
assert not AlertRule.objects_with_snapshots.filter(id=alert_rule_id).exists()
mock_seer_logger.error.assert_called_with(
"Request to delete alert rule from Seer was unsuccessful",
extra={"source_id": query_sub.id, "message": None},
)
mock_model_logger.error.assert_called_with(
"Call to delete rule data in Seer failed",
extra={"source_id": query_sub.id},
)
assert mock_seer_request.call_count == 1
| DeleteAlertRuleTest |
python | astropy__astropy | astropy/table/info.py | {
"start": 3521,
"end": 7381
} | class ____(DataInfo):
def __call__(self, option="attributes", out=""):
return table_info(self._parent, option, out)
__call__.__doc__ = table_info.__doc__
@contextmanager
def serialize_method_as(tbl, serialize_method):
"""Context manager to temporarily override individual
column info.serialize_method dict values. The serialize_method
attribute is an optional dict which might look like ``{'fits':
'jd1_jd2', 'ecsv': 'formatted_value', ..}``.
``serialize_method`` is a str or dict. If str then it the value
is the ``serialize_method`` that will be used for all formats.
If dict then the key values can be either:
- Column name. This has higher precedence than the second option of
matching class.
- Class (matches any column which is an instance of the class)
This context manager is expected to be used only within ``Table.write``.
It could have been a private method on Table but prefer not to add
clutter to that class.
Parameters
----------
tbl : Table object
Input table
serialize_method : dict, str
Dict with key values of column names or types, or str
Returns
-------
None (context manager)
"""
def get_override_sm(col):
"""
Determine if the ``serialize_method`` str or dict specifies an
override of column presets for ``col``. Returns the matching
serialize_method value or ``None``.
"""
# If a string then all columns match
if isinstance(serialize_method, str):
return serialize_method
# If column name then return that serialize_method
if col.info.name in serialize_method:
return serialize_method[col.info.name]
# Otherwise look for subclass matches
for key in serialize_method:
if isinstance(key, type) and isinstance(col, key):
return serialize_method[key]
return None
# Setup for the context block. Set individual column.info.serialize_method
# values as appropriate and keep a backup copy. If ``serialize_method``
# is None or empty then don't do anything.
# Original serialize_method dict, keyed by column name. This only
# gets used and set if there is an override.
original_sms = {}
if serialize_method:
# Go through every column and if it has a serialize_method info
# attribute then potentially update it for the duration of the write.
for col in tbl.itercols():
if hasattr(col.info, "serialize_method"):
override_sm = get_override_sm(col)
if override_sm:
# Make a reference copy of the column serialize_method
# dict which maps format (e.g. 'fits') to the
# appropriate method (e.g. 'data_mask').
original_sms[col.info.name] = col.info.serialize_method
# Set serialize method for *every* available format. This is
# brute force, but at this point the format ('fits', 'ecsv', etc)
# is not actually known (this gets determined by the write function
# in registry.py). Note this creates a new temporary dict object
# so that the restored version is the same original object.
col.info.serialize_method = dict.fromkeys(
col.info.serialize_method, override_sm
)
# Finally yield for the context block
try:
yield
finally:
# Teardown (restore) for the context block. Be sure to do this even
# if an exception occurred.
if serialize_method:
for name, original_sm in original_sms.items():
tbl[name].info.serialize_method = original_sm
| TableInfo |
python | scipy__scipy | scipy/signal/tests/test_filter_design.py | {
"start": 212977,
"end": 217534
} | class ____:
@pytest.mark.parametrize(
"func,ftype",
[
make_xp_pytest_param(butter, "butter"),
make_xp_pytest_param(bessel, "bessel"),
make_xp_pytest_param(cheby1, "cheby1"),
make_xp_pytest_param(cheby2, "cheby2"),
make_xp_pytest_param(ellip, "ellip"),
]
)
def test_symmetry(self, func, ftype, xp):
# All built-in IIR filters are real, so should have perfectly
# symmetrical poles and zeros. Then ba representation (using
# numpy.poly) will be purely real instead of having negligible
# imaginary parts.
for N in range(1, 26):
z, p, k = iirfilter(N, xp.asarray(1.1), 1, 20, 'low', analog=True,
ftype=ftype, output='zpk')
xp_assert_close(_sort_cmplx(z, xp=xp), _sort_cmplx(xp.conj(z), xp=xp))
xp_assert_close(_sort_cmplx(p, xp=xp), _sort_cmplx(xp.conj(p), xp=xp))
assert complex(k).imag == 0
b, a = iirfilter(N, xp.asarray(1.1), 1, 20, 'low', analog=True,
ftype=ftype, output='ba')
isdtype = array_namespace(b).isdtype
assert isdtype(b.dtype, ('real floating', 'complex floating'))
assert isdtype(a.dtype, ('real floating', 'complex floating'))
@make_xp_test_case(bessel)
def test_int_inputs(self, xp):
# Using integer frequency arguments and large N should not produce
# numpy integers that wraparound to negative numbers
k = iirfilter(24, xp.asarray(100), btype='low', analog=True, ftype='bessel',
output='zpk')[2]
k2 = 9.999999999999989e+47
assert math.isclose(k, k2)
# if fs is specified then the normalization of Wn to have
# 0 <= Wn <= 1 should not cause an integer overflow
# the following line should not raise an exception
iirfilter(20, xp.asarray([1000000000, 1100000000]), btype='bp',
analog=False, fs=6250000000)
def test_invalid_wn_size(self):
# low and high have 1 Wn, band and stop have 2 Wn
assert_raises(ValueError, iirfilter, 1, [0.1, 0.9], btype='low')
assert_raises(ValueError, iirfilter, 1, [0.2, 0.5], btype='high')
assert_raises(ValueError, iirfilter, 1, 0.2, btype='bp')
assert_raises(ValueError, iirfilter, 1, 400, btype='bs', analog=True)
def test_invalid_wn_range(self):
# For digital filters, 0 <= Wn <= 1
assert_raises(ValueError, iirfilter, 1, 2, btype='low')
assert_raises(ValueError, iirfilter, 1, [0.5, 1], btype='band')
assert_raises(ValueError, iirfilter, 1, [0., 0.5], btype='band')
assert_raises(ValueError, iirfilter, 1, -1, btype='high')
assert_raises(ValueError, iirfilter, 1, [1, 2], btype='band')
assert_raises(ValueError, iirfilter, 1, [10, 20], btype='stop')
# analog=True with non-positive critical frequencies
with pytest.raises(ValueError, match="must be greater than 0"):
iirfilter(2, 0, btype='low', analog=True)
with pytest.raises(ValueError, match="must be greater than 0"):
iirfilter(2, -1, btype='low', analog=True)
with pytest.raises(ValueError, match="must be greater than 0"):
iirfilter(2, [0, 100], analog=True)
with pytest.raises(ValueError, match="must be greater than 0"):
iirfilter(2, [-1, 100], analog=True)
with pytest.raises(ValueError, match="must be greater than 0"):
iirfilter(2, [10, 0], analog=True)
with pytest.raises(ValueError, match="must be greater than 0"):
iirfilter(2, [10, -1], analog=True)
@make_xp_test_case(butter)
def test_analog_sos(self, xp):
# first order Butterworth filter with Wn = 1 has tf 1/(s+1)
sos = xp.asarray([[0., 0., 1., 0., 1., 1.]])
sos2 = iirfilter(N=1, Wn=xp.asarray(1), btype='low', analog=True, output='sos')
assert_array_almost_equal(sos, sos2)
def test_wn1_ge_wn0(self):
# gh-15773: should raise error if Wn[0] >= Wn[1]
with pytest.raises(ValueError,
match=r"Wn\[0\] must be less than Wn\[1\]"):
iirfilter(2, [0.5, 0.5])
with pytest.raises(ValueError,
match=r"Wn\[0\] must be less than Wn\[1\]"):
iirfilter(2, [0.6, 0.5])
@skip_xp_backends("dask.array", reason="https://github.com/dask/dask/issues/11883")
@make_xp_test_case(group_delay)
| TestIIRFilter |
python | pandas-dev__pandas | pandas/core/interchange/dataframe.py | {
"start": 455,
"end": 3867
} | class ____(DataFrameXchg):
"""
A data frame class, with only the methods required by the interchange
protocol defined.
Instances of this (private) class are returned from
``pd.DataFrame.__dataframe__`` as objects with the methods and
attributes defined on this class.
"""
def __init__(self, df: DataFrame, allow_copy: bool = True) -> None:
"""
Constructor - an instance of this (private) class is returned from
`pd.DataFrame.__dataframe__`.
"""
self._df = df.rename(columns=str)
self._allow_copy = allow_copy
for i, _col in enumerate(self._df.columns):
rechunked = maybe_rechunk(self._df.iloc[:, i], allow_copy=allow_copy)
if rechunked is not None:
self._df.isetitem(i, rechunked)
def __dataframe__(
self, nan_as_null: bool = False, allow_copy: bool = True
) -> PandasDataFrameXchg:
# `nan_as_null` can be removed here once it's removed from
# Dataframe.__dataframe__
return PandasDataFrameXchg(self._df, allow_copy)
@property
def metadata(self) -> dict[str, Index]:
# `index` isn't a regular column, and the protocol doesn't support row
# labels - so we export it as Pandas-specific metadata here.
return {"pandas.index": self._df.index}
def num_columns(self) -> int:
return len(self._df.columns)
def num_rows(self) -> int:
return len(self._df)
def num_chunks(self) -> int:
return 1
def column_names(self) -> Index:
return self._df.columns
def get_column(self, i: int) -> PandasColumn:
return PandasColumn(self._df.iloc[:, i], allow_copy=self._allow_copy)
def get_column_by_name(self, name: str) -> PandasColumn:
return PandasColumn(self._df[name], allow_copy=self._allow_copy)
def get_columns(self) -> list[PandasColumn]:
return [
PandasColumn(self._df[name], allow_copy=self._allow_copy)
for name in self._df.columns
]
def select_columns(self, indices: Sequence[int]) -> PandasDataFrameXchg:
if not isinstance(indices, abc.Sequence):
raise ValueError("`indices` is not a sequence")
if not isinstance(indices, list):
indices = list(indices)
return PandasDataFrameXchg(
self._df.iloc[:, indices], allow_copy=self._allow_copy
)
def select_columns_by_name(self, names: list[str]) -> PandasDataFrameXchg: # type: ignore[override]
if not isinstance(names, abc.Sequence):
raise ValueError("`names` is not a sequence")
if not isinstance(names, list):
names = list(names)
return PandasDataFrameXchg(self._df.loc[:, names], allow_copy=self._allow_copy)
def get_chunks(self, n_chunks: int | None = None) -> Iterable[PandasDataFrameXchg]:
"""
Return an iterator yielding the chunks.
"""
if n_chunks and n_chunks > 1:
size = len(self._df)
step = size // n_chunks
if size % n_chunks != 0:
step += 1
for start in range(0, step * n_chunks, step):
yield PandasDataFrameXchg(
self._df.iloc[start : start + step, :],
allow_copy=self._allow_copy,
)
else:
yield self
| PandasDataFrameXchg |
python | astropy__astropy | astropy/units/errors.py | {
"start": 322,
"end": 418
} | class ____(Exception):
"""
The base class for unit-specific exceptions.
"""
| UnitsError |
python | walkccc__LeetCode | solutions/1987. Number of Unique Good Subsequences/1987.py | {
"start": 0,
"end": 557
} | class ____:
# Similar to 940. Distinct Subsequences II
def numberOfUniqueGoodSubsequences(self, binary: str) -> int:
MOD = 1_000_000_007
# endsIn[i] := the number of subsequence that end in ('0' + i)
endsIn = {'0': 0, '1': 0}
for c in binary:
endsIn[c] = sum(endsIn.values()) % MOD
# Don't count '0' since we want to avoid the leading zeros case.
# However, we can always count '1'.
if c == '1':
endsIn['1'] += 1
# Count '0' in the end.
return (sum(endsIn.values()) + ('0' in binary)) % MOD
| Solution |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/with2.py | {
"start": 188,
"end": 254
} | class ____(object):
def __enter__(self):
return 1
| Class2 |
python | django__django | django/contrib/auth/migrations/0010_alter_group_name_max_length.py | {
"start": 43,
"end": 378
} | class ____(migrations.Migration):
dependencies = [
("auth", "0009_alter_user_last_name_max_length"),
]
operations = [
migrations.AlterField(
model_name="group",
name="name",
field=models.CharField(max_length=150, unique=True, verbose_name="name"),
),
]
| Migration |
python | crytic__slither | slither/vyper_parsing/ast/ast.py | {
"start": 612,
"end": 11525
} | class ____(Exception):
pass
def _extract_base_props(raw: Dict) -> Dict:
return {
"src": raw["src"],
"node_id": raw["node_id"],
}
def _extract_decl_props(raw: Dict) -> Dict:
return {
"doc_string": parse_doc_str(raw["doc_string"]) if raw["doc_string"] else None,
**_extract_base_props(raw),
}
def parse_module(raw: Dict) -> Module:
nodes_parsed: List[ASTNode] = []
for node in raw["body"]:
nodes_parsed.append(parse(node))
return Module(name=raw["name"], body=nodes_parsed, **_extract_decl_props(raw))
def parse_import_from(raw: Dict) -> ImportFrom:
return ImportFrom(
module=raw["module"],
name=raw["name"],
alias=raw["alias"],
**_extract_base_props(raw),
)
def parse_event_def(raw: Dict) -> EventDef:
body_parsed: List[ASTNode] = []
for node in raw["body"]:
body_parsed.append(parse(node))
return EventDef(
name=raw["name"],
body=body_parsed,
*_extract_base_props(raw),
)
def parse_ann_assign(raw: Dict) -> AnnAssign:
return AnnAssign(
target=parse(raw["target"]),
annotation=parse(raw["annotation"]),
value=parse(raw["value"]) if raw["value"] else None,
**_extract_base_props(raw),
)
def parse_name(raw: Dict) -> Name:
return Name(
id=raw["id"],
**_extract_base_props(raw),
)
def parse_call(raw: Dict) -> Call:
return Call(
func=parse(raw["func"]),
args=[parse(arg) for arg in raw["args"]],
keyword=parse(raw["keyword"]) if raw["keyword"] else None,
keywords=[parse(keyword) for keyword in raw["keywords"]],
**_extract_base_props(raw),
)
def parse_struct_def(raw: Dict) -> StructDef:
body_parsed: List[ASTNode] = []
for node in raw["body"]:
body_parsed.append(parse(node))
return StructDef(
name=raw["name"],
body=body_parsed,
**_extract_base_props(raw),
)
def parse_variable_decl(raw: Dict) -> VariableDecl:
return VariableDecl(
annotation=parse(raw["annotation"]),
value=parse(raw["value"]) if raw["value"] else None,
target=parse(raw["target"]),
is_constant=raw["is_constant"],
is_immutable=raw["is_immutable"],
is_public=raw["is_public"],
**_extract_base_props(raw),
)
def parse_subscript(raw: Dict) -> Subscript:
return Subscript(
value=parse(raw["value"]),
slice=parse(raw["slice"]),
**_extract_base_props(raw),
)
def parse_index(raw: Dict) -> Index:
return Index(value=parse(raw["value"]), **_extract_base_props(raw))
def parse_bytes(raw: Dict) -> Bytes:
return Bytes(value=raw["value"], **_extract_base_props(raw))
def parse_hex(raw: Dict) -> Hex:
return Hex(value=raw["value"], **_extract_base_props(raw))
def parse_int(raw: Dict) -> Int:
return Int(value=raw["value"], **_extract_base_props(raw))
def parse_str(raw: Dict) -> Str:
return Str(value=raw["value"], **_extract_base_props(raw))
def parse_tuple(raw: Dict) -> ASTNode:
return Tuple(elements=[parse(elem) for elem in raw["elements"]], **_extract_base_props(raw))
def parse_function_def(raw: Dict) -> FunctionDef:
body_parsed: List[ASTNode] = []
for node in raw["body"]:
body_parsed.append(parse(node))
decorators_parsed: List[ASTNode] = []
for node in raw["decorator_list"]:
decorators_parsed.append(parse(node))
return FunctionDef(
name=raw["name"],
args=parse_arguments(raw["args"]),
returns=parse(raw["returns"]) if raw["returns"] else None,
body=body_parsed,
pos=raw["pos"],
decorators=decorators_parsed,
**_extract_decl_props(raw),
)
def parse_assign(raw: Dict) -> Assign:
return Assign(
target=parse(raw["target"]),
value=parse(raw["value"]),
**_extract_base_props(raw),
)
def parse_attribute(raw: Dict) -> Attribute:
return Attribute(
value=parse(raw["value"]),
attr=raw["attr"],
**_extract_base_props(raw),
)
def parse_arguments(raw: Dict) -> Arguments:
return Arguments(
args=[parse_arg(arg) for arg in raw["args"]],
default=parse(raw["default"]) if raw["default"] else None,
defaults=[parse(x) for x in raw["defaults"]],
**_extract_base_props(raw),
)
def parse_arg(raw: Dict) -> Arg:
return Arg(arg=raw["arg"], annotation=parse(raw["annotation"]), **_extract_base_props(raw))
def parse_assert(raw: Dict) -> Assert:
return Assert(
test=parse(raw["test"]),
msg=parse(raw["msg"]) if raw["msg"] else None,
**_extract_base_props(raw),
)
def parse_raise(raw: Dict) -> Raise:
return Raise(exc=parse(raw["exc"]) if raw["exc"] else None, **_extract_base_props(raw))
def parse_expr(raw: Dict) -> Expr:
return Expr(value=parse(raw["value"]), **_extract_base_props(raw))
# This is done for convenience so we can call `UnaryOperationType.get_type` during expression parsing.
unop_ast_type_to_op_symbol = {"Not": "!", "USub": "-"}
def parse_unary_op(raw: Dict) -> UnaryOp:
unop_str = unop_ast_type_to_op_symbol[raw["op"]["ast_type"]]
return UnaryOp(op=unop_str, operand=parse(raw["operand"]), **_extract_base_props(raw))
# This is done for convenience so we can call `BinaryOperationType.get_type` during expression parsing.
binop_ast_type_to_op_symbol = {
"Add": "+",
"Mult": "*",
"Sub": "-",
"Div": "/",
"Pow": "**",
"Mod": "%",
"BitAnd": "&",
"BitOr": "|",
"Shr": "<<",
"Shl": ">>",
"NotEq": "!=",
"Eq": "==",
"LtE": "<=",
"GtE": ">=",
"Lt": "<",
"Gt": ">",
"In": "In",
"NotIn": "NotIn",
}
def parse_bin_op(raw: Dict) -> BinOp:
arith_op_str = binop_ast_type_to_op_symbol[raw["op"]["ast_type"]]
return BinOp(
left=parse(raw["left"]),
op=arith_op_str,
right=parse(raw["right"]),
**_extract_base_props(raw),
)
def parse_compare(raw: Dict) -> Compare:
logical_op_str = binop_ast_type_to_op_symbol[raw["op"]["ast_type"]]
return Compare(
left=parse(raw["left"]),
op=logical_op_str,
right=parse(raw["right"]),
**_extract_base_props(raw),
)
def parse_keyword(raw: Dict) -> Keyword:
return Keyword(arg=raw["arg"], value=parse(raw["value"]), **_extract_base_props(raw))
def parse_log(raw: Dict) -> Log:
return Log(value=parse(raw["value"]), **_extract_base_props(raw))
def parse_return(raw: Dict) -> Return:
return Return(value=parse(raw["value"]) if raw["value"] else None, **_extract_base_props(raw))
def parse_dict(raw: Dict) -> ASTNode:
return VyDict(
keys=[parse(x) for x in raw["keys"]],
values=[parse(x) for x in raw["values"]],
**_extract_base_props(raw),
)
def parse_list(raw: Dict) -> VyList:
return VyList(elements=[parse(x) for x in raw["elements"]], **_extract_base_props(raw))
def parse_name_constant(raw: Dict) -> NameConstant:
return NameConstant(value=raw["value"], **_extract_base_props(raw))
def parse_doc_str(raw: Dict) -> str:
assert isinstance(raw["value"], str)
return raw["value"]
def parse_if(raw: Dict) -> ASTNode:
return If(
test=parse(raw["test"]),
body=[parse(x) for x in raw["body"]],
orelse=[parse(x) for x in raw["orelse"]],
**_extract_base_props(raw),
)
def parse_for(raw: Dict) -> For:
return For(
target=parse(raw["target"]),
iter=parse(raw["iter"]),
body=[parse(x) for x in raw["body"]],
**_extract_base_props(raw),
)
def parse_break(raw: Dict) -> Break:
return Break(**_extract_base_props(raw))
def parse_continue(raw: Dict) -> Continue:
return Continue(**_extract_base_props(raw))
def parse_pass(raw: Dict) -> Pass:
return Pass(
**_extract_base_props(raw),
)
def parse_interface_def(raw: Dict) -> InterfaceDef:
nodes_parsed: List[ASTNode] = []
for node in raw["body"]:
nodes_parsed.append(parse(node))
return InterfaceDef(name=raw["name"], body=nodes_parsed, **_extract_base_props(raw))
def parse_enum_def(raw: Dict) -> EnumDef:
nodes_parsed: List[ASTNode] = []
for node in raw["body"]:
nodes_parsed.append(parse(node))
return EnumDef(name=raw["name"], body=nodes_parsed, **_extract_base_props(raw))
aug_assign_ast_type_to_op_symbol = {
"Add": "+=",
"Mult": "*=",
"Sub": "-=",
"Div": "-=",
"Pow": "**=",
"Mod": "%=",
"BitAnd": "&=",
"BitOr": "|=",
"Shr": "<<=",
"Shl": ">>=",
}
def parse_aug_assign(raw: Dict) -> AugAssign:
op_str = aug_assign_ast_type_to_op_symbol[raw["op"]["ast_type"]]
return AugAssign(
target=parse(raw["target"]),
op=op_str,
value=parse(raw["value"]),
**_extract_base_props(raw),
)
def parse_unsupported(raw: Dict) -> ASTNode:
raise ParsingError("unsupported Vyper node", raw["ast_type"], raw.keys(), raw)
bool_op_ast_type_to_op_symbol = {"And": "&&", "Or": "||"}
def parse_bool_op(raw: Dict) -> BoolOp:
op_str = bool_op_ast_type_to_op_symbol[raw["op"]["ast_type"]]
return BoolOp(op=op_str, values=[parse(x) for x in raw["values"]], **_extract_base_props(raw))
def parse(raw: Dict) -> ASTNode:
try:
return PARSERS.get(raw["ast_type"], parse_unsupported)(raw)
except ParsingError as e:
raise e
except Exception as e:
raise e
# raise ParsingError("failed to parse Vyper node", raw["ast_type"], e, raw.keys(), raw)
PARSERS: Dict[str, Callable[[Dict], ASTNode]] = {
"Module": parse_module,
"ImportFrom": parse_import_from,
"EventDef": parse_event_def,
"AnnAssign": parse_ann_assign,
"Name": parse_name,
"Call": parse_call,
"Pass": parse_pass,
"StructDef": parse_struct_def,
"VariableDecl": parse_variable_decl,
"Subscript": parse_subscript,
"Index": parse_index,
"Hex": parse_hex,
"Int": parse_int,
"Str": parse_str,
"DocStr": parse_doc_str,
"Tuple": parse_tuple,
"FunctionDef": parse_function_def,
"Assign": parse_assign,
"Raise": parse_raise,
"Attribute": parse_attribute,
"Assert": parse_assert,
"keyword": parse_keyword,
"arguments": parse_arguments,
"arg": parse_arg,
"UnaryOp": parse_unary_op,
"BinOp": parse_bin_op,
"Expr": parse_expr,
"Log": parse_log,
"Return": parse_return,
"If": parse_if,
"Dict": parse_dict,
"List": parse_list,
"Compare": parse_compare,
"NameConstant": parse_name_constant,
"For": parse_for,
"Break": parse_break,
"Continue": parse_continue,
"InterfaceDef": parse_interface_def,
"EnumDef": parse_enum_def,
"Bytes": parse_bytes,
"AugAssign": parse_aug_assign,
"BoolOp": parse_bool_op,
}
| ParsingError |
python | plotly__plotly.py | plotly/graph_objs/parcats/line/colorbar/_tickfont.py | {
"start": 233,
"end": 9944
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "parcats.line.colorbar"
_path_str = "parcats.line.colorbar.tickfont"
_valid_props = {
"color",
"family",
"lineposition",
"shadow",
"size",
"style",
"textcase",
"variant",
"weight",
}
@property
def color(self):
"""
The 'color' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color: see https://plotly.com/python/css-colors/ for a list
Returns
-------
str
"""
return self["color"]
@color.setter
def color(self, val):
self["color"] = val
@property
def family(self):
"""
HTML font family - the typeface that will be applied by the web
browser. The web browser can only apply a font if it is
available on the system where it runs. Provide multiple font
families, separated by commas, to indicate the order in which
to apply fonts if they aren't available.
The 'family' property is a string and must be specified as:
- A non-empty string
Returns
-------
str
"""
return self["family"]
@family.setter
def family(self, val):
self["family"] = val
@property
def lineposition(self):
"""
Sets the kind of decoration line(s) with text, such as an
"under", "over" or "through" as well as combinations e.g.
"under+over", etc.
The 'lineposition' property is a flaglist and may be specified
as a string containing:
- Any combination of ['under', 'over', 'through'] joined with '+' characters
(e.g. 'under+over')
OR exactly one of ['none'] (e.g. 'none')
Returns
-------
Any
"""
return self["lineposition"]
@lineposition.setter
def lineposition(self, val):
self["lineposition"] = val
@property
def shadow(self):
"""
Sets the shape and color of the shadow behind text. "auto"
places minimal shadow and applies contrast text font color. See
https://developer.mozilla.org/en-US/docs/Web/CSS/text-shadow
for additional options.
The 'shadow' property is a string and must be specified as:
- A string
- A number that will be converted to a string
Returns
-------
str
"""
return self["shadow"]
@shadow.setter
def shadow(self, val):
self["shadow"] = val
@property
def size(self):
"""
The 'size' property is a number and may be specified as:
- An int or float in the interval [1, inf]
Returns
-------
int|float
"""
return self["size"]
@size.setter
def size(self, val):
self["size"] = val
@property
def style(self):
"""
Sets whether a font should be styled with a normal or italic
face from its family.
The 'style' property is an enumeration that may be specified as:
- One of the following enumeration values:
['normal', 'italic']
Returns
-------
Any
"""
return self["style"]
@style.setter
def style(self, val):
self["style"] = val
@property
def textcase(self):
"""
Sets capitalization of text. It can be used to make text appear
in all-uppercase or all-lowercase, or with each word
capitalized.
The 'textcase' property is an enumeration that may be specified as:
- One of the following enumeration values:
['normal', 'word caps', 'upper', 'lower']
Returns
-------
Any
"""
return self["textcase"]
@textcase.setter
def textcase(self, val):
self["textcase"] = val
@property
def variant(self):
"""
Sets the variant of the font.
The 'variant' property is an enumeration that may be specified as:
- One of the following enumeration values:
['normal', 'small-caps', 'all-small-caps',
'all-petite-caps', 'petite-caps', 'unicase']
Returns
-------
Any
"""
return self["variant"]
@variant.setter
def variant(self, val):
self["variant"] = val
@property
def weight(self):
"""
Sets the weight (or boldness) of the font.
The 'weight' property is a integer and may be specified as:
- An int (or float that will be cast to an int)
in the interval [1, 1000]
OR exactly one of ['normal', 'bold'] (e.g. 'bold')
Returns
-------
int
"""
return self["weight"]
@weight.setter
def weight(self, val):
self["weight"] = val
@property
def _prop_descriptions(self):
return """\
color
family
HTML font family - the typeface that will be applied by
the web browser. The web browser can only apply a font
if it is available on the system where it runs. Provide
multiple font families, separated by commas, to
indicate the order in which to apply fonts if they
aren't available.
lineposition
Sets the kind of decoration line(s) with text, such as
an "under", "over" or "through" as well as combinations
e.g. "under+over", etc.
shadow
Sets the shape and color of the shadow behind text.
"auto" places minimal shadow and applies contrast text
font color. See https://developer.mozilla.org/en-
US/docs/Web/CSS/text-shadow for additional options.
size
style
Sets whether a font should be styled with a normal or
italic face from its family.
textcase
Sets capitalization of text. It can be used to make
text appear in all-uppercase or all-lowercase, or with
each word capitalized.
variant
Sets the variant of the font.
weight
Sets the weight (or boldness) of the font.
"""
def __init__(
self,
arg=None,
color=None,
family=None,
lineposition=None,
shadow=None,
size=None,
style=None,
textcase=None,
variant=None,
weight=None,
**kwargs,
):
"""
Construct a new Tickfont object
Sets the color bar's tick label font
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.parcats.line.c
olorbar.Tickfont`
color
family
HTML font family - the typeface that will be applied by
the web browser. The web browser can only apply a font
if it is available on the system where it runs. Provide
multiple font families, separated by commas, to
indicate the order in which to apply fonts if they
aren't available.
lineposition
Sets the kind of decoration line(s) with text, such as
an "under", "over" or "through" as well as combinations
e.g. "under+over", etc.
shadow
Sets the shape and color of the shadow behind text.
"auto" places minimal shadow and applies contrast text
font color. See https://developer.mozilla.org/en-
US/docs/Web/CSS/text-shadow for additional options.
size
style
Sets whether a font should be styled with a normal or
italic face from its family.
textcase
Sets capitalization of text. It can be used to make
text appear in all-uppercase or all-lowercase, or with
each word capitalized.
variant
Sets the variant of the font.
weight
Sets the weight (or boldness) of the font.
Returns
-------
Tickfont
"""
super().__init__("tickfont")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError("""\
The first argument to the plotly.graph_objs.parcats.line.colorbar.Tickfont
constructor must be a dict or
an instance of :class:`plotly.graph_objs.parcats.line.colorbar.Tickfont`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("color", arg, color)
self._set_property("family", arg, family)
self._set_property("lineposition", arg, lineposition)
self._set_property("shadow", arg, shadow)
self._set_property("size", arg, size)
self._set_property("style", arg, style)
self._set_property("textcase", arg, textcase)
self._set_property("variant", arg, variant)
self._set_property("weight", arg, weight)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
| Tickfont |
python | Pylons__pyramid | tests/test_security.py | {
"start": 6733,
"end": 9492
} | class ____(unittest.TestCase):
def setUp(self):
testing.setUp()
def tearDown(self):
testing.tearDown()
def _callFUT(self, *arg, **kw):
from pyramid.security import view_execution_permitted
return view_execution_permitted(*arg, **kw)
def _registerSecuredView(self, view_name, allow=True):
from zope.interface import Interface
from pyramid.interfaces import ISecuredView, IViewClassifier
from pyramid.threadlocal import get_current_registry
class Checker:
def __permitted__(self, context, request):
self.context = context
self.request = request
return allow
checker = Checker()
reg = get_current_registry()
reg.registerAdapter(
checker,
(IViewClassifier, Interface, Interface),
ISecuredView,
view_name,
)
return checker
def test_no_permission(self):
from zope.interface import Interface
from pyramid.interfaces import ISettings, IView, IViewClassifier
from pyramid.threadlocal import get_current_registry
settings = dict(debug_authorization=True)
reg = get_current_registry()
reg.registerUtility(settings, ISettings)
context = DummyContext()
request = testing.DummyRequest({})
class DummyView:
pass
view = DummyView()
reg.registerAdapter(
view, (IViewClassifier, Interface, Interface), IView, ''
)
result = self._callFUT(context, request, '')
msg = result.msg
self.assertTrue("Allowed: view name '' in context" in msg)
self.assertTrue('(no permission defined)' in msg)
self.assertEqual(result, True)
def test_no_view_registered(self):
from pyramid.interfaces import ISettings
from pyramid.threadlocal import get_current_registry
settings = dict(debug_authorization=True)
reg = get_current_registry()
reg.registerUtility(settings, ISettings)
context = DummyContext()
request = testing.DummyRequest({})
self.assertRaises(TypeError, self._callFUT, context, request, '')
def test_with_permission(self):
from zope.interface import Interface, directlyProvides
from pyramid.interfaces import IRequest
class IContext(Interface):
pass
context = DummyContext()
directlyProvides(context, IContext)
self._registerSecuredView('', True)
request = testing.DummyRequest({})
directlyProvides(request, IRequest)
result = self._callFUT(context, request, '')
self.assertTrue(result)
| TestViewExecutionPermitted |
python | walkccc__LeetCode | solutions/2963. Count the Number of Good Partitions/2963.py | {
"start": 0,
"end": 709
} | class ____:
def numberOfGoodPartitions(self, nums: list[int]) -> int:
MOD = 1_000_000_007
ans = 1
# lastSeen[num] := the index of the last time `num` appeared
lastSeen = {}
for i, num in enumerate(nums):
lastSeen[num] = i
# Track the maximum right index of each running partition by ensuring that
# the first and last occurrences of a number fall within the same partition.
maxRight = 0
for i, num in enumerate(nums):
if i > maxRight:
# Start a new partition that starts from nums[i].
# Each partition doubles the total number of good partitions.
ans = ans * 2 % MOD
maxRight = max(maxRight, lastSeen[num])
return ans
| Solution |
python | spyder-ide__spyder | spyder/plugins/run/tests/test_run.py | {
"start": 11736,
"end": 31105
} | class ____(type(ExampleRunExecutorWrapper)):
def __new__(cls, clsname, bases, attrs):
executor_name = attrs.pop('executor_name_meta')
def get_name():
return executor_name
return super(MetaExampleRunExecutor, cls).__new__(
cls, clsname, bases, {
**attrs,
'get_name': staticmethod(get_name),
'NAME': executor_name
}
)
def ExampleRunExecutorFactory(parent, info, executor_name):
class ExampleRunExecutor(
ExampleRunExecutorWrapper, metaclass=MetaExampleRunExecutor):
executor_name_meta = executor_name
return ExampleRunExecutor(parent, info, executor_name)
@pytest.fixture
def run_mock(qtbot, tmpdir):
temp_dir = str(tmpdir.mkdir('run'))
mock_main_window = MockedMainWindow()
run = Run(mock_main_window, None)
run.on_initialize()
run._switch_working_dir(temp_dir)
return run, mock_main_window, temp_dir
@pytest.mark.skipif(PYQT6, reason="Fails with PyQt6")
def test_run_plugin(qtbot, run_mock):
run, main_window, temp_cwd = run_mock
# Create mock run configuration providers
provider_1_conf = [
('ext1', 'RegisteredContext', True, False),
('ext1', 'SubordinateContext1', False, True),
('ext1', 'UnusedContext', False, True),
('ext2', 'AnotherSuperContext', True, False),
('ext3', 'RegisteredContext', True, False)
]
provider_2_conf = [
('ext1', 'RegisteredContext', True, False),
('ext1', 'SubordinateContext1', False, True),
('ext1', 'SubordinateContext2', False, True),
('ext3', 'AnotherSuperContext', True, False)
]
exec_provider_1 = ExampleConfigurationProvider(
main_window, provider_1_conf, 'conf_prov_1')
exec_provider_2 = ExampleConfigurationProvider(
main_window, provider_2_conf, 'conf_prov_2')
# Register providers with the Run plugin
exec_provider_1.on_run_available(run)
exec_provider_2.on_run_available(run)
# Assert that the actions for 'SubordinateContext1' are the same for both
# providers.
act1 = exec_provider_1.actions['SubordinateContext1']
act2 = exec_provider_2.actions['SubordinateContext1']
assert act1 == act2
# Create mock run executors
executor_1_conf = [
(
'ext1', 'RegisteredContext', 0, {
'opt1': True,
'opt2': '',
'opt3': False
}, True, 'both', True
),
(
'ext1', 'SubordinateContext1', 1, {
'arg1': '',
'arg2': False,
'arg3': False
}, False, 'ext', True
),
(
'ext2', 'AnotherSuperContext', 0, {
'only_opt': '',
}, True, 'context', False
),
(
'ext3', 'AnotherSuperContext', 0, {
'name_1': False,
'name_2': True
}, False, 'context', False
),
]
executor_2_conf = [
(
'ext1', 'RegisteredContext', 1, {
'ex2_opt1': True,
'ex2_opt2': False,
'ex2_opt3': False,
}, True, 'ext', True
),
(
'ext1', 'SubordinateContext1', 0, {
'arg1': '',
'arg2': False,
'arg3': False
}, True, 'ext', True
),
(
'ext1', 'SubordinateContext2', 0, {
'opt1': True,
'opt2': False,
'opt3': False
}, True, 'context', True
),
(
'ext3', 'RegisteredContext', 0, {
'name_1': False,
'name_2': True
}, False, 'all', False
),
]
executor_1 = ExampleRunExecutorFactory(
main_window, executor_1_conf, 'executor_1')
executor_2 = ExampleRunExecutorFactory(
main_window, executor_2_conf, 'executor_2')
# Register run executors on the Run plugin
executor_1.on_run_available(run)
executor_2.on_run_available(run)
# Focus on the first run configuration for the first configuration provider
exec_provider_1.switch_focus('ext1', 'RegisteredContext')
# Assert that both provider and run are in sync
container = run.get_container()
run_uuid = container.currently_selected_configuration
assert run_uuid == exec_provider_1.current_uuid
# Assert that run-specific context actions are available or disabled
act = exec_provider_1.actions['SubordinateContext1']
assert act.isEnabled()
act = exec_provider_1.actions['UnusedContext']
assert not act.isEnabled()
act = exec_provider_2.actions['SubordinateContext2']
assert not act.isEnabled()
# Spawn the configuration dialog
run_act = run.get_action(RunActions.Run)
run_act.trigger()
expected_configurations = []
total_prov_1_conf = zip(
repeat(exec_provider_1.provider_name, len(provider_1_conf)),
provider_1_conf)
total_prov_2_conf = zip(
repeat(exec_provider_2.provider_name, len(provider_2_conf)),
provider_2_conf)
for provider_name, (ext, context, reg, _) in chain(
total_prov_1_conf, total_prov_2_conf):
if reg:
expected_configurations.append(
(ext, context,
f'{ext}_{context.lower()}_{provider_name}_example'))
executors_per_conf = {}
executor_1_conf_id = zip(repeat(executor_1.NAME, len(executor_1_conf)),
executor_1_conf)
executor_2_conf_id = zip(repeat(executor_2.NAME, len(executor_2_conf)),
executor_2_conf)
executor_conf_iter = chain(executor_1_conf_id, executor_2_conf_id)
for (exec_name, (ext, context, prio,
default_conf, req_cwd, handler, _)) in executor_conf_iter:
conf_executors = executors_per_conf.get((ext, context), [])
conf_executors.insert(
prio, (exec_name, default_conf, req_cwd, handler))
executors_per_conf[(ext, context)] = conf_executors
dialog = container.dialog
with qtbot.waitSignal(dialog.finished, timeout=200000):
conf_combo = dialog.configuration_combo
exec_combo = dialog.executor_combo
wdir_group = dialog.wdir_group
# Ensure that there are 5 registered run configurations
assert conf_combo.count() == 5
# Ensure that the combobox contain all available configurations
for i, (_, _, label) in enumerate(expected_configurations):
combo_label = conf_combo.itemText(i)
assert label == combo_label
# Ensure that the currently selected configuration corresponds to the
# currently selected one.
assert conf_combo.currentText() == expected_configurations[0][-1]
# Ensure that the executor settings are being loaded correctly per
# run configuration
for i, (ext, context, _) in enumerate(expected_configurations):
conf_combo.setCurrentIndex(i)
available_executors = executors_per_conf[(ext, context)]
# Assert that the order and the executor configurations are loaded
# according to the priority order.
for (j, (executor_name,
default_conf,
req_cwd, _)) in enumerate(available_executors):
exec_combo.setCurrentIndex(j)
current_exec_name = exec_combo.currentText()
conf_widget = dialog.current_widget
current_conf = conf_widget.get_configuration()
# Ensure that the selected executor corresponds to the one
# defined by the priority order
assert current_exec_name == executor_name
# Ensure that the working directory options are enabled or
# disabled according to the executor settings.
assert not (wdir_group.isEnabled() ^ req_cwd)
# Ensure that the executor configuration group widget contains
# the default options declared.
assert current_conf == default_conf
# Select the first configuration again
conf_combo.setCurrentIndex(0)
# Change some default options
conf_widget = dialog.current_widget
cwd_radio = dialog.cwd_radio
conf_widget.widgets['opt2'].setText('Test')
cwd_radio.setChecked(True)
# Execute the configuration
buttons = dialog.bbox.buttons()
run_btn = buttons[2]
with qtbot.waitSignal(executor_1.sig_run_invocation) as sig:
qtbot.mouseClick(run_btn, Qt.LeftButton)
# Verify the selected executor output
test_executor_name, handler_name, run_input, exec_conf = sig.args[0]
ext, context, name = expected_configurations[0]
available_executors = executors_per_conf[(ext, context)]
executor_name, default_conf, _, handler = available_executors[0]
conf_copy = copy.deepcopy(default_conf)
conf_copy['opt2'] = 'Test'
actual_run_input = run_input['run_input']
metadata = run_input['metadata']
name = metadata['name']
source = metadata['source']
path = metadata['path']
context = metadata['context']
run_conf_uuid = metadata['uuid']
ext = metadata['input_extension']
contents = actual_run_input['contents']
assert contents == (f'File: {name} | Location: {path} | Source: {source} '
f'| Context: {context["name"]} | Ext: {ext}')
assert test_executor_name == executor_name
assert handler == 'both'
# Ensure that the executor run configuration was saved
assert exec_conf['uuid'] is not None
assert exec_conf['name'] == "Default (custom)"
# Check that the configuration parameters are the ones defined by the
# dialog
params = exec_conf['params']
working_dir = params['working_dir']
assert params['executor_params'] == conf_copy
assert working_dir['source'] == WorkingDirSource.CurrentDirectory
assert working_dir['path'] == temp_cwd
# Assert that the run_exec dispatcher works for the specific combination
assert handler_name == f'{ext}_{context["identifier"]}'
# Assert that the run configuration gets registered
stored_run_params = run.get_last_used_executor_parameters(run_conf_uuid)
current_exec_uuid = exec_conf['uuid']
assert stored_run_params['executor'] == test_executor_name
assert stored_run_params['selected'] == current_exec_uuid
# Spawn the configuration dialog
run_act = run.get_action(RunActions.Run)
run_act.trigger()
dialog = container.dialog
with qtbot.waitSignal(dialog.finished, timeout=200000):
# Select the first configuration again
conf_combo.setCurrentIndex(0)
# Change some options
conf_widget = dialog.current_widget
conf_widget.widgets['opt1'].setChecked(False)
# Execute the configuration
buttons = dialog.bbox.buttons()
run_btn = buttons[2]
with qtbot.waitSignal(executor_1.sig_run_invocation) as sig:
qtbot.mouseClick(run_btn, Qt.LeftButton)
# Assert that changes took effect and that the run executor parameters were
# saved in the Custom config
_, _, _, exec_conf = sig.args[0]
params = exec_conf['params']
assert params['executor_params']['opt1'] is False
assert exec_conf['uuid'] == current_exec_uuid
# Focus into another configuration
exec_provider_2.switch_focus('ext3', 'AnotherSuperContext')
# Re-run last configuration
re_run_act = run.get_action(RunActions.ReRun)
with qtbot.waitSignal(executor_1.sig_run_invocation) as sig:
re_run_act.trigger()
# Assert that the previously ran configuration is the same as the current
# one
_, _, run_input, _ = sig.args[0]
re_run_metadata = run_input['metadata']
assert re_run_metadata == metadata
# Run a subordinate context on the same executor
subordinate_act = exec_provider_1.actions['SubordinateContext1']
with qtbot.waitSignal(executor_1.sig_run_invocation) as sig:
subordinate_act.trigger()
subord_executor_name, handler_name, run_input, exec_conf = sig.args[0]
available_executors = executors_per_conf[('ext1', 'SubordinateContext1')]
executor_name, default_conf, _, handler = available_executors[1]
assert subord_executor_name == executor_name
assert handler_name == 'ext_ext1'
actual_run_input = run_input['run_input']
metadata = run_input['metadata']
name = metadata['name']
source = metadata['source']
path = metadata['path']
context = metadata['context']
run_conf_uuid = metadata['uuid']
ext = metadata['input_extension']
contents = actual_run_input['contents']
action = actual_run_input['action']
re_run = actual_run_input['re_run']
assert contents == (f'File: {name} | Location: {path} | Source: {source} '
f'| Context: {context["name"]} | Ext: {ext} '
f'| Action: {action} | Re-run: {re_run}')
params = exec_conf['params']
working_dir = params['working_dir']
assert params['executor_params'] == default_conf
assert working_dir['source'] == WorkingDirSource.ConfigurationDirectory
assert working_dir['path'] == ''
# Run a subordinate context on a different executor
subordinate_act = exec_provider_2.actions['SubordinateContext2']
with qtbot.waitSignal(executor_2.sig_run_invocation) as sig:
subordinate_act.trigger()
subord_executor_name, handler_name, run_input, exec_conf = sig.args[0]
available_executors = executors_per_conf[('ext1', 'SubordinateContext2')]
executor_name, default_conf, _, handler = available_executors[0]
assert subord_executor_name == executor_name
assert handler_name == 'context_subordinate_context2'
actual_run_input = run_input['run_input']
metadata = run_input['metadata']
name = metadata['name']
source = metadata['source']
path = metadata['path']
context = metadata['context']
run_conf_uuid = metadata['uuid']
ext = metadata['input_extension']
contents = actual_run_input['contents']
action = actual_run_input['action']
re_run = actual_run_input['re_run']
assert contents == (f'File: {name} | Location: {path} | Source: {source} '
f'| Context: {context["name"]} | Ext: {ext} '
f'| Action: {action} | Re-run: {re_run}')
params = exec_conf['params']
working_dir = params['working_dir']
assert params['executor_params'] == default_conf
assert working_dir['source'] == WorkingDirSource.ConfigurationDirectory
assert working_dir['path'] == ''
# Invoke another executor using one of the dedicated actions
with qtbot.waitSignal(executor_2.sig_run_invocation) as sig:
subordinate_act.trigger()
used_executor_name, handler_name, run_input, exec_conf = sig.args[0]
available_executors = executors_per_conf[('ext1', 'SubordinateContext1')]
executor_name, default_conf, _, handler = available_executors[0]
assert used_executor_name == executor_name
# Switch to other run configuration and register a set of custom run
# executor parameters
exec_provider_2.switch_focus('ext3', 'AnotherSuperContext')
dialog.exec_()
# Spawn the configuration dialog
run_act = run.get_action(RunActions.Run)
run_act.trigger()
dialog = container.dialog
with qtbot.waitSignal(dialog.finished, timeout=200000):
conf_combo = dialog.configuration_combo
exec_combo = dialog.executor_combo
name_params_text = dialog.name_params_text
# Modify some options
conf_widget = dialog.current_widget
conf_widget.widgets['name_1'].setChecked(True)
conf_widget.widgets['name_2'].setChecked(False)
# Make sure that the custom configuration is stored
name_params_text.setText('CustomParams')
# Execute the configuration
buttons = dialog.bbox.buttons()
run_btn = buttons[2]
with qtbot.waitSignal(executor_1.sig_run_invocation) as sig:
qtbot.mouseClick(run_btn, Qt.LeftButton)
executor_name, _, run_input, exec_conf = sig.args[0]
# Ensure that the configuration got saved
saved_params = run.get_executor_configuration_parameters(
executor_name, 'ext3', RunContext.AnotherSuperContext)
executor_params = saved_params['params']
assert len(executor_params) == 2
# Check that the configuration passed to the executor is the same that was
# saved.
exec_conf_uuid = exec_conf['uuid']
current_saved_params = executor_params[exec_conf_uuid]
current_saved_params['params']['working_dir']['path'] = ''
assert current_saved_params == exec_conf
assert current_saved_params['name'] == 'CustomParams'
# Check that the run configuration points to the latest saved parameters
metadata = run_input['metadata']
run_conf_uuid = metadata['uuid']
stored_run_params = run.get_last_used_executor_parameters(run_conf_uuid)
assert stored_run_params['executor'] == executor_name
assert stored_run_params['selected'] == exec_conf_uuid
# Check deleting a parameters config
current_exec_params = container.get_conf('parameters')[executor_name]
current_ext_ctx_params = (
current_exec_params[('ext3', RunContext.AnotherSuperContext)]['params']
)
assert current_ext_ctx_params != {} # Check params to delete are present
container.delete_executor_configuration_parameters(
executor_name, 'ext3', RunContext.AnotherSuperContext, exec_conf_uuid
)
new_exec_params = container.get_conf('parameters')[executor_name]
new_ext_ctx_params = (
new_exec_params[('ext3', RunContext.AnotherSuperContext)]['params']
)
assert len(new_ext_ctx_params) == 1
# Check that adding new parameters preserves the previous ones
current_exec_params = container.get_conf('parameters')[executor_name]
assert (
len(
current_exec_params[("ext1", RunContext.RegisteredContext)][
"params"
]
)
== 2
) # Check that we have one config in this context
new_exec_conf_uuid = str(uuid4())
new_params = StoredRunExecutorParameters(
params={
new_exec_conf_uuid: ExtendedRunExecutionParameters(
uuid=new_exec_conf_uuid,
name='Foo',
params=RunExecutionParameters(
WorkingDirOpts(source=WorkingDirSource.CurrentDirectory)
),
file_uuid=None
)
}
)
container.set_executor_configuration_parameters(
executor_name, 'ext1', RunContext.RegisteredContext, new_params
)
new_exec_params = container.get_conf('parameters')[executor_name]
assert (
len(
new_exec_params[('ext1', RunContext.RegisteredContext)]['params']
) == 3
) # Now we should have two configs in the same context
# Test teardown functions
executor_1.on_run_teardown(run)
executor_2.on_run_teardown(run)
exec_provider_1.on_run_teardown(run)
exec_provider_2.on_run_teardown(run)
| MetaExampleRunExecutor |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/isinstance2.py | {
"start": 345,
"end": 991
} | class ____(Document):
pass
def func1() -> Union[int, DbModel]:
return DbModel()
# This should not generate an error even though DbModel is
# derived from an unknown base class.
isinstance(func1(), int)
def func2(obj: object, typ: type):
return isinstance(obj, typ)
def func3(obj: float):
if isinstance(obj, float):
reveal_type(obj, expected_text="float")
else:
reveal_type(obj, expected_text="int")
T = TypeVar("T", bound=float)
def func4(t: type[T]):
if issubclass(t, float):
reveal_type(t, expected_text="type[float]*")
else:
reveal_type(t, expected_text="type[int]*")
| DbModel |
python | huggingface__transformers | src/transformers/models/cwm/modeling_cwm.py | {
"start": 15465,
"end": 15547
} | class ____(BaseModelOutputWithPast):
pass
@auto_docstring
| CwmModelOutputWithPast |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.