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 | scipy__scipy | scipy/fftpack/tests/test_basic.py | {
"start": 12099,
"end": 14596
} | class ____:
def setup_method(self):
np.random.seed(1234)
def test_definition(self):
x = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
y = fftn(np.array(x, np.float32))
assert_(y.dtype == np.complex64,
msg="double precision output with single precision")
y_r = np.array(fftn(x), np.complex64)
assert_array_almost_equal_nulp(y, y_r)
@pytest.mark.parametrize('size', SMALL_COMPOSITE_SIZES + SMALL_PRIME_SIZES)
def test_size_accuracy_small(self, size):
rng = np.random.default_rng(1234)
x = rng.random((size, size)) + 1j*rng.random((size, size))
y1 = fftn(x.real.astype(np.float32))
y2 = fftn(x.real.astype(np.float64)).astype(np.complex64)
assert_equal(y1.dtype, np.complex64)
assert_array_almost_equal_nulp(y1, y2, 2000)
@pytest.mark.parametrize('size', LARGE_COMPOSITE_SIZES + LARGE_PRIME_SIZES)
def test_size_accuracy_large(self, size):
rand = np.random.default_rng(1234)
x = rand.random((size, 3)) + 1j*rand.random((size, 3))
y1 = fftn(x.real.astype(np.float32))
y2 = fftn(x.real.astype(np.float64)).astype(np.complex64)
assert_equal(y1.dtype, np.complex64)
assert_array_almost_equal_nulp(y1, y2, 2000)
def test_definition_float16(self):
x = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
y = fftn(np.array(x, np.float16))
assert_equal(y.dtype, np.complex64)
y_r = np.array(fftn(x), np.complex64)
assert_array_almost_equal_nulp(y, y_r)
@pytest.mark.parametrize('size', SMALL_COMPOSITE_SIZES + SMALL_PRIME_SIZES)
def test_float16_input_small(self, size):
rng = np.random.default_rng(1234)
x = rng.random((size, size)) + 1j * rng.random((size, size))
y1 = fftn(x.real.astype(np.float16))
y2 = fftn(x.real.astype(np.float64)).astype(np.complex64)
assert_equal(y1.dtype, np.complex64)
assert_array_almost_equal_nulp(y1, y2, 5e5)
@pytest.mark.parametrize('size', LARGE_COMPOSITE_SIZES + LARGE_PRIME_SIZES)
def test_float16_input_large(self, size):
rng = np.random.default_rng(1234)
x = rng.random((size, 3)) + 1j*rng.random((size, 3))
y1 = fftn(x.real.astype(np.float16))
y2 = fftn(x.real.astype(np.float64)).astype(np.complex64)
assert_equal(y1.dtype, np.complex64)
assert_array_almost_equal_nulp(y1, y2, 2e6)
| TestFftnSingle |
python | django__django | tests/apps/tests.py | {
"start": 15460,
"end": 15545
} | class ____:
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
| Stub |
python | tensorflow__tensorflow | tensorflow/python/ops/linalg/linear_operator_addition.py | {
"start": 12253,
"end": 15681
} | class ____(_Adder):
""""Handles additions resulting in a `LinearOperatorFullMatrix`."""
def can_add(self, op1, op2): # pylint: disable=unused-argument
return isinstance(op1, linear_operator.LinearOperator) and isinstance(
op2, linear_operator.LinearOperator)
def _add(self, op1, op2, operator_name, hints):
if _type(op1) in _EFFICIENT_ADD_TO_TENSOR:
op_add_to_tensor, op_other = op1, op2
else:
op_add_to_tensor, op_other = op2, op1
return linear_operator_full_matrix.LinearOperatorFullMatrix(
matrix=op_add_to_tensor.add_to_tensor(op_other.to_dense()),
is_non_singular=hints.is_non_singular,
is_self_adjoint=hints.is_self_adjoint,
is_positive_definite=hints.is_positive_definite,
name=operator_name)
################################################################################
# Constants designating types of LinearOperators
################################################################################
# Type name constants for LinearOperator classes.
_IDENTITY = "identity"
_SCALED_IDENTITY = "scaled_identity"
_DIAG = "diag"
_TRIL = "tril"
_MATRIX = "matrix"
# Groups of operators.
_DIAG_LIKE = {_DIAG, _IDENTITY, _SCALED_IDENTITY}
_IDENTITY_FAMILY = {_IDENTITY, _SCALED_IDENTITY}
# operators with an efficient .add_to_tensor() method.
_EFFICIENT_ADD_TO_TENSOR = _DIAG_LIKE
# Supported LinearOperator classes.
SUPPORTED_OPERATORS = [
linear_operator_diag.LinearOperatorDiag,
linear_operator_lower_triangular.LinearOperatorLowerTriangular,
linear_operator_full_matrix.LinearOperatorFullMatrix,
linear_operator_identity.LinearOperatorIdentity,
linear_operator_identity.LinearOperatorScaledIdentity
]
def _type(operator):
"""Returns the type name constant (e.g. _TRIL) for operator."""
if isinstance(operator, linear_operator_diag.LinearOperatorDiag):
return _DIAG
if isinstance(operator,
linear_operator_lower_triangular.LinearOperatorLowerTriangular):
return _TRIL
if isinstance(operator, linear_operator_full_matrix.LinearOperatorFullMatrix):
return _MATRIX
if isinstance(operator, linear_operator_identity.LinearOperatorIdentity):
return _IDENTITY
if isinstance(operator,
linear_operator_identity.LinearOperatorScaledIdentity):
return _SCALED_IDENTITY
raise TypeError(f"Expected operator to be one of [LinearOperatorDiag, "
f"LinearOperatorLowerTriangular, LinearOperatorFullMatrix, "
f"LinearOperatorIdentity, LinearOperatorScaledIdentity]. "
f"Received: {operator}")
################################################################################
# Addition tiers:
# We attempt to use Adders in tier K before K+1.
#
# Organize tiers to
# (i) reduce O(..) complexity of forming final operator, and
# (ii) produce the "most efficient" final operator.
# Dev notes:
# * Results of addition at tier K will be added at tier K or higher.
# * Tiers may change, and we warn the user that it may change.
################################################################################
# Note that the final tier, _AddAndReturnMatrix, will convert everything to a
# dense matrix. So it is sometimes very inefficient.
_DEFAULT_ADDITION_TIERS = [
[_AddAndReturnScaledIdentity()],
[_AddAndReturnDiag()],
[_AddAndReturnTriL()],
[_AddAndReturnMatrix()],
]
| _AddAndReturnMatrix |
python | django-import-export__django-import-export | tests/core/tests/test_base_formats.py | {
"start": 8318,
"end": 8596
} | class ____(TestCase):
def setUp(self):
self.format = base_formats.TextFormat()
def test_get_read_mode(self):
self.assertEqual("r", self.format.get_read_mode())
def test_is_binary(self):
self.assertFalse(self.format.is_binary())
| TextFormatTest |
python | tornadoweb__tornado | tornado/test/concurrent_test.py | {
"start": 1005,
"end": 1548
} | class ____(AsyncTestCase):
def test_future_set_result_unless_cancelled(self):
fut = Future() # type: Future[int]
future_set_result_unless_cancelled(fut, 42)
self.assertEqual(fut.result(), 42)
self.assertFalse(fut.cancelled())
fut = Future()
fut.cancel()
is_cancelled = fut.cancelled()
future_set_result_unless_cancelled(fut, 42)
self.assertEqual(fut.cancelled(), is_cancelled)
if not is_cancelled:
self.assertEqual(fut.result(), 42)
| MiscFutureTest |
python | numba__numba | numba/core/datamodel/testing.py | {
"start": 111,
"end": 3125
} | class ____(unittest.TestCase):
"""
Test the implementation of a DataModel for a frontend type.
"""
fe_type = NotImplemented
def setUp(self):
self.module = ir.Module()
self.datamodel = datamodel.default_manager[self.fe_type]
def test_as_arg(self):
"""
- Is as_arg() and from_arg() implemented?
- Are they the inverse of each other?
"""
fnty = ir.FunctionType(ir.VoidType(), [])
function = ir.Function(self.module, fnty, name="test_as_arg")
builder = ir.IRBuilder()
builder.position_at_end(function.append_basic_block())
undef_value = ir.Constant(self.datamodel.get_value_type(), None)
args = self.datamodel.as_argument(builder, undef_value)
self.assertIsNot(args, NotImplemented, "as_argument returned "
"NotImplementedError")
if isinstance(args, (tuple, list)):
def recur_tuplize(args, func=None):
for arg in args:
if isinstance(arg, (tuple, list)):
yield tuple(recur_tuplize(arg, func=func))
else:
if func is None:
yield arg
else:
yield func(arg)
argtypes = tuple(recur_tuplize(args, func=lambda x: x.type))
exptypes = tuple(recur_tuplize(
self.datamodel.get_argument_type()))
self.assertEqual(exptypes, argtypes)
else:
self.assertEqual(args.type,
self.datamodel.get_argument_type())
rev_value = self.datamodel.from_argument(builder, args)
self.assertEqual(rev_value.type, self.datamodel.get_value_type())
builder.ret_void() # end function
# Ensure valid LLVM generation
materialized = ll.parse_assembly(str(self.module))
str(materialized)
def test_as_return(self):
"""
- Is as_return() and from_return() implemented?
- Are they the inverse of each other?
"""
fnty = ir.FunctionType(ir.VoidType(), [])
function = ir.Function(self.module, fnty, name="test_as_return")
builder = ir.IRBuilder()
builder.position_at_end(function.append_basic_block())
undef_value = ir.Constant(self.datamodel.get_value_type(), None)
ret = self.datamodel.as_return(builder, undef_value)
self.assertIsNot(ret, NotImplemented, "as_return returned "
"NotImplementedError")
self.assertEqual(ret.type, self.datamodel.get_return_type())
rev_value = self.datamodel.from_return(builder, ret)
self.assertEqual(rev_value.type, self.datamodel.get_value_type())
builder.ret_void() # end function
# Ensure valid LLVM generation
materialized = ll.parse_assembly(str(self.module))
str(materialized)
| DataModelTester |
python | allegroai__clearml | clearml/backend_api/services/v2_13/tasks.py | {
"start": 31833,
"end": 32159
} | class ____(StringEnum):
training = "training"
testing = "testing"
inference = "inference"
data_processing = "data_processing"
application = "application"
monitor = "monitor"
controller = "controller"
optimizer = "optimizer"
service = "service"
qc = "qc"
custom = "custom"
| TaskTypeEnum |
python | tensorflow__tensorflow | tensorflow/compiler/tests/sharding_util_ops_test.py | {
"start": 24445,
"end": 28638
} | class ____(xla_test.XLATestCase, parameterized.TestCase):
@parameterized.named_parameters(
('1Tensor', create_tensor_roundtrip_graph, 1),
('2Tensor', create_tensor_roundtrip_graph, 2),
('3Tensor', create_tensor_roundtrip_graph, 3),
('4Tensor', create_tensor_roundtrip_graph, 4),
('5Tensor', create_tensor_roundtrip_graph, 5),
('6Tensor', create_tensor_roundtrip_graph, 6),
('7Tensor', create_tensor_roundtrip_graph, 7),
('8Tensor', create_tensor_roundtrip_graph, 8),
('1Resource', create_resource_roundtrip_graph, 1),
('2Resource', create_resource_roundtrip_graph, 2),
('3Resource', create_resource_roundtrip_graph, 3),
('4Resource', create_resource_roundtrip_graph, 4),
('5Resource', create_resource_roundtrip_graph, 5),
('6Resource', create_resource_roundtrip_graph, 6),
('7Resource', create_resource_roundtrip_graph, 7),
('8Resource', create_resource_roundtrip_graph, 8),
)
def testNoPadding(self, graph_fn, rank):
num_partitions = [2] * rank
shape = [4] * rank
value = np.arange(0, np.prod(shape)).reshape(shape)
for dtype in self.numeric_types:
with self.session() as sess, self.device_scope():
validate = graph_fn(sess, value, dtype, num_partitions)
result = sess.run(validate)
self.assertAllEqual(result, np.broadcast_to(True, shape))
@parameterized.named_parameters(
('1Tensor', create_tensor_roundtrip_graph, 1),
('2Tensor', create_tensor_roundtrip_graph, 2),
('3Tensor', create_tensor_roundtrip_graph, 3),
('4Tensor', create_tensor_roundtrip_graph, 4),
('5Tensor', create_tensor_roundtrip_graph, 5),
('6Tensor', create_tensor_roundtrip_graph, 6),
('7Tensor', create_tensor_roundtrip_graph, 7),
('8Tensor', create_tensor_roundtrip_graph, 8),
('1Resource', create_resource_roundtrip_graph, 1),
('2Resource', create_resource_roundtrip_graph, 2),
('3Resource', create_resource_roundtrip_graph, 3),
('4Resource', create_resource_roundtrip_graph, 4),
('5Resource', create_resource_roundtrip_graph, 5),
('6Resource', create_resource_roundtrip_graph, 6),
('7Resource', create_resource_roundtrip_graph, 7),
('8Resource', create_resource_roundtrip_graph, 8),
)
def testPartialPadding(self, graph_fn, rank):
num_partitions = [2] * rank
shape = [4] * rank
value = np.arange(0, np.prod(shape)).reshape(shape)
paddings = [2] * rank
for dtype in self.numeric_types:
with self.session() as sess, self.device_scope():
validate = graph_fn(sess, value, dtype, num_partitions, paddings)
result = sess.run(validate)
self.assertAllEqual(result, np.broadcast_to(True, shape))
@parameterized.named_parameters(
('1Tensor', create_tensor_roundtrip_graph, 1),
('2Tensor', create_tensor_roundtrip_graph, 2),
('3Tensor', create_tensor_roundtrip_graph, 3),
('4Tensor', create_tensor_roundtrip_graph, 4),
('5Tensor', create_tensor_roundtrip_graph, 5),
('6Tensor', create_tensor_roundtrip_graph, 6),
('7Tensor', create_tensor_roundtrip_graph, 7),
('8Tensor', create_tensor_roundtrip_graph, 8),
('1Resource', create_resource_roundtrip_graph, 1),
('2Resource', create_resource_roundtrip_graph, 2),
('3Resource', create_resource_roundtrip_graph, 3),
('4Resource', create_resource_roundtrip_graph, 4),
('5Resource', create_resource_roundtrip_graph, 5),
('6Resource', create_resource_roundtrip_graph, 6),
('7Resource', create_resource_roundtrip_graph, 7),
('8Resource', create_resource_roundtrip_graph, 8),
)
def testCompletePadding(self, graph_fn, rank):
num_partitions = [2] * rank
shape = [4] * rank
value = np.arange(0, np.prod(shape)).reshape(shape)
paddings = [4] * rank
for dtype in self.numeric_types:
with self.session() as sess, self.device_scope():
validate = graph_fn(sess, value, dtype, num_partitions, paddings)
result = sess.run(validate)
self.assertAllEqual(result, np.broadcast_to(True, shape))
if __name__ == '__main__':
test.main()
| XlaSplitConcatNDTest |
python | pytorch__pytorch | test/distributed/fsdp/test_hsdp_dtensor_state_dict.py | {
"start": 1059,
"end": 1670
} | class ____(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
torch.manual_seed(0)
self.net1 = nn.Sequential(nn.Linear(8, 16), nn.ReLU())
self.net2 = nn.Sequential(nn.Linear(16, 32), nn.ReLU())
self.net3 = nn.Sequential(nn.Linear(32, 64), nn.ReLU())
self.net4 = nn.Sequential(nn.ReLU(), nn.Linear(64, 8))
def forward(self, x):
return self.net4(self.net3(self.net2(self.net1(x))))
def get_input(self, device):
return torch.rand(4, 8, device=device)
# TODO: Consolidate DeviceMesh based FSDP and HSDP test cases.
| DenseModel |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_cloud_logging_sink.py | {
"start": 11443,
"end": 15107
} | class ____:
def test_template_fields(self):
operator = CloudLoggingDeleteSinkOperator(
task_id=TASK_ID,
sink_name=SINK_NAME,
project_id=PROJECT_ID,
)
assert "sink_name" in operator.template_fields
_assert_common_template_fields(operator.template_fields)
def test_missing_required_params(self):
with pytest.raises(AirflowException) as excinfo:
CloudLoggingDeleteSinkOperator(
task_id=TASK_ID,
sink_name=None,
project_id=None,
).execute(context={})
assert "Required parameters are missing" in str(excinfo.value)
@mock.patch(CLOUD_LOGGING_HOOK_PATH)
def test_delete_sink_success(self, hook_mock):
hook_instance = hook_mock.return_value
hook_instance.delete_sink.return_value = None
operator = CloudLoggingDeleteSinkOperator(
task_id=TASK_ID,
sink_name=SINK_NAME,
project_id=PROJECT_ID,
)
context = mock.MagicMock()
operator.execute(context=context)
hook_instance.delete_sink.assert_called_once()
@mock.patch(CLOUD_LOGGING_HOOK_PATH)
def test_delete_sink_raises_error(self, hook_mock):
hook_instance = hook_mock.return_value
hook_instance.delete_sink.side_effect = GoogleCloudError("Internal Error")
operator = CloudLoggingDeleteSinkOperator(
task_id=TASK_ID,
sink_name=SINK_NAME,
project_id=PROJECT_ID,
)
with pytest.raises(GoogleCloudError):
operator.execute(context=mock.MagicMock())
hook_instance.delete_sink.assert_called_once()
@mock.patch(CLOUD_LOGGING_HOOK_PATH)
def test_missing_rendered_field_raises(self, hook_mock):
with DAG(
dag_id="test_render_native",
start_date=datetime(2024, 1, 1),
render_template_as_native_obj=True,
) as dag:
operator = CloudLoggingDeleteSinkOperator(
task_id=TASK_ID,
sink_name="{{ var.value.sink_name }}",
project_id="{{ var.value.project_id }}",
dag=dag,
)
context = {
"var": {"value": {"project_id": PROJECT_ID, "sink_name": None}},
}
operator.render_template_fields(context)
with pytest.raises(
AirflowException,
match=re.escape(
"Required parameters are missing: ['sink_name']. These must be passed as keyword parameters."
),
):
operator.execute(context)
@mock.patch(CLOUD_LOGGING_HOOK_PATH)
@pytest.mark.parametrize("sink_config", create_test_cases, ids=create_test_ids)
def test_template_rendering(self, hook_mock, sink_config):
with DAG(
dag_id="test_render_native",
start_date=datetime(2024, 1, 1),
render_template_as_native_obj=True,
) as dag:
operator = CloudLoggingDeleteSinkOperator(
task_id=TASK_ID,
sink_name="{{ var.value.sink_name }}",
project_id="{{ var.value.project_id }}",
dag=dag,
)
context = {
"var": {"value": {"project_id": PROJECT_ID, "sink_name": SINK_NAME}},
}
hook_instance = hook_mock.return_value
hook_instance.delete_sink.return_value = None
operator.render_template_fields(context)
operator.execute(context)
assert operator.project_id == PROJECT_ID
assert operator.sink_name == SINK_NAME
| TestCloudLoggingDeleteSinkOperator |
python | walkccc__LeetCode | solutions/2923. Find Champion I/2923-2.py | {
"start": 0,
"end": 133
} | class ____:
def findChampion(self, grid: list[list[int]]) -> int:
return max(range(len(grid)), key=lambda x: sum(grid[x]))
| Solution |
python | pytest-dev__pytest | testing/test_assertion.py | {
"start": 53093,
"end": 70695
} | class ____:
@pytest.mark.parametrize("op", [">=", ">", "<=", "<", "=="])
def test_set_extra_item(self, op, pytester: Pytester) -> None:
pytester.makepyfile(
f"""
def test_hello():
x = set("hello x")
y = set("hello y")
assert x {op} y
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(
[
"*def test_hello():*",
f"*assert x {op} y*",
]
)
if op in [">=", ">", "=="]:
result.stdout.fnmatch_lines(
[
"*E*Extra items in the right set:*",
"*E*'y'",
]
)
if op in ["<=", "<", "=="]:
result.stdout.fnmatch_lines(
[
"*E*Extra items in the left set:*",
"*E*'x'",
]
)
@pytest.mark.parametrize("op", [">", "<", "!="])
def test_set_proper_superset_equal(self, pytester: Pytester, op) -> None:
pytester.makepyfile(
f"""
def test_hello():
x = set([1, 2, 3])
y = x.copy()
assert x {op} y
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(
[
"*def test_hello():*",
f"*assert x {op} y*",
"*E*Both sets are equal*",
]
)
def test_pytest_assertrepr_compare_integration(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
def test_hello():
x = set(range(100))
y = x.copy()
y.remove(50)
assert x == y
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(
[
"*def test_hello():*",
"*assert x == y*",
"*E*Extra items*left*",
"*E*50*",
"*= 1 failed in*",
]
)
def test_assertrepr_loaded_per_dir(pytester: Pytester) -> None:
pytester.makepyfile(test_base=["def test_base(): assert 1 == 2"])
a = pytester.mkdir("a")
a.joinpath("test_a.py").write_text("def test_a(): assert 1 == 2", encoding="utf-8")
a.joinpath("conftest.py").write_text(
'def pytest_assertrepr_compare(): return ["summary a"]', encoding="utf-8"
)
b = pytester.mkdir("b")
b.joinpath("test_b.py").write_text("def test_b(): assert 1 == 2", encoding="utf-8")
b.joinpath("conftest.py").write_text(
'def pytest_assertrepr_compare(): return ["summary b"]', encoding="utf-8"
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(
[
"*def test_a():*",
"*E*assert summary a*",
"*def test_b():*",
"*E*assert summary b*",
"*def test_base():*",
"*E*assert 1 == 2*",
]
)
def test_assertion_options(pytester: Pytester) -> None:
pytester.makepyfile(
"""
def test_hello():
x = 3
assert x == 4
"""
)
result = pytester.runpytest()
assert "3 == 4" in result.stdout.str()
result = pytester.runpytest_subprocess("--assert=plain")
result.stdout.no_fnmatch_line("*3 == 4*")
def test_triple_quoted_string_issue113(pytester: Pytester) -> None:
pytester.makepyfile(
"""
def test_hello():
assert "" == '''
'''"""
)
result = pytester.runpytest("--fulltrace")
result.stdout.fnmatch_lines(["*1 failed*"])
result.stdout.no_fnmatch_line("*SyntaxError*")
def test_traceback_failure(pytester: Pytester) -> None:
p1 = pytester.makepyfile(
"""
def g():
return 2
def f(x):
assert x == g()
def test_onefails():
f(3)
"""
)
result = pytester.runpytest(p1, "--tb=long")
result.stdout.fnmatch_lines(
[
"*test_traceback_failure.py F*",
"====* FAILURES *====",
"____*____",
"",
" def test_onefails():",
"> f(3)",
"",
"*test_*.py:6: ",
"_ _ _ *",
# "",
" def f(x):",
"> assert x == g()",
"E assert 3 == 2",
"E + where 2 = g()",
"",
"*test_traceback_failure.py:4: AssertionError",
]
)
result = pytester.runpytest(p1) # "auto"
result.stdout.fnmatch_lines(
[
"*test_traceback_failure.py F*",
"====* FAILURES *====",
"____*____",
"",
" def test_onefails():",
"> f(3)",
"",
"*test_*.py:6: ",
"",
" def f(x):",
"> assert x == g()",
"E assert 3 == 2",
"E + where 2 = g()",
"",
"*test_traceback_failure.py:4: AssertionError",
]
)
def test_exception_handling_no_traceback(pytester: Pytester) -> None:
"""Handle chain exceptions in tasks submitted by the multiprocess module (#1984)."""
p1 = pytester.makepyfile(
"""
from multiprocessing import Pool
def process_task(n):
assert n == 10
def multitask_job():
tasks = [1]
with Pool(processes=1) as pool:
pool.map(process_task, tasks)
def test_multitask_job():
multitask_job()
"""
)
pytester.syspathinsert()
result = pytester.runpytest(p1, "--tb=long")
result.stdout.fnmatch_lines(
[
"====* FAILURES *====",
"*multiprocessing.pool.RemoteTraceback:*",
"Traceback (most recent call last):",
"*assert n == 10",
"The above exception was the direct cause of the following exception:",
"> * multitask_job()",
]
)
@pytest.mark.skipif("'__pypy__' in sys.builtin_module_names")
@pytest.mark.parametrize(
"cmdline_args, warning_output",
[
(
["-OO", "-m", "pytest", "-h"],
["warning :*PytestConfigWarning:*assert statements are not executed*"],
),
(
["-OO", "-m", "pytest"],
[
"=*= warnings summary =*=",
"*PytestConfigWarning:*assert statements are not executed*",
],
),
(
["-OO", "-m", "pytest", "--assert=plain"],
[
"=*= warnings summary =*=",
"*PytestConfigWarning: ASSERTIONS ARE NOT EXECUTED and FAILING TESTS WILL PASS. "
"Are you using python -O?",
],
),
],
)
def test_warn_missing(pytester: Pytester, cmdline_args, warning_output) -> None:
pytester.makepyfile("")
result = pytester.run(sys.executable, *cmdline_args)
result.stdout.fnmatch_lines(warning_output)
def test_recursion_source_decode(pytester: Pytester) -> None:
pytester.makepyfile(
"""
def test_something():
pass
"""
)
pytester.makeini(
"""
[pytest]
python_files = *.py
"""
)
result = pytester.runpytest("--collect-only")
result.stdout.fnmatch_lines(
[
" <Module*>",
]
)
def test_AssertionError_message(pytester: Pytester) -> None:
pytester.makepyfile(
"""
def test_hello():
x,y = 1,2
assert 0, (x,y)
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(
"""
*def test_hello*
*assert 0, (x,y)*
*AssertionError: (1, 2)*
"""
)
def test_diff_newline_at_end(pytester: Pytester) -> None:
pytester.makepyfile(
r"""
def test_diff():
assert 'asdf' == 'asdf\n'
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(
r"""
*assert 'asdf' == 'asdf\n'
* - asdf
* ? -
* + asdf
"""
)
@pytest.mark.filterwarnings("default")
def test_assert_tuple_warning(pytester: Pytester) -> None:
msg = "assertion is always true"
pytester.makepyfile(
"""
def test_tuple():
assert(False, 'you shall not pass')
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines([f"*test_assert_tuple_warning.py:2:*{msg}*"])
# tuples with size != 2 should not trigger the warning
pytester.makepyfile(
"""
def test_tuple():
assert ()
"""
)
result = pytester.runpytest()
assert msg not in result.stdout.str()
def test_assert_indirect_tuple_no_warning(pytester: Pytester) -> None:
pytester.makepyfile(
"""
def test_tuple():
tpl = ('foo', 'bar')
assert tpl
"""
)
result = pytester.runpytest()
output = "\n".join(result.stdout.lines)
assert "WR1" not in output
def test_assert_with_unicode(pytester: Pytester) -> None:
pytester.makepyfile(
"""\
def test_unicode():
assert '유니코드' == 'Unicode'
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(["*AssertionError*"])
def test_raise_unprintable_assertion_error(pytester: Pytester) -> None:
pytester.makepyfile(
r"""
def test_raise_assertion_error():
raise AssertionError('\xff')
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(
[r"> raise AssertionError('\xff')", "E AssertionError: *"]
)
def test_raise_assertion_error_raising_repr(pytester: Pytester) -> None:
pytester.makepyfile(
"""
class RaisingRepr(object):
def __repr__(self):
raise Exception()
def test_raising_repr():
raise AssertionError(RaisingRepr())
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(["E AssertionError: <exception str() failed>"])
def test_issue_1944(pytester: Pytester) -> None:
pytester.makepyfile(
"""
def f():
return
assert f() == 10
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(["*1 error*"])
assert (
"AttributeError: 'Module' object has no attribute '_obj'"
not in result.stdout.str()
)
def test_exit_from_assertrepr_compare(monkeypatch) -> None:
def raise_exit(obj):
outcomes.exit("Quitting debugger")
monkeypatch.setattr(util, "istext", raise_exit)
with pytest.raises(outcomes.Exit, match="Quitting debugger"):
callequal(1, 1)
def test_assertion_location_with_coverage(pytester: Pytester) -> None:
"""This used to report the wrong location when run with coverage (#5754)."""
p = pytester.makepyfile(
"""
def test():
assert False, 1
assert False, 2
"""
)
result = pytester.runpytest(str(p))
result.stdout.fnmatch_lines(
[
"> assert False, 1",
"E AssertionError: 1",
"E assert False",
"*= 1 failed in*",
]
)
def test_reprcompare_verbose_long() -> None:
a = {f"v{i}": i for i in range(11)}
b = a.copy()
b["v2"] += 10
lines = callop("==", a, b, verbose=2)
assert lines is not None
assert lines[0] == (
"{'v0': 0, 'v1': 1, 'v2': 2, 'v3': 3, 'v4': 4, 'v5': 5, "
"'v6': 6, 'v7': 7, 'v8': 8, 'v9': 9, 'v10': 10}"
" == "
"{'v0': 0, 'v1': 1, 'v2': 12, 'v3': 3, 'v4': 4, 'v5': 5, "
"'v6': 6, 'v7': 7, 'v8': 8, 'v9': 9, 'v10': 10}"
)
@pytest.mark.parametrize("enable_colors", [True, False])
@pytest.mark.parametrize(
("test_code", "expected_lines"),
(
(
"""
def test():
assert [0, 1] == [0, 2]
""",
[
"{bold}{red}E At index 1 diff: {reset}{number}1{hl-reset}{endline} != {reset}{number}2*",
"{bold}{red}E {light-red}- 2,{hl-reset}{endline}{reset}",
"{bold}{red}E {light-green}+ 1,{hl-reset}{endline}{reset}",
],
),
(
"""
def test():
assert {f"number-is-{i}": i for i in range(1, 6)} == {
f"number-is-{i}": i for i in range(5)
}
""",
[
"{bold}{red}E Common items:{reset}",
"{bold}{red}E {reset}{{{str}'{hl-reset}{str}number-is-1{hl-reset}{str}'{hl-reset}: {number}1*",
"{bold}{red}E Left contains 1 more item:{reset}",
"{bold}{red}E {reset}{{{str}'{hl-reset}{str}number-is-5{hl-reset}{str}'{hl-reset}: {number}5*",
"{bold}{red}E Right contains 1 more item:{reset}",
"{bold}{red}E {reset}{{{str}'{hl-reset}{str}number-is-0{hl-reset}{str}'{hl-reset}: {number}0*",
"{bold}{red}E {reset}{light-gray} {hl-reset} {{{endline}{reset}",
"{bold}{red}E {light-gray} {hl-reset} 'number-is-1': 1,{endline}{reset}",
"{bold}{red}E {light-green}+ 'number-is-5': 5,{hl-reset}{endline}{reset}",
],
),
(
"""
def test():
assert "abcd" == "abce"
""",
[
"{bold}{red}E {reset}{light-red}- abce{hl-reset}{endline}{reset}",
"{bold}{red}E {light-green}+ abcd{hl-reset}{endline}{reset}",
],
),
),
)
def test_comparisons_handle_colors(
pytester: Pytester, color_mapping, enable_colors, test_code, expected_lines
) -> None:
p = pytester.makepyfile(test_code)
result = pytester.runpytest(
f"--color={'yes' if enable_colors else 'no'}", "-vv", str(p)
)
formatter = (
color_mapping.format_for_fnmatch
if enable_colors
else color_mapping.strip_colors
)
result.stdout.fnmatch_lines(formatter(expected_lines), consecutive=False)
def test_fine_grained_assertion_verbosity(pytester: Pytester):
long_text = "Lorem ipsum dolor sit amet " * 10
p = pytester.makepyfile(
f"""
def test_ok():
pass
def test_words_fail():
fruits1 = ["banana", "apple", "grapes", "melon", "kiwi"]
fruits2 = ["banana", "apple", "orange", "melon", "kiwi"]
assert fruits1 == fruits2
def test_numbers_fail():
number_to_text1 = {{str(x): x for x in range(5)}}
number_to_text2 = {{str(x * 10): x * 10 for x in range(5)}}
assert number_to_text1 == number_to_text2
def test_long_text_fail():
long_text = "{long_text}"
assert "hello world" in long_text
"""
)
pytester.makeini(
"""
[pytest]
verbosity_assertions = 2
"""
)
result = pytester.runpytest(p)
result.stdout.fnmatch_lines(
[
f"{p.name} .FFF [100%]",
"E At index 2 diff: 'grapes' != 'orange'",
"E Full diff:",
"E [",
"E 'banana',",
"E 'apple',",
"E - 'orange',",
"E ? ^ ^^",
"E + 'grapes',",
"E ? ^ ^ +",
"E 'melon',",
"E 'kiwi',",
"E ]",
"E Full diff:",
"E {",
"E '0': 0,",
"E - '10': 10,",
"E ? - -",
"E + '1': 1,",
"E - '20': 20,",
"E ? - -",
"E + '2': 2,",
"E - '30': 30,",
"E ? - -",
"E + '3': 3,",
"E - '40': 40,",
"E ? - -",
"E + '4': 4,",
"E }",
f"E AssertionError: assert 'hello world' in '{long_text}'",
]
)
def test_full_output_vvv(pytester: Pytester) -> None:
pytester.makepyfile(
r"""
def crash_helper(m):
assert 1 == 2
def test_vvv():
crash_helper(500 * "a")
"""
)
result = pytester.runpytest("")
# without -vvv, the passed args are truncated
expected_non_vvv_arg_line = "m = 'aaaaaaaaaaaaaaa*..aaaaaaaaaaaa*"
result.stdout.fnmatch_lines(
[
expected_non_vvv_arg_line,
"test_full_output_vvv.py:2: AssertionError",
],
)
# double check that the untruncated part is not in the output
expected_vvv_arg_line = "m = '{}'".format(500 * "a")
result.stdout.no_fnmatch_line(expected_vvv_arg_line)
# but with "-vvv" the args are not truncated
result = pytester.runpytest("-vvv")
result.stdout.fnmatch_lines(
[
expected_vvv_arg_line,
"test_full_output_vvv.py:2: AssertionError",
]
)
result.stdout.no_fnmatch_line(expected_non_vvv_arg_line)
| TestSetAssertions |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-iterable/source_iterable/streams.py | {
"start": 12687,
"end": 12992
} | class ____(IterableExportStreamAdjustableRange, ABC):
def get_json_schema(self) -> Mapping[str, Any]:
"""All child stream share the same 'events' schema"""
return ResourceSchemaLoader(package_name_from_class(self.__class__)).get_schema("events")
| IterableExportEventsStreamAdjustableRange |
python | qdrant__qdrant-client | qdrant_client/local/json_path_parser.py | {
"start": 84,
"end": 195
} | class ____(str, Enum):
KEY = "key"
INDEX = "index"
WILDCARD_INDEX = "wildcard_index"
| JsonPathItemType |
python | pytorch__pytorch | test/test_mps.py | {
"start": 396062,
"end": 401567
} | class ____(TestCaseMPS):
def test_constant_pad(self):
m = torch.nn.ConstantPad2d((-2, -2, -2, -2), 3.5)
input_cpu = torch.randn(1, 16, 16, 16)
input_mps = input_cpu.detach().clone().to("mps")
r_cpu = m(input_cpu)
r_mps = m(input_mps)
self.assertEqual(r_cpu, r_mps.to("cpu"))
# Arbitrary input dimensions
pad = (1, 1, 0, 0, 0, 0)
value = 3.5
input_cpu = torch.randn((1, 1, 3, 3, 3, 3, 3, 3, 3, 3))
input_mps = input_cpu.detach().clone().to("mps")
r_cpu = F.pad(input_cpu, pad=pad, value=value)
r_mps = F.pad(input_mps, pad=pad, value=value)
self.assertEqual(r_cpu, r_mps.to("cpu"))
def test_circular_pad(self):
# https://github.com/pytorch/pytorch/issues/80856
k_cpu = torch.ones(3, 3, 9, 9)
k_mps = k_cpu.detach().clone().to("mps")
x_cpu = torch.rand(1, 3, 32, 32)
x_mps = x_cpu.detach().clone().to("mps")
x_pad_cpu = F.pad(x_cpu, (2, 2, 2, 2), mode='circular')
x_pad_mps = F.pad(x_mps, (2, 2, 2, 2), mode='circular')
y_cpu = F.conv2d(x_pad_cpu, k_cpu)
y_mps = F.conv2d(x_pad_mps, k_mps)
self.assertEqual(y_cpu, y_mps.cpu())
def test_constant_pad_4d_warning(self):
inputCPU = torch.rand((1, 2, 2, 2, 1, 1))
inputMPS = inputCPU.detach().clone().to('mps')
outputCPU = F.pad(inputCPU, [0, 0, 0, 0, 0, 0, 1, 0])
outputMPS = F.pad(inputMPS, [0, 0, 0, 0, 0, 0, 1, 0])
self.assertEqual(outputCPU, outputMPS)
def test_pad(self):
def helper(shape, padding, op, value=0):
inputCPU = torch.randn(shape, device='cpu', dtype=torch.float, requires_grad=True)
inputCPU.retain_grad()
inputMPS = inputCPU.detach().clone().to('mps').requires_grad_()
if (op in [nn.ConstantPad1d, nn.ConstantPad2d, nn.ConstantPad3d]):
padCriteria = op(padding, value)
else:
padCriteria = op(padding)
outputCPU = padCriteria(inputCPU)
outputMPS = padCriteria(inputMPS)
self.assertEqual(outputCPU, outputMPS)
# backward pass (chose 0.6 just to have the grad_output != 1)
outputCPU.backward(gradient=torch.full_like(outputCPU, 0.6))
outputMPS.backward(gradient=torch.full_like(outputMPS, 0.6))
self.assertEqual(inputCPU.grad, inputMPS.grad)
# 1D Padding
helper((2, 4, 3), 2, nn.ReflectionPad1d)
# verify if a change in shape of input would cause problems with graph caching
helper((2, 4, 4), (1, 3), nn.ReflectionPad1d)
# Replication 1D
helper((2, 1, 6), 3, nn.ReplicationPad1d)
# Constant Pad 1D
helper((2, 3, 4), 2, nn.ConstantPad1d)
# Constant Pad 1D with single dimension input
helper((16), (1, 2), nn.ConstantPad1d)
# 2D Padding
helper((1, 2, 3, 4), (1, 1, 2, 0), nn.ReflectionPad2d)
# verify if a change in shape of input would cause problems with graph caching
helper((2, 4, 3, 4), (1, 1, 2, 0), nn.ReflectionPad2d)
# this should make the padding (2, 2, 2, 2)
helper((2, 1, 6, 8), 2, nn.ReplicationPad2d)
# verify if a change in shape of padding would cause problems with graph caching
helper((2, 1, 6, 8), (2, 4, 3, 5), nn.ReplicationPad2d)
# Constant Pad 2D
helper((2, 1, 6, 8), (2, 4, 3, 5), nn.ConstantPad2d)
# input size < pad size
helper((1, 2, 3), (0, 0, 0, 1), nn.ConstantPad2d)
# pad dims < input dims
helper((50, 9, 300), (0, 0, 0, 31), nn.ConstantPad2d)
# pad dims == input dims
helper((1, 3), (0, 2, 0, 1), nn.ConstantPad2d)
# input.numel() == 0 but output.numel() > 0
helper((0, 3, 3), (1, 1, 1, 1, 1, 1), nn.ConstantPad2d)
# pad dims < input dims - 2
helper((1, 2, 3, 4), (1, 2), nn.ConstantPad2d)
# 3D Padding
helper((2, 4, 6, 8, 4), (1, 3, 3, 5, 3, 4), nn.ReflectionPad3d)
# verify if a change in shape of padding would cause problems with graph caching
helper((2, 4, 6, 8, 4), (1, 3, 3, 5, 3, 4), nn.ReplicationPad3d)
# case where input_d == pad_front/back for ReplicationPad3d
helper((3, 4, 5, 6, 7), (1, 2, 3, 4, 5, 6), nn.ReplicationPad3d)
# Constant Pad 3D
helper((2, 4, 6, 8, 4), (1, 3, 3, 5, 3, 4), nn.ConstantPad3d)
# input size < pad size
helper((2, 4, 6), (1, 3, 3, 5, 3, 4), nn.ConstantPad3d)
# check the workaround for the right padding bug in Monterey
helper((1, 2, 2, 2, 2), (0, 1), nn.ConstantPad3d)
def test_constant_pad_nd_preserves_memory_format(self):
nchw_tensor = torch.rand((1, 2, 5, 3))
nchw_padded = torch.constant_pad_nd(nchw_tensor, [1, 2], 0.5)
self.assertTrue(nchw_padded.is_contiguous(memory_format=torch.contiguous_format))
nhwc_tensor = nchw_tensor.contiguous(memory_format=torch.channels_last)
nhwc_padded = torch.constant_pad_nd(nhwc_tensor, [1, 2], 0.5)
self.assertTrue(nhwc_padded.is_contiguous(memory_format=torch.channels_last))
def test_constant_pad_nd_with_empty_pad(self):
# Empty constant pad is no-op
# See https://github.com/pytorch/pytorch/issues/161066
input_mps = torch.randn((2, 3, 4), device="mps")
output_mps = torch.constant_pad_nd(input_mps, [])
self.assertEqual(output_mps, input_mps)
| TestPad |
python | huggingface__transformers | tests/models/mvp/test_modeling_mvp.py | {
"start": 23349,
"end": 31153
} | class ____:
def __init__(
self,
parent,
vocab_size=99,
batch_size=13,
d_model=16,
decoder_seq_length=7,
is_training=True,
is_decoder=True,
use_attention_mask=True,
use_cache=False,
use_labels=True,
decoder_start_token_id=2,
decoder_ffn_dim=32,
decoder_layers=2,
encoder_attention_heads=4,
decoder_attention_heads=4,
max_position_embeddings=30,
is_encoder_decoder=False,
pad_token_id=0,
bos_token_id=1,
eos_token_id=2,
scope=None,
):
self.parent = parent
self.batch_size = batch_size
self.decoder_seq_length = decoder_seq_length
# For common tests
self.seq_length = self.decoder_seq_length
self.is_training = is_training
self.use_attention_mask = use_attention_mask
self.use_labels = use_labels
self.vocab_size = vocab_size
self.d_model = d_model
self.hidden_size = d_model
self.num_hidden_layers = decoder_layers
self.decoder_layers = decoder_layers
self.decoder_ffn_dim = decoder_ffn_dim
self.encoder_attention_heads = encoder_attention_heads
self.decoder_attention_heads = decoder_attention_heads
self.num_attention_heads = decoder_attention_heads
self.eos_token_id = eos_token_id
self.bos_token_id = bos_token_id
self.pad_token_id = pad_token_id
self.decoder_start_token_id = decoder_start_token_id
self.use_cache = use_cache
self.max_position_embeddings = max_position_embeddings
self.is_encoder_decoder = is_encoder_decoder
self.scope = None
self.decoder_key_length = decoder_seq_length
self.base_model_out_len = 2
self.decoder_attention_idx = 1
def prepare_config_and_inputs(self):
input_ids = ids_tensor([self.batch_size, self.decoder_seq_length], self.vocab_size)
attention_mask = None
if self.use_attention_mask:
attention_mask = ids_tensor([self.batch_size, self.decoder_seq_length], vocab_size=2)
lm_labels = None
if self.use_labels:
lm_labels = ids_tensor([self.batch_size, self.decoder_seq_length], self.vocab_size)
config = MvpConfig(
vocab_size=self.vocab_size,
d_model=self.d_model,
encoder_layers=self.decoder_layers,
decoder_layers=self.decoder_layers,
decoder_ffn_dim=self.decoder_ffn_dim,
encoder_attention_heads=self.encoder_attention_heads,
decoder_attention_heads=self.decoder_attention_heads,
eos_token_id=self.eos_token_id,
bos_token_id=self.bos_token_id,
use_cache=self.use_cache,
pad_token_id=self.pad_token_id,
decoder_start_token_id=self.decoder_start_token_id,
max_position_embeddings=self.max_position_embeddings,
is_encoder_decoder=self.is_encoder_decoder,
)
return (
config,
input_ids,
attention_mask,
lm_labels,
)
def prepare_config_and_inputs_for_decoder(self):
(
config,
input_ids,
attention_mask,
lm_labels,
) = self.prepare_config_and_inputs()
encoder_hidden_states = floats_tensor([self.batch_size, self.decoder_seq_length, self.hidden_size])
encoder_attention_mask = ids_tensor([self.batch_size, self.decoder_seq_length], vocab_size=2)
return (
config,
input_ids,
attention_mask,
encoder_hidden_states,
encoder_attention_mask,
lm_labels,
)
def create_and_check_decoder_model_past(
self,
config,
input_ids,
attention_mask,
lm_labels,
):
config.use_cache = True
model = MvpDecoder(config=config).to(torch_device).eval()
# first forward pass
outputs = model(input_ids, use_cache=True)
outputs_use_cache_conf = model(input_ids)
outputs_no_past = model(input_ids, use_cache=False)
self.parent.assertTrue(len(outputs) == len(outputs_use_cache_conf))
self.parent.assertTrue(len(outputs) == len(outputs_no_past) + 1)
past_key_values = outputs["past_key_values"]
# create hypothetical next token and extent to next_input_ids
next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size)
# append to next input_ids and
next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
output_from_no_past = model(next_input_ids)["last_hidden_state"]
output_from_past = model(next_tokens, past_key_values=past_key_values)["last_hidden_state"]
# select random slice
random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
output_from_no_past_slice = output_from_no_past[:, next_input_ids.shape[-1] - 1, random_slice_idx].detach()
output_from_past_slice = output_from_past[:, 0, random_slice_idx].detach()
# test that outputs are equal for slice
assert torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3)
def create_and_check_decoder_model_attention_mask_past(
self,
config,
input_ids,
attention_mask,
lm_labels,
):
model = MvpDecoder(config=config).to(torch_device).eval()
# create attention mask
attn_mask = torch.ones(input_ids.shape, dtype=torch.long, device=torch_device)
half_seq_length = input_ids.shape[-1] // 2
attn_mask[:, half_seq_length:] = 0
# first forward pass
past_key_values = model(input_ids, attention_mask=attn_mask, use_cache=True)["past_key_values"]
# create hypothetical next token and extent to next_input_ids
next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size)
# change a random masked slice from input_ids
random_seq_idx_to_change = ids_tensor((1,), half_seq_length).item() + 1
random_other_next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size).squeeze(-1)
input_ids[:, -random_seq_idx_to_change] = random_other_next_tokens
# append to next input_ids and attn_mask
next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
attn_mask = torch.cat(
[attn_mask, torch.ones((attn_mask.shape[0], 1), dtype=torch.long, device=torch_device)],
dim=1,
)
# get two different outputs
output_from_no_past = model(next_input_ids, attention_mask=attn_mask)["last_hidden_state"]
output_from_past = model(
next_tokens, attention_mask=attn_mask, past_key_values=past_key_values, use_cache=True
)["last_hidden_state"]
# select random slice
random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
output_from_no_past_slice = output_from_no_past[:, next_input_ids.shape[-1] - 1, random_slice_idx].detach()
output_from_past_slice = output_from_past[:, 0, random_slice_idx].detach()
# test that outputs are equal for slice
assert torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3)
def prepare_config_and_inputs_for_common(self):
config_and_inputs = self.prepare_config_and_inputs()
(
config,
input_ids,
attention_mask,
lm_labels,
) = config_and_inputs
inputs_dict = {
"input_ids": input_ids,
"attention_mask": attention_mask,
}
return config, inputs_dict
@require_torch
| MvpStandaloneDecoderModelTester |
python | Lightning-AI__lightning | tests/tests_pytorch/callbacks/test_finetuning_callback.py | {
"start": 8274,
"end": 10524
} | class ____(BaseFinetuning):
def freeze_before_training(self, pl_module: LightningModule):
self.freeze(pl_module.layer)
def finetune_function(self, pl_module: LightningModule, epoch: int, optimizer: Optimizer):
self.unfreeze_and_add_param_group(pl_module.layer[epoch + 1], optimizer)
def test_base_finetuning_internal_optimizer_metadata(tmp_path):
"""Test the param_groups updates are properly saved within the internal state of the BaseFinetuning Callbacks."""
seed_everything(42)
class FreezeModel(BoringModel):
def __init__(self):
super().__init__()
self.layer = nn.Sequential(
nn.Linear(32, 32, bias=False),
nn.Linear(32, 32, bias=True),
nn.Linear(32, 32, bias=False),
nn.Linear(32, 32, bias=True),
nn.Linear(32, 32, bias=False),
nn.Linear(32, 2, bias=True),
)
def forward(self, x):
return self.layer(x)
def configure_optimizers(self):
return torch.optim.SGD(self.layer[0].parameters(), lr=0.1)
cb = OnEpochLayerFinetuning()
chk = ModelCheckpoint(dirpath=tmp_path, save_last=True)
model = FreezeModel()
trainer = Trainer(default_root_dir=tmp_path, max_epochs=5, limit_train_batches=1, callbacks=[cb, chk])
trainer.fit(model)
assert len(cb._internal_optimizer_metadata[0]) == 6
assert cb._internal_optimizer_metadata[0][0]["params"] == ["layer.0.weight"]
assert cb._internal_optimizer_metadata[0][1]["params"] == ["layer.1.weight", "layer.1.bias"]
assert cb._internal_optimizer_metadata[0][2]["params"] == ["layer.2.weight"]
assert cb._internal_optimizer_metadata[0][3]["params"] == ["layer.3.weight", "layer.3.bias"]
assert cb._internal_optimizer_metadata[0][4]["params"] == ["layer.4.weight"]
assert cb._internal_optimizer_metadata[0][5]["params"] == ["layer.5.weight", "layer.5.bias"]
model = FreezeModel()
cb = OnEpochLayerFinetuning()
trainer = Trainer(default_root_dir=tmp_path, max_epochs=10, callbacks=[cb])
with pytest.raises(IndexError, match="index 6 is out of range"):
trainer.fit(model, ckpt_path=chk.last_model_path)
| OnEpochLayerFinetuning |
python | pandas-dev__pandas | asv_bench/benchmarks/arithmetic.py | {
"start": 10903,
"end": 11405
} | class ____:
params = offsets
param_names = ["offset"]
def setup(self, offset):
N = 10000
rng = date_range(start="1/1/2000", periods=N, freq="min")
self.rng = rng
self.ser = Series(rng)
def time_add_series_offset(self, offset):
with warnings.catch_warnings(record=True):
self.ser + offset
def time_add_dti_offset(self, offset):
with warnings.catch_warnings(record=True):
self.rng + offset
| OffsetArrayArithmetic |
python | tensorflow__tensorflow | tensorflow/python/distribute/cross_device_ops_test.py | {
"start": 5789,
"end": 58309
} | class ____(test.TestCase, parameterized.TestCase):
def setUp(self):
super().setUp()
# Enabling collectives can be done in "setUpClass", but requires using
# different collective_keys in different tests as collectives are reused
# across tests. Always resetting collective ops before each test offers
# better test isolation.
global_mpr_1p.runner.run(enable_collective_ops)
global_mpr_2p.runner.run(enable_collective_ops)
def make_collective(self, num_processes, gpu_per_process):
"""Returns collectives and other info to be used in tests.
Args:
num_processes: an integer indicating the number of processes that
participate in the collective.
gpu_per_process: number of GPUs (0 if no GPUs) used by each process.
Returns:
A tuple of (collective, devices, pid) where collective is a instance
of `CollectiveAllReduce`, devices are a list of local devices (str)
attached to the current process, and pid is the id of this process among
all participant processes.
"""
cluster_resolver = cluster_resolver_lib.TFConfigClusterResolver()
devices = [
"/job:worker/replica:0/task:%d/device:CPU:0" % cluster_resolver.task_id
]
if gpu_per_process > 0:
devices = [
"/job:worker/replica:0/task:%d/device:GPU:%d"
% (cluster_resolver.task_id, i)
for i in range(gpu_per_process)
]
group_size = num_processes * len(devices)
collective = cross_device_ops_lib.CollectiveAllReduce(
devices=devices,
group_size=group_size,
options=collective_util.Options(),
)
return collective, devices, cluster_resolver.task_id
def as_list(self, value):
"""An utility to convert a `Mirrored`, `Tensor` or `IndexedSlices` to a list.
The reason it exists is to provide a uniformed view of returned value of
"reduce" calls, especially across tf.function boundaries. Returning
`Mirrored` from a tf.function will only evaluate the primary value, which
makes collective ops of non-primary device being pruned, and will eventually
cause hanging.
Args:
value: the value to convert, can be one of `Mirrored`, `Tensor` and
`IndexedSlices`.
Returns:
A list of `Tensor` or `IndexedSlices`.
"""
if isinstance(value, tensor_lib.Tensor):
return [value]
elif isinstance(value, IndexedSlices):
return [value]
elif isinstance(value, value_lib.Mirrored):
return value.values
else:
raise ValueError("unwrap: unsupported input type: %s" % type(value))
RunOptions = collections.namedtuple( # pylint: disable=invalid-name
"RunOptions",
[
"mode", # A list of str from ["eager", "func_graph"]
"num_processes",
"gpus_per_process",
"reduce_op",
"communication_options",
"prefer_unique_instance_key",
],
)
RunOptions.__new__.__defaults__ = (
["eager", "func_graph"],
2,
0,
ReduceOp.SUM,
collective_util.Options(),
True,
)
def reduce_and_verify(self, inputs, expect, options):
"""Reduce the given `inputs` and verify the output matches `expect`.
Args:
inputs: a list of `Tensor` or `IndexedSlices`, where i-th value will be
fed to i-th replica.
expect: a `Tensor` or `IndexedSlices`. This should be the expected value
for one replica.
options: a `RunOpotions` instance.
"""
def replica_fn():
CollectiveReplicaLauncher._prefer_unique_instance_key = (
options.prefer_unique_instance_key
)
collective, devices, pid = self.make_collective(
options.num_processes, options.gpus_per_process
)
def reduce_fn():
value_fn = lambda device_idx: inputs[pid * len(devices) + device_idx]
per_replica_value = make_per_replica_value(value_fn, devices)
reduced_values = collective.reduce(
options.reduce_op,
per_replica_value,
per_replica_value,
options.communication_options,
)
if options.gpus_per_process > 1:
self.assertIsInstance(reduced_values, value_lib.Mirrored)
reduced_values = self.as_list(reduced_values)
self.assertAllEqual(devices, [v.device for v in reduced_values])
return [ops.convert_to_tensor(v) for v in reduced_values]
per_replica_expect = [ops.convert_to_tensor(expect)] * len(devices)
if "eager" in options.mode:
got = reduce_fn()
self.assertAllClose(got, per_replica_expect)
if "func_graph" in options.mode:
got = def_function.function(reduce_fn)()
self.assertAllClose(got, per_replica_expect)
get_global_mpr(options.num_processes).run(replica_fn)
def batch_reduce_and_verify(self, inputs, expect, options):
"""Batch reduce the given `inputs` and verify the output matches `expect`.
Args:
inputs: a 2-level nested list of `Tensor` or `IndexedSlices`, where i-th
value will be fed to i-th replica.
expect: a list of `Tensor` or `IndexedSlices`. This should be the expected
value for one replica.
options: a `RunOpotions` instance.
"""
def replica_fn():
CollectiveReplicaLauncher._prefer_unique_instance_key = (
options.prefer_unique_instance_key
)
collective, devices, pid = self.make_collective(
options.num_processes, options.gpus_per_process
)
def batch_reduce_fn():
batch_size = len(inputs[0])
value_dst_pairs = []
for i in range(batch_size):
def value_fn(device_idx, idx=i):
return inputs[pid * len(devices) + device_idx][idx]
per_replica_value = make_per_replica_value(value_fn, devices)
value_dst_pairs.append((per_replica_value, per_replica_value))
reduced_values = collective.batch_reduce(
options.reduce_op, value_dst_pairs, options.communication_options
)
if options.gpus_per_process > 1:
for v in reduced_values:
self.assertIsInstance(v, value_lib.Mirrored)
reduced_values = [self.as_list(v) for v in reduced_values]
for v in reduced_values:
self.assertAllEqual(devices, [t.device for t in v])
return nest.map_structure(ops.convert_to_tensor, reduced_values)
per_replica_expect = nest.map_structure(
lambda x: [ops.convert_to_tensor(x)] * len(devices), expect
)
if "eager" in options.mode:
got = batch_reduce_fn()
self.assertAllClose(got, per_replica_expect)
if "func_graph" in options.mode:
got = def_function.function(batch_reduce_fn)()
self.assertAllClose(got, per_replica_expect)
get_global_mpr(options.num_processes).run(replica_fn)
@combinations.generate(
combinations.combine(
num_processes=[1, 2],
required_gpus=[0, 1, 2],
implementation=[
CommunicationImplementation.AUTO,
CommunicationImplementation.RING,
CommunicationImplementation.NCCL,
],
reduce_op=[ReduceOp.SUM, ReduceOp.MEAN],
prefer_unique_instance_key=[True, False],
)
)
def testReduceDense(
self,
num_processes,
required_gpus,
implementation,
reduce_op,
prefer_unique_instance_key,
):
if (
required_gpus == 0
and implementation == CommunicationImplementation.NCCL
):
self.skipTest("Skip CPU + NCCL combination")
if (
num_processes != required_gpus
and implementation == CommunicationImplementation.NCCL
):
self.skipTest(
"Skip NCCL combination with mismatched process and GPU "
"count. NCCL requires physical GPUs for every process."
)
if (
num_processes != required_gpus
and implementation == CommunicationImplementation.AUTO
):
self.skipTest(
"Skip potential NCCL combination (AUTO) with mismatched "
"process and GPU count. NCCL requires physical GPUs for "
"every process."
)
options = self.RunOptions(
num_processes=num_processes,
gpus_per_process=required_gpus,
reduce_op=reduce_op,
communication_options=collective_util.Options(
implementation=implementation
),
prefer_unique_instance_key=prefer_unique_instance_key,
)
group_size = options.num_processes * (options.gpus_per_process or 1)
inputs_data = [1.0, 2.0, 3.0, 4.0]
inputs = inputs_data[0:group_size]
if group_size == 1:
expect = 1.0
if group_size == 2:
expect = 3.0 if reduce_op == ReduceOp.SUM else 1.5
elif group_size == 4:
expect = 10.0 if reduce_op == ReduceOp.SUM else 2.5
self.reduce_and_verify(inputs, expect, options)
@combinations.generate(
combinations.combine(
num_processes=[1, 2],
required_gpus=[0, 1, 2],
implementation=[
CommunicationImplementation.AUTO,
CommunicationImplementation.RING,
CommunicationImplementation.NCCL,
],
# TODO(b/166682130): add MEAN reduce once the bug is fixed.
reduce_op=ReduceOp.SUM,
prefer_unique_instance_key=[True, False],
)
)
def testReduceSparse(
self,
num_processes,
required_gpus,
implementation,
reduce_op,
prefer_unique_instance_key,
):
if (
required_gpus == 0
and implementation == CommunicationImplementation.NCCL
):
self.skipTest("Skip CPU + NCCL combination")
if (
num_processes != required_gpus
and implementation == CommunicationImplementation.NCCL
):
self.skipTest(
"Skip NCCL combination with mismatched process and GPU "
"count. NCCL requires physical GPUs for every process."
)
if (
num_processes != required_gpus
and implementation == CommunicationImplementation.AUTO
):
self.skipTest(
"Skip potential NCCL combination (AUTO) with mismatched "
"process and GPU count. NCCL requires physical GPUs for "
"every process."
)
options = self.RunOptions(
mode=["func_graph"], # Sparse reduce is not supported in eager.
num_processes=num_processes,
gpus_per_process=required_gpus,
reduce_op=reduce_op,
communication_options=collective_util.Options(
implementation=implementation
),
prefer_unique_instance_key=prefer_unique_instance_key,
)
group_size = options.num_processes * (options.gpus_per_process or 1)
inputs_data = [
IndexedSlicesValue(
values=[[1.0], [2.0]], indices=[0, 1], dense_shape=[10, 1]
),
IndexedSlicesValue(
values=[[3.0], [4.0]], indices=[1, 2], dense_shape=[10, 1]
),
IndexedSlicesValue(
values=[[5.0], [6.0]], indices=[7, 8], dense_shape=[10, 1]
),
IndexedSlicesValue(
values=[[7.0], [8.0]], indices=[3, 2], dense_shape=[10, 1]
),
]
inputs = inputs_data[0:group_size]
if group_size == 1:
expect = IndexedSlices(
values=[[1.0], [2.0]], indices=[0, 1], dense_shape=[10, 1]
)
elif group_size == 2:
expect = IndexedSlices(
values=[[1.0], [2.0], [3.0], [4.0]],
indices=[0, 1, 1, 2],
dense_shape=[10, 1],
)
elif group_size == 4:
expect = IndexedSlices(
values=[[1.0], [2.0], [3.0], [4.0], [5.0], [6.0], [7.0], [8.0]],
indices=[0, 1, 1, 2, 7, 8, 3, 2],
dense_shape=[10, 1],
)
self.reduce_and_verify(inputs, expect, options)
@combinations.generate(
combinations.combine(prefer_unique_instance_key=[True, False])
)
def testReduceSparseVariableLength(self, prefer_unique_instance_key):
# One device per process, 2 processes, 2 replicas in total.
inputs = [
IndexedSlicesValue(values=[[1.0]], indices=[0], dense_shape=[10, 1]),
IndexedSlicesValue(
values=[[2.0], [3.0], [4.0]], indices=[0, 1, 2], dense_shape=[10, 1]
),
]
expect = IndexedSlices(
values=[[1.0], [2.0], [3.0], [4.0]],
indices=[0, 0, 1, 2],
dense_shape=[10, 1],
)
self.reduce_and_verify(
inputs,
expect,
self.RunOptions(
mode=["func_graph"], # Sparse reduce is not supported in eager.
num_processes=2,
reduce_op=ReduceOp.SUM,
prefer_unique_instance_key=prefer_unique_instance_key,
),
)
@combinations.generate(
combinations.combine(
num_processes=[1, 2],
required_gpus=[0, 1, 2],
implementation=[
CommunicationImplementation.AUTO,
CommunicationImplementation.RING,
CommunicationImplementation.NCCL,
],
reduce_op=[ReduceOp.SUM, ReduceOp.MEAN],
prefer_unique_instance_key=[True, False],
)
)
def testBatchReduceDense(
self,
num_processes,
required_gpus,
implementation,
reduce_op,
prefer_unique_instance_key,
):
if (
required_gpus == 0
and implementation == CommunicationImplementation.NCCL
):
self.skipTest("Skip CPU + NCCL combination")
if (
num_processes != required_gpus
and implementation == CommunicationImplementation.NCCL
):
self.skipTest(
"Skip NCCL combination with mismatched process and GPU "
"count. NCCL requires physical GPUs for every process."
)
if (
num_processes != required_gpus
and implementation == CommunicationImplementation.AUTO
):
self.skipTest(
"Skip potential NCCL combination (AUTO) with mismatched "
"process and GPU count. NCCL requires physical GPUs for "
"every process."
)
options = self.RunOptions(
num_processes=num_processes,
gpus_per_process=required_gpus,
reduce_op=reduce_op,
communication_options=collective_util.Options(
implementation=implementation
),
prefer_unique_instance_key=prefer_unique_instance_key,
)
group_size = options.num_processes * (options.gpus_per_process or 1)
inputs_data = [[1.0, 2.0], [3.0, 4.0], [5.0, 6.0], [7.0, 8.0]]
inputs = inputs_data[0:group_size]
if group_size == 1:
expect = [1.0, 2.0]
if group_size == 2:
expect = [4.0, 6.0] if reduce_op == ReduceOp.SUM else [2.0, 3.0]
elif group_size == 4:
expect = [16.0, 20.0] if reduce_op == ReduceOp.SUM else [4.0, 5.0]
self.batch_reduce_and_verify(inputs, expect, options)
@combinations.generate(
combinations.combine(
num_processes=[1, 2],
required_gpus=[0, 1, 2],
implementation=[
CommunicationImplementation.AUTO,
CommunicationImplementation.RING,
CommunicationImplementation.NCCL,
],
# TODO(b/166682130): add MEAN reduce once the bug is fixed.
reduce_op=ReduceOp.SUM,
prefer_unique_instance_key=[True, False],
)
)
def testBatchReduceSparse(
self,
num_processes,
required_gpus,
implementation,
reduce_op,
prefer_unique_instance_key,
):
if (
required_gpus == 0
and implementation == CommunicationImplementation.NCCL
):
self.skipTest("Skip CPU + NCCL combination")
if (
num_processes != required_gpus
and implementation == CommunicationImplementation.NCCL
):
self.skipTest(
"Skip NCCL combination with mismatched process and GPU "
"count. NCCL requires physical GPUs for every process."
)
if (
num_processes != required_gpus
and implementation == CommunicationImplementation.AUTO
):
self.skipTest(
"Skip potential NCCL combination (AUTO) with mismatched "
"process and GPU count. NCCL requires physical GPUs for "
"every process."
)
options = self.RunOptions(
mode=["func_graph"], # Sparse reduce is not supported in eager.
num_processes=num_processes,
gpus_per_process=required_gpus,
reduce_op=reduce_op,
communication_options=collective_util.Options(
implementation=implementation
),
prefer_unique_instance_key=prefer_unique_instance_key,
)
group_size = options.num_processes * (options.gpus_per_process or 1)
inputs_data = (
[
IndexedSlicesValue(
values=[[1.0], [2.0]], indices=[0, 1], dense_shape=[10, 1]
),
IndexedSlicesValue(
values=[[3.0], [4.0]], indices=[1, 2], dense_shape=[5, 1]
),
],
[
IndexedSlicesValue(
values=[[5.0], [6.0]], indices=[1, 2], dense_shape=[10, 1]
),
IndexedSlicesValue(
values=[[7.0], [8.0]], indices=[0, 1], dense_shape=[5, 1]
),
],
[
IndexedSlicesValue(
values=[[9.0], [10.0]], indices=[3, 4], dense_shape=[10, 1]
),
IndexedSlicesValue(
values=[[11.0], [12.0]], indices=[3, 4], dense_shape=[5, 1]
),
],
[
IndexedSlicesValue(
values=[[13.0], [14.0]], indices=[8, 9], dense_shape=[10, 1]
),
IndexedSlicesValue(
values=[[15.0], [16.0]], indices=[3, 4], dense_shape=[5, 1]
),
],
)
inputs = inputs_data[0:group_size]
if group_size == 1:
expect = [
IndexedSlices(
values=[[1.0], [2.0]], indices=[0, 1], dense_shape=[10, 1]
),
IndexedSlices(
values=[[3.0], [4.0]], indices=[1, 2], dense_shape=[5, 1]
),
]
if group_size == 2:
expect = [
IndexedSlices(
values=[[1.0], [2.0], [5.0], [6.0]],
indices=[0, 1, 1, 2],
dense_shape=[10, 1],
),
IndexedSlices(
values=[[3.0], [4.0], [7.0], [8.0]],
indices=[1, 2, 0, 1],
dense_shape=[5, 1],
),
]
elif group_size == 4:
expect = [
IndexedSlices(
values=[
[1.0],
[2.0],
[5.0],
[6.0],
[9.0],
[10.0],
[13.0],
[14.0],
],
indices=[0, 1, 1, 2, 3, 4, 8, 9],
dense_shape=[10, 1],
),
IndexedSlices(
values=[
[3.0],
[4.0],
[7.0],
[8.0],
[11.0],
[12.0],
[15.0],
[16.0],
],
indices=[1, 2, 0, 1, 3, 4, 3, 4],
dense_shape=[5, 2],
),
]
self.batch_reduce_and_verify(inputs, expect, options)
def testBatchReduceMixedDenseAndSparse(self):
options = self.RunOptions(
num_processes=2,
gpus_per_process=0,
reduce_op=ReduceOp.SUM,
mode=["func_graph"],
)
inputs_data = [
[
1.0,
2.0,
IndexedSlicesValue(
values=[[1.0], [2.0]], indices=[0, 1], dense_shape=[10, 1]
),
IndexedSlicesValue(
values=[[3.0], [4.0]], indices=[1, 2], dense_shape=[5, 1]
),
],
[
3.0,
4.0,
IndexedSlicesValue(
values=[[5.0], [6.0]], indices=[1, 2], dense_shape=[10, 1]
),
IndexedSlicesValue(
values=[[7.0], [8.0]], indices=[0, 1], dense_shape=[5, 1]
),
],
]
expect = [
4.0,
6.0,
IndexedSlices(
values=[[1.0], [2.0], [5.0], [6.0]],
indices=[0, 1, 1, 2],
dense_shape=[10, 1],
),
IndexedSlices(
values=[[3.0], [4.0], [7.0], [8.0]],
indices=[1, 2, 0, 1],
dense_shape=[5, 1],
),
]
self.batch_reduce_and_verify(inputs_data, expect, options)
@combinations.generate(
combinations.combine(
num_processes=[1, 2],
required_gpus=[0, 1, 2],
implementation=[
CommunicationImplementation.AUTO,
CommunicationImplementation.RING,
CommunicationImplementation.NCCL,
],
reduce_op=[ReduceOp.SUM, ReduceOp.MEAN],
)
)
def testAllReduceDense(
self, num_processes, required_gpus, implementation, reduce_op
):
if (
required_gpus == 0
and implementation == CommunicationImplementation.NCCL
):
self.skipTest("Skip CPU + NCCL combination")
if (
num_processes != required_gpus
and implementation == CommunicationImplementation.NCCL
):
self.skipTest(
"Skip NCCL combination with mismatched process and GPU "
"count. NCCL requires physical GPUs for every process."
)
if (
num_processes != required_gpus
and implementation == CommunicationImplementation.AUTO
):
self.skipTest(
"Skip potential NCCL combination (AUTO) with mismatched "
"process and GPU count. NCCL requires physical GPUs for "
"every process."
)
self.skipTest(
"b/435404154: As we moved from NVIDIA CUDA base image to Ubuntu 22.04"
" with NVIDIA Driver 580 installed for RBE, this test is failing and"
" needs to be addressed as part of the bug."
)
def replica_fn():
collective, devices, _ = self.make_collective(
num_processes, required_gpus
)
options = collective_util.Options(implementation=implementation)
group_size = num_processes * (required_gpus or 1)
@def_function.function
def collective_all_reduce():
results = []
for replica_id, device in enumerate(devices):
with ops.device(device):
value = constant_op.constant(1.0)
results.append(
collective._all_reduce(reduce_op, value, replica_id, options)
)
return results
got = collective_all_reduce()
if reduce_op == ReduceOp.SUM:
expect = [1.0 * group_size] * len(devices)
elif reduce_op == ReduceOp.MEAN:
expect = [1.0] * len(devices)
self.assertAllClose(got, expect)
@def_function.function
def collective_batch_all_reduce():
results = []
for replica_id, device in enumerate(devices):
with ops.device(device):
value = (constant_op.constant(1.0), constant_op.constant(2.0))
results.append(
collective._all_reduce(reduce_op, value, replica_id, options)
)
return results
got = collective_batch_all_reduce()
if reduce_op == ReduceOp.SUM:
expect = [(1.0 * group_size, 2.0 * group_size)] * len(devices)
elif reduce_op == ReduceOp.MEAN:
expect = [(1.0, 2.0)] * len(devices)
self.assertAllClose(got, expect)
get_global_mpr(num_processes).run(replica_fn)
@combinations.generate(
combinations.combine(
num_processes=[1, 2],
required_gpus=[0, 1, 2],
implementation=[
CommunicationImplementation.AUTO,
CommunicationImplementation.RING,
CommunicationImplementation.NCCL,
],
reduce_op=[ReduceOp.SUM, ReduceOp.MEAN],
)
)
def testAllReduceSparse(
self, num_processes, required_gpus, implementation, reduce_op
):
self.skipTest(
"b/435404154: As we moved from NVIDIA CUDA base image to Ubuntu 22.04"
" with NVIDIA Driver 580 installed for RBE, this test is failing and"
" needs to be addressed as part of the bug."
)
if (
required_gpus == 0
and implementation == CommunicationImplementation.NCCL
):
self.skipTest("Skip CPU + NCCL combination")
if (
num_processes != required_gpus
and implementation == CommunicationImplementation.NCCL
):
self.skipTest(
"Skip NCCL combination with mismatched process and GPU "
"count. NCCL requires physical GPUs for every process."
)
if (
num_processes != required_gpus
and implementation == CommunicationImplementation.AUTO
):
self.skipTest(
"Skip potential NCCL combination (AUTO) with mismatched "
"process and GPU count. NCCL requires physical GPUs for "
"every process."
)
def replica_fn():
collective, devices, _ = self.make_collective(
num_processes, required_gpus
)
options = collective_util.Options(implementation=implementation)
group_size = num_processes * (required_gpus or 1)
@def_function.function
def collective_all_reduce():
results = []
for replica_id, device in enumerate(devices):
with ops.device(device):
value = IndexedSlices(
values=array_ops.identity([[1.0]]),
indices=array_ops.identity([0]),
dense_shape=array_ops.identity([5, 1]),
)
results.append(
collective._all_reduce(reduce_op, value, replica_id, options)
)
return results
got = collective_all_reduce()
if reduce_op == ReduceOp.SUM:
expect = [IndexedSlices([[1.0 * group_size]], [0], [5, 1])] * len(
devices
)
elif reduce_op == ReduceOp.MEAN:
expect = [IndexedSlices([[1.0]], [0], [5, 1])] * len(devices)
self.assertAllClose(
nest.map_structure(ops.convert_to_tensor, got),
nest.map_structure(ops.convert_to_tensor, expect),
)
@def_function.function
def collective_batch_all_reduce():
results = []
for replica_id, device in enumerate(devices):
with ops.device(device):
value = (
IndexedSlices(
array_ops.identity([[1.0]]),
array_ops.identity([0]),
array_ops.identity([5, 1]),
),
IndexedSlices(
array_ops.identity([[3.0]]),
array_ops.identity([2]),
array_ops.identity([5, 1]),
),
)
results.append(
collective._all_reduce(reduce_op, value, replica_id, options)
)
return results
got = collective_batch_all_reduce()
if reduce_op == ReduceOp.SUM:
expect = [(
IndexedSlices([[1.0 * group_size]], [0], [5, 1]),
IndexedSlices([[3.0 * group_size]], [2], [5, 1]),
)] * len(devices)
elif reduce_op == ReduceOp.MEAN:
expect = [(
IndexedSlices([[1.0]], [0], [5, 1]),
IndexedSlices([[3.0]], [2], [5, 1]),
)] * len(devices)
self.assertAllClose(
nest.map_structure(ops.convert_to_tensor, got),
nest.map_structure(ops.convert_to_tensor, expect),
)
get_global_mpr(num_processes).run(replica_fn)
@combinations.generate(
combinations.combine(
num_processes=2,
required_gpus=0,
implementation=CommunicationImplementation.AUTO,
reduce_op=ReduceOp.SUM,
)
)
def testAllReduceMixedDenseAndSparse(
self, num_processes, required_gpus, implementation, reduce_op
):
if (
num_processes != required_gpus
and implementation == CommunicationImplementation.AUTO
):
self.skipTest(
"Skip potential NCCL combination (AUTO) with mismatched "
"process and GPU count. NCCL requires physical GPUs for "
"every process."
)
def replica_fn():
collective, devices, _ = self.make_collective(
num_processes, required_gpus
)
options = collective_util.Options(implementation=implementation)
group_size = num_processes * (required_gpus or 1)
@def_function.function
def collective_batch_all_reduce():
results = []
for replica_id, device in enumerate(devices):
with ops.device(device):
value = (
IndexedSlices(
array_ops.identity([[1.0]]),
array_ops.identity([0]),
array_ops.identity([5, 1]),
),
array_ops.identity(1.0),
IndexedSlices(
array_ops.identity([[3.0]]),
array_ops.identity([2]),
array_ops.identity([5, 1]),
),
array_ops.identity(2.0),
)
results.append(
collective._all_reduce(reduce_op, value, replica_id, options)
)
return results
got = collective_batch_all_reduce()
expect = [(
IndexedSlices([[1.0 * group_size]], [0], [5, 1]),
1.0 * group_size,
IndexedSlices([[3.0 * group_size]], [2], [5, 1]),
2.0 * group_size,
)] * len(devices)
self.assertAllClose(
nest.map_structure(ops.convert_to_tensor, got),
nest.map_structure(ops.convert_to_tensor, expect),
)
get_global_mpr(num_processes).run(replica_fn)
@combinations.generate(
combinations.combine(
num_processes=[1, 2],
required_gpus=[0, 1, 2],
axis=[0, 1, 2],
func_mode=["eager", "func_graph"],
implementation=[
CommunicationImplementation.AUTO,
CommunicationImplementation.RING,
CommunicationImplementation.NCCL,
],
prefer_unique_instance_key=[True, False],
)
)
def testAllGatherSameShape(
self,
num_processes,
required_gpus,
implementation,
func_mode,
axis,
prefer_unique_instance_key,
):
if (
required_gpus == 0
and implementation == CommunicationImplementation.NCCL
):
self.skipTest("Skip CPU + NCCL combination")
if (
num_processes != required_gpus
and implementation == CommunicationImplementation.NCCL
):
self.skipTest(
"Skip NCCL combination with mismatched process and GPU "
"count. NCCL requires physical GPUs for every process."
)
if (
num_processes != required_gpus
and implementation == CommunicationImplementation.AUTO
):
self.skipTest(
"Skip potential NCCL combination (AUTO) with mismatched "
"process and GPU count. NCCL requires physical GPUs for "
"every process."
)
def replica_fn():
CollectiveReplicaLauncher._prefer_unique_instance_key = (
prefer_unique_instance_key
)
collective, devices, _ = self.make_collective(
num_processes, required_gpus
)
options = collective_util.Options(implementation=implementation)
value = constant_op.constant([[[1, 2], [1, 2]]], dtype=dtypes.float32)
def gather_fn():
per_replica_value = make_per_replica_value(value, devices)
gathered_values = collective._gather(
per_replica_value, per_replica_value, axis=axis, options=options
)
gathered_values = self.as_list(gathered_values)
# Skip checking devices in eager. In eager the device attribute doesn't
# reflect the actual device of the tensor.
if not context.executing_eagerly():
self.assertAllEqual(devices, [v.device for v in gathered_values])
return [ops.convert_to_tensor(v) for v in gathered_values]
group_size = num_processes * (required_gpus or 1)
expect = array_ops.concat([value] * group_size, axis=axis)
per_replica_expect = [ops.convert_to_tensor(expect)] * len(devices)
if func_mode == "eager":
result = gather_fn()
self.assertAllClose(result, per_replica_expect)
if func_mode == "func_graph":
result = def_function.function(gather_fn)()
self.assertAllClose(result, per_replica_expect)
get_global_mpr(num_processes).run(replica_fn)
@combinations.generate(
combinations.combine(
num_processes=[1, 2],
required_gpus=[0, 1, 2],
implementation=[CommunicationImplementation.RING],
)
)
def testCollectiveV2ControlFlow(
self, num_processes, required_gpus, implementation
):
def replica_fn():
CollectiveReplicaLauncher._prefer_unique_instance_key = True
collective, devices, _ = self.make_collective(
num_processes, required_gpus
)
options = collective_util.Options(implementation=implementation)
value = make_per_replica_value(constant_op.constant([1.0]), devices)
@def_function.function
def reduce_fn():
def cond_body():
reduced = collective.reduce(
reduce_util.ReduceOp.SUM, value, value, options
)
return math_ops.add_n(self.as_list(reduced)) / len(devices)
return cond.cond(array_ops.identity(False), cond_body, cond_body)
num_replicas = num_processes * len(devices)
self.assertAllEqual(reduce_fn(), [1.0 * num_replicas])
get_global_mpr(num_processes).run(replica_fn)
@combinations.generate(
combinations.combine(
num_processes=1,
required_gpus=2,
implementation=[
CommunicationImplementation.RING,
CommunicationImplementation.NCCL,
],
prefer_unique_instance_key=[True, False],
)
)
def testMultiThreadedCollectiveLaunchNoInterleave(
self,
num_processes,
required_gpus,
implementation,
prefer_unique_instance_key,
):
if (
num_processes != required_gpus
and implementation == CommunicationImplementation.NCCL
):
self.skipTest(
"Skip NCCL combination with mismatched process and GPU "
"count. NCCL requires physical GPUs for every process."
)
if (
num_processes != required_gpus
and implementation == CommunicationImplementation.AUTO
):
self.skipTest(
"Skip potential NCCL combination (AUTO) with mismatched "
"process and GPU count. NCCL requires physical GPUs for "
"every process."
)
def replica_fn():
CollectiveReplicaLauncher._prefer_unique_instance_key = (
prefer_unique_instance_key
)
collective, devices, _ = self.make_collective(
num_processes, required_gpus
)
options = collective_util.Options(implementation=implementation)
# We would like to simulate the following sequence:
# thread-0 device0 device1
# thread-1 device0 device1
# If the kernel launch sequence is as-is the program will deadlock since
# NCCL requires the launch order to be same on each device.
v0 = make_per_replica_value(1.0, devices)
v1 = make_per_replica_value(2.0, devices)
# Add a delay to collective_ops.all_reduce according to the input tensors
# index in `sequence.`
sequence = [v0.values[0], v1.values[0], v1.values[1], v0.values[1]]
all_reduce = collective_ops.all_reduce
def delayed_all_reduce(input_tensor, *args, **kwargs):
for idx, v in enumerate(sequence):
if input_tensor is v:
time.sleep(idx)
break
return all_reduce(input_tensor, *args, **kwargs)
with test.mock.patch.object(
collective_ops, "all_reduce", delayed_all_reduce
):
# We only use NCCL for batch reduce with two or more values, so we use
# two values here.
def thread_fn():
reduced = collective.batch_reduce(
reduce_util.ReduceOp.SUM, [(v0, v0), (v0, v0)], options
)
self.assertAllEqual(reduced[0].values, [2.0, 2.0])
self.assertAllEqual(reduced[1].values, [2.0, 2.0])
t = threading.Thread(target=thread_fn)
t.start()
reduced = collective.batch_reduce(
reduce_util.ReduceOp.SUM, [(v1, v1), (v1, v1)], options
)
self.assertAllEqual(reduced[0].values, [4.0, 4.0])
self.assertAllEqual(reduced[1].values, [4.0, 4.0])
t.join()
get_global_mpr(num_processes).run(replica_fn)
@combinations.generate(
combinations.combine(
num_processes=1,
required_gpus=2,
implementation=[
CommunicationImplementation.RING,
CommunicationImplementation.NCCL,
],
prefer_unique_instance_key=[True, False],
)
)
def testInputsAreFunctionArgs(
self,
num_processes,
required_gpus,
implementation,
prefer_unique_instance_key,
):
if (
num_processes != required_gpus
and implementation == CommunicationImplementation.NCCL
):
self.skipTest(
"Skip NCCL combination with mismatched process and GPU "
"count. NCCL requires physical GPUs for every process."
)
if (
num_processes != required_gpus
and implementation == CommunicationImplementation.AUTO
):
self.skipTest(
"Skip potential NCCL combination (AUTO) with mismatched "
"process and GPU count. NCCL requires physical GPUs for "
"every process."
)
def replica_fn():
CollectiveReplicaLauncher._prefer_unique_instance_key = (
prefer_unique_instance_key
)
collective, devices, _ = self.make_collective(
num_processes, required_gpus
)
options = collective_util.Options(implementation=implementation)
@def_function.function
def reduce_fn(v):
# Function inputs don't have device placement.
self.assertEqual(v.values[0].device, "")
self.assertEqual(v.values[1].device, "")
# We only use NCCL for batch reduce with two or more values, so we use
# two values here.
reduced = collective.batch_reduce(
reduce_util.ReduceOp.SUM, [(v, v), (v, v)], options
)
self.assertEqual(reduced[0].values[0].device, devices[0])
self.assertEqual(reduced[0].values[1].device, devices[1])
self.assertEqual(reduced[1].values[0].device, devices[0])
self.assertEqual(reduced[1].values[1].device, devices[1])
# Returning Mirrored only evaluates the primary value, which causes
# hanging,
return [reduced[0].values, reduced[1].values]
v = make_per_replica_value(1.0, devices)
reduced = reduce_fn(v)
self.assertAllClose(reduced, [[2.0, 2.0], [2.0, 2.0]])
get_global_mpr(num_processes).run(replica_fn)
@combinations.generate(
combinations.combine(
num_processes=2,
required_gpus=[0, 1],
implementation=[
CommunicationImplementation.RING,
CommunicationImplementation.NCCL,
],
prefer_unique_instance_key=[True, False],
)
)
def testTimeoutReduceDense(
self,
num_processes,
implementation,
required_gpus,
prefer_unique_instance_key,
):
if (
required_gpus == 0
and implementation == CommunicationImplementation.NCCL
):
self.skipTest("Skip CPU + NCCL combination")
if (
num_processes != required_gpus
and implementation == CommunicationImplementation.NCCL
):
self.skipTest(
"Skip NCCL combination with mismatched process and GPU "
"count. NCCL requires physical GPUs for every process."
)
if (
num_processes != required_gpus
and implementation == CommunicationImplementation.AUTO
):
self.skipTest(
"Skip potential NCCL combination (AUTO) with mismatched "
"process and GPU count. NCCL requires physical GPUs for "
"every process."
)
def replica_fn():
CollectiveReplicaLauncher._prefer_unique_instance_key = (
prefer_unique_instance_key
)
collective, devices, task_id = self.make_collective(
num_processes, required_gpus
)
if task_id != 0:
return
v = make_per_replica_value(1.0, devices)
options = collective_util.Options(
timeout_seconds=1.0, implementation=implementation
)
@def_function.function
def reduce_dense():
return collective.reduce(reduce_util.ReduceOp.SUM, v, v, options)
# The collective should time out because we only launch it on worker-0,
# while there're three workers in total.
with self.assertRaises(errors.DeadlineExceededError):
reduce_dense()
get_global_mpr(num_processes).run(replica_fn)
@combinations.generate(
combinations.combine(
num_processes=2,
required_gpus=[0, 1],
implementation=[
CommunicationImplementation.RING,
CommunicationImplementation.NCCL,
],
prefer_unique_instance_key=[True, False],
)
)
def testTimeoutBatchReduceDense(
self,
num_processes,
implementation,
required_gpus,
prefer_unique_instance_key,
):
if (
required_gpus == 0
and implementation == CommunicationImplementation.NCCL
):
self.skipTest("Skip CPU + NCCL combination")
if (
num_processes != required_gpus
and implementation == CommunicationImplementation.NCCL
):
self.skipTest(
"Skip NCCL combination with mismatched process and GPU "
"count. NCCL requires physical GPUs for every process."
)
if (
num_processes != required_gpus
and implementation == CommunicationImplementation.AUTO
):
self.skipTest(
"Skip potential NCCL combination (AUTO) with mismatched "
"process and GPU count. NCCL requires physical GPUs for "
"every process."
)
def replica_fn():
CollectiveReplicaLauncher._prefer_unique_instance_key = (
prefer_unique_instance_key
)
collective, devices, task_id = self.make_collective(
num_processes, required_gpus
)
if task_id != 0:
return
v = make_per_replica_value(1.0, devices)
options = collective_util.Options(
timeout_seconds=1.0, implementation=implementation
)
@def_function.function
def batch_reduce_dense():
return collective.batch_reduce(
reduce_util.ReduceOp.SUM, [(v, v), (v, v)], options
)
# The collective should time out because we only launch it on worker-0,
# while there're two workers in total.
with self.assertRaises(errors.DeadlineExceededError):
batch_reduce_dense()
get_global_mpr(num_processes).run(replica_fn)
@combinations.generate(
combinations.combine(
num_processes=2,
required_gpus=[0, 1],
implementation=[
CommunicationImplementation.RING,
CommunicationImplementation.NCCL,
],
prefer_unique_instance_key=[True, False],
)
)
def testTimeoutReduceSparse(
self,
num_processes,
implementation,
required_gpus,
prefer_unique_instance_key,
):
if (
required_gpus == 0
and implementation == CommunicationImplementation.NCCL
):
self.skipTest("Skip CPU + NCCL combination")
if (
num_processes != required_gpus
and implementation == CommunicationImplementation.NCCL
):
self.skipTest(
"Skip NCCL combination with mismatched process and GPU "
"count. NCCL requires physical GPUs for every process."
)
if (
num_processes != required_gpus
and implementation == CommunicationImplementation.AUTO
):
self.skipTest(
"Skip potential NCCL combination (AUTO) with mismatched "
"process and GPU count. NCCL requires physical GPUs for "
"every process."
)
def replica_fn():
CollectiveReplicaLauncher._prefer_unique_instance_key = (
prefer_unique_instance_key
)
collective, devices, task_id = self.make_collective(
num_processes, required_gpus
)
if task_id != 0:
return
v = make_per_replica_value(
IndexedSlicesValue(
values=[[4.0, 6.0]], indices=[1], dense_shape=[5, 2]
),
devices,
)
options = collective_util.Options(
timeout_seconds=1.0, implementation=implementation
)
@def_function.function
def reduce_sparse():
return collective.reduce(reduce_util.ReduceOp.SUM, v, v, options)
# The collective should time out because we only launch it on worker-0,
# while there're two workers in total.
with self.assertRaises(errors.DeadlineExceededError):
reduce_sparse()
get_global_mpr(num_processes).run(replica_fn)
@combinations.generate(
combinations.combine(
num_processes=2,
required_gpus=[0, 1],
implementation=[
CommunicationImplementation.RING,
CommunicationImplementation.NCCL,
],
prefer_unique_instance_key=[True, False],
)
)
def testTimeoutBatchReduceSparse(
self,
num_processes,
required_gpus,
implementation,
prefer_unique_instance_key,
):
if (
required_gpus == 0
and implementation == CommunicationImplementation.NCCL
):
self.skipTest("Skip CPU + NCCL combination")
if (
num_processes != required_gpus
and implementation == CommunicationImplementation.NCCL
):
self.skipTest(
"Skip NCCL combination with mismatched process and GPU "
"count. NCCL requires physical GPUs for every process."
)
if (
num_processes != required_gpus
and implementation == CommunicationImplementation.AUTO
):
self.skipTest(
"Skip potential NCCL combination (AUTO) with mismatched "
"process and GPU count. NCCL requires physical GPUs for "
"every process."
)
def replica_fn():
CollectiveReplicaLauncher._prefer_unique_instance_key = (
prefer_unique_instance_key
)
collective, devices, task_id = self.make_collective(
num_processes, required_gpus
)
if task_id != 0:
return
v = make_per_replica_value(
IndexedSlicesValue(
values=[[4.0, 6.0]], indices=[1], dense_shape=[5, 2]
),
devices,
)
options = collective_util.Options(
timeout_seconds=1.0, implementation=implementation
)
@def_function.function
def batch_reduce_sparse():
return collective.batch_reduce(
reduce_util.ReduceOp.SUM, [(v, v), (v, v)], options
)
# The collective should time out because we only launch it on worker-0,
# while there're two workers in total.
with self.assertRaises(errors.DeadlineExceededError):
batch_reduce_sparse()
get_global_mpr(num_processes).run(replica_fn)
@combinations.generate(combinations.combine(num_processes=1, required_gpus=2))
def testNcclOrdering(self, num_processes, required_gpus):
if num_processes != required_gpus:
self.skipTest(
"Skip NCCL combination with mismatched process and GPU "
"count. NCCL requires physical GPUs for every process."
)
def replica_fn():
CollectiveReplicaLauncher._prefer_unique_instance_key = True
CollectiveReplicaLauncher._prefer_ordering_token = True
collective, devices, _ = self.make_collective(
num_processes, required_gpus
)
options = collective_util.Options(
implementation=CommunicationImplementation.NCCL
)
v_dense = make_per_replica_value([1.0, 1.0], devices)
v_sparse = make_per_replica_value(
[
IndexedSlicesValue([[4.0, 6.0], [5.0, 6.0]], [1, 3], [5, 2]),
IndexedSlicesValue([[4.0, 6.0], [5.0, 6.0]], [1, 3], [5, 2]),
],
devices,
)
@def_function.function
def nested_dense():
collective.reduce(reduce_util.ReduceOp.SUM, v_dense, v_dense, options)
@def_function.function
def nested_sparse():
collective.reduce(reduce_util.ReduceOp.SUM, v_sparse, v_sparse, options)
# All collectives, function calls, if clause and while loops should be
# chained by control dependencies, so that the execution order is
# deterministic.
@def_function.function
def f():
# pylint: disable=pointless-statement
collective.reduce(reduce_util.ReduceOp.SUM, v_sparse, v_sparse, options)
# reducing dense value.
collective.reduce(reduce_util.ReduceOp.SUM, v_dense, v_dense, options)
# reducing sparse value.
collective.reduce(reduce_util.ReduceOp.SUM, v_sparse, v_sparse, options)
# reduce dense value in nested tf.function.
nested_dense()
# reduce sparse value in nested tf.function.
nested_sparse()
# reduce dense value in tf.cond.
if array_ops.identity(1.0) > array_ops.identity(2.0):
collective.reduce(reduce_util.ReduceOp.SUM, v_dense, v_dense, options)
else:
v_dense
# reduce sparse value in tf.cond.
if array_ops.identity(1.0) > array_ops.identity(2.0):
v_sparse
else:
collective.reduce(
reduce_util.ReduceOp.SUM, v_sparse, v_sparse, options
)
# reduce dense value in tf.while_loop.
i = array_ops.identity(1)
while i < 3:
collective.reduce(reduce_util.ReduceOp.SUM, v_dense, v_dense, options)
i += 1
# reduce sparse value in tf.while_loop.
i = array_ops.identity(1)
while i < 3:
collective.reduce(
reduce_util.ReduceOp.SUM, v_sparse, v_sparse, options
)
i += 1
# reducing dense and sparse value again.
collective.reduce(reduce_util.ReduceOp.SUM, v_dense, v_dense, options)
collective.reduce(reduce_util.ReduceOp.SUM, v_sparse, v_sparse, options)
# pylint: enable=pointless-statement
graph = f.get_concrete_function().graph
should_be_ordered = set([
"CollectiveReduceV2",
"CollectiveGatherV2",
"If",
"While",
"StatefulPartitionedCall",
])
nodes_by_device = {}
for op in graph.get_operations():
if op.type in should_be_ordered:
if op.device not in nodes_by_device:
nodes_by_device[op.device] = []
nodes_by_device[op.device].append(op)
order = test_util.topological_sort_operations(graph.get_operations())
for device in devices:
device = device_util.canonicalize(device)
# Those function ops don't have device annotations, but they contain
# collectives for both devices so we always include them.
operations = nodes_by_device[device] + nodes_by_device[""]
# Verify that we get all types of nodes we want.
self.assertEqual(set(op.type for op in operations), should_be_ordered)
test_util.assert_sequential_execution(order, operations)
get_global_mpr(num_processes).run(replica_fn)
@_REGISTER_DECORATOR(CollectiveOpsTest)
def _save_test_case(pickler, obj):
def reconstruct(*args, **kwargs):
del args, kwargs
return CollectiveOpsTest()
return pickler.save_reduce(reconstruct, (), obj=obj)
if __name__ == "__main__":
# Set default inter op thread pool size to one to ensure we don't exhaust the
# thread pool with the additional executors to run collectives in eager.
os.environ["TF_NUM_INTEROP_THREADS"] = "1"
# TODO(b/172304955): figure why logical devices doesn't work.
test_util.main(config_logical_devices=False)
| CollectiveOpsTest |
python | getsentry__sentry | tests/snuba/rules/conditions/test_event_frequency.py | {
"start": 23386,
"end": 31122
} | class ____(SnubaTestCase, RuleTestCase, PerformanceIssueTestCase):
__test__ = Abstract(__module__, __qualname__)
def add_event(self, data, project_id, timestamp):
raise NotImplementedError
def increment(self, event, count, environment=None, timestamp=None):
raise NotImplementedError
def _run_test(self, minutes, data, passes, add_events=False):
rule = self.get_rule(data=data, rule=Rule(environment_id=None))
environment_rule = self.get_rule(data=data, rule=Rule(environment_id=self.environment.id))
event = self.add_event(
data={
"fingerprint": ["something_random"],
"user": {"id": uuid4().hex},
},
project_id=self.project.id,
timestamp=before_now(minutes=minutes),
)
if add_events:
self.increment(
event,
data["value"] + 1,
environment=self.environment.name,
timestamp=timezone.now() - timedelta(minutes=minutes),
)
self.increment(
event,
data["value"] + 1,
timestamp=timezone.now() - timedelta(minutes=minutes),
)
if passes:
self.assertPasses(rule, event, is_new=False)
self.assertPasses(environment_rule, event, is_new=False)
else:
self.assertDoesNotPass(rule, event, is_new=False)
self.assertDoesNotPass(environment_rule, event, is_new=False)
def test_comparison_interval_empty_string(self) -> None:
data = {
"interval": "1m",
"value": 16,
"comparisonType": "count",
"comparisonInterval": "",
}
self._run_test(data=data, minutes=1, passes=False)
def test_one_minute_with_events(self) -> None:
data = {"interval": "1m", "value": 6, "comparisonType": "count", "comparisonInterval": "5m"}
self._run_test(data=data, minutes=1, passes=True, add_events=True)
data = {
"interval": "1m",
"value": 16,
"comparisonType": "count",
"comparisonInterval": "5m",
}
self._run_test(data=data, minutes=1, passes=False)
def test_one_hour_with_events(self) -> None:
data = {"interval": "1h", "value": 6, "comparisonType": "count", "comparisonInterval": "5m"}
self._run_test(data=data, minutes=60, passes=True, add_events=True)
data = {
"interval": "1h",
"value": 16,
"comparisonType": "count",
"comparisonInterval": "5m",
}
self._run_test(data=data, minutes=60, passes=False)
def test_one_day_with_events(self) -> None:
data = {"interval": "1d", "value": 6, "comparisonType": "count", "comparisonInterval": "5m"}
self._run_test(data=data, minutes=1440, passes=True, add_events=True)
data = {
"interval": "1d",
"value": 16,
"comparisonType": "count",
"comparisonInterval": "5m",
}
self._run_test(data=data, minutes=1440, passes=False)
def test_one_week_with_events(self) -> None:
data = {"interval": "1w", "value": 6, "comparisonType": "count", "comparisonInterval": "5m"}
self._run_test(data=data, minutes=10080, passes=True, add_events=True)
data = {
"interval": "1w",
"value": 16,
"comparisonType": "count",
"comparisonInterval": "5m",
}
self._run_test(data=data, minutes=10080, passes=False)
def test_one_minute_no_events(self) -> None:
data = {"interval": "1m", "value": 6, "comparisonType": "count", "comparisonInterval": "5m"}
self._run_test(data=data, minutes=1, passes=False)
def test_one_hour_no_events(self) -> None:
data = {"interval": "1h", "value": 6, "comparisonType": "count", "comparisonInterval": "5m"}
self._run_test(data=data, minutes=60, passes=False)
def test_one_day_no_events(self) -> None:
data = {"interval": "1d", "value": 6, "comparisonType": "count", "comparisonInterval": "5m"}
self._run_test(data=data, minutes=1440, passes=False)
def test_one_week_no_events(self) -> None:
data = {"interval": "1w", "value": 6, "comparisonType": "count", "comparisonInterval": "5m"}
self._run_test(data=data, minutes=10080, passes=False)
def test_comparison(self) -> None:
# Test data is 4 events in the current period and 2 events in the comparison period, so
# a 100% increase.
event = self.add_event(
data={
"fingerprint": ["something_random"],
"user": {"id": uuid4().hex},
},
project_id=self.project.id,
timestamp=before_now(minutes=1),
)
self.increment(
event,
3,
timestamp=timezone.now() - timedelta(minutes=1),
)
self.increment(
event,
2,
timestamp=timezone.now() - timedelta(days=1, minutes=20),
)
data = {
"interval": "1h",
"value": 99,
"comparisonType": "percent",
"comparisonInterval": "1d",
}
rule = self.get_rule(data=data, rule=Rule(environment_id=None))
self.assertPasses(rule, event, is_new=False)
data = {
"interval": "1h",
"value": 101,
"comparisonType": "percent",
"comparisonInterval": "1d",
}
rule = self.get_rule(data=data, rule=Rule(environment_id=None))
self.assertDoesNotPass(rule, event, is_new=False)
def test_comparison_empty_comparison_period(self) -> None:
# Test data is 1 event in the current period and 0 events in the comparison period. This
# should always result in 0 and never fire.
event = self.add_event(
data={
"fingerprint": ["something_random"],
"user": {"id": uuid4().hex},
},
project_id=self.project.id,
timestamp=before_now(minutes=1),
)
data = {
"interval": "1h",
"value": 0,
"comparisonType": "percent",
"comparisonInterval": "1d",
}
rule = self.get_rule(data=data, rule=Rule(environment_id=None))
self.assertDoesNotPass(rule, event, is_new=False)
data = {
"interval": "1h",
"value": 100,
"comparisonType": "percent",
"comparisonInterval": "1d",
}
rule = self.get_rule(data=data, rule=Rule(environment_id=None))
self.assertDoesNotPass(rule, event, is_new=False)
@patch("sentry.rules.conditions.event_frequency.BaseEventFrequencyCondition.get_rate")
def test_is_new_issue_skips_snuba(self, mock_get_rate: MagicMock) -> None:
# Looking for more than 1 event
data = {"interval": "1m", "value": 6}
minutes = 1
rule = self.get_rule(data=data, rule=Rule(environment_id=None))
environment_rule = self.get_rule(data=data, rule=Rule(environment_id=self.environment.id))
event = self.add_event(
data={
"fingerprint": ["something_random"],
"user": {"id": uuid4().hex},
},
project_id=self.project.id,
timestamp=before_now(minutes=minutes),
)
# Issue is new and is the first event
self.assertDoesNotPass(rule, event, is_new=True)
self.assertDoesNotPass(environment_rule, event, is_new=True)
assert mock_get_rate.call_count == 0
| StandardIntervalTestBase |
python | ipython__ipython | IPython/utils/tokenutil.py | {
"start": 329,
"end": 6552
} | class ____(NamedTuple):
token: int
text: str
start: int
end: int
line: str
def generate_tokens(readline) -> Generator[TokenInfo, None, None]:
"""wrap generate_tkens to catch EOF errors"""
try:
yield from tokenize.generate_tokens(readline)
except tokenize.TokenError:
# catch EOF error
return
def generate_tokens_catch_errors(
readline, extra_errors_to_catch: list[str] | None = None
):
default_errors_to_catch = [
"unterminated string literal",
"invalid non-printable character",
"after line continuation character",
]
assert extra_errors_to_catch is None or isinstance(extra_errors_to_catch, list)
errors_to_catch = default_errors_to_catch + (extra_errors_to_catch or [])
tokens: list[TokenInfo] = []
try:
for token in tokenize.generate_tokens(readline):
tokens.append(token)
yield token
except tokenize.TokenError as exc:
if any(error in exc.args[0] for error in errors_to_catch):
if tokens:
start = tokens[-1].start[0], tokens[-1].end[0]
end = start
line = tokens[-1].line
else:
start = end = (1, 0)
line = ""
yield TokenInfo(tokenize.ERRORTOKEN, "", start, end, line)
else:
# Catch EOF
raise
def line_at_cursor(cell: str, cursor_pos: int = 0) -> tuple[str, int]:
"""Return the line in a cell at a given cursor position
Used for calling line-based APIs that don't support multi-line input, yet.
Parameters
----------
cell : str
multiline block of text
cursor_pos : integer
the cursor position
Returns
-------
(line, offset): (string, integer)
The line with the current cursor, and the character offset of the start of the line.
"""
offset = 0
lines = cell.splitlines(True)
for line in lines:
next_offset = offset + len(line)
if not line.endswith("\n"):
# If the last line doesn't have a trailing newline, treat it as if
# it does so that the cursor at the end of the line still counts
# as being on that line.
next_offset += 1
if next_offset > cursor_pos:
break
offset = next_offset
else:
line = ""
return line, offset
def token_at_cursor(cell: str, cursor_pos: int = 0) -> str:
"""Get the token at a given cursor
Used for introspection.
Function calls are prioritized, so the token for the callable will be returned
if the cursor is anywhere inside the call.
Parameters
----------
cell : str
A block of Python code
cursor_pos : int
The location of the cursor in the block where the token should be found
"""
names: list[str] = []
call_names: list[str] = []
closing_call_name: str | None = None
most_recent_outer_name: str | None = None
offsets = {1: 0} # lines start at 1
intersects_with_cursor = False
cur_token_is_name = False
tokens: list[Token | None] = [
Token(*tup) for tup in generate_tokens(StringIO(cell).readline)
]
if not tokens:
return ""
for prev_tok, (tok, next_tok) in zip(
[None] + tokens, itertools.pairwise(tokens + [None])
):
# token, text, start, end, line = tup
start_line, start_col = tok.start
end_line, end_col = tok.end
if end_line + 1 not in offsets:
# keep track of offsets for each line
lines = tok.line.splitlines(True)
for lineno, line in enumerate(lines, start_line + 1):
if lineno not in offsets:
offsets[lineno] = offsets[lineno - 1] + len(line)
closing_call_name = None
offset = offsets[start_line]
if offset + start_col > cursor_pos:
# current token starts after the cursor,
# don't consume it
break
if cur_token_is_name := tok.token == tokenize.NAME and not iskeyword(tok.text):
if (
names
and prev_tok
and prev_tok.token == tokenize.OP
and prev_tok.text == "."
):
names[-1] = "%s.%s" % (names[-1], tok.text)
else:
names.append(tok.text)
if (
next_tok is not None
and next_tok.token == tokenize.OP
and next_tok.text == "="
):
# don't inspect the lhs of an assignment
names.pop(-1)
cur_token_is_name = False
if not call_names:
most_recent_outer_name = names[-1] if names else None
elif tok.token == tokenize.OP:
if tok.text == "(" and names:
# if we are inside a function call, inspect the function
call_names.append(names[-1])
elif tok.text == ")" and call_names:
# keep track of the most recently popped call_name from the stack
closing_call_name = call_names.pop(-1)
if offsets[end_line] + end_col > cursor_pos:
# we found the cursor, stop reading
# if the current token intersects directly, use it instead of the call token
intersects_with_cursor = offsets[start_line] + start_col <= cursor_pos
break
if cur_token_is_name and intersects_with_cursor:
return names[-1]
# if the cursor isn't directly over a name token, use the most recent
# call name if we can find one
elif closing_call_name:
# if we're on a ")", use the most recently popped call name
return closing_call_name
elif call_names:
# otherwise, look for the most recent call name in the stack
return call_names[-1]
elif most_recent_outer_name:
# if we've popped all the call names, use the most recently-seen
# outer name
return most_recent_outer_name
elif names:
# failing that, use the most recently seen name
return names[-1]
else:
# give up
return ""
| Token |
python | pytorch__pytorch | torch/autograd/graph.py | {
"start": 16608,
"end": 23459
} | class ____(RemovableHandle):
handles: tuple[RemovableHandle, ...]
def __init__(self, handles: tuple[RemovableHandle, ...]) -> None:
self.handles = handles
def remove(self) -> None:
for handle in self.handles:
handle.remove()
def __getstate__(self) -> tuple[RemovableHandle, ...]:
return self.handles
def __setstate__(self, state: tuple[RemovableHandle, ...]) -> None:
self.handles = state
def register_multi_grad_hook(
tensors: Sequence[torch.Tensor],
fn: Union[
Callable[[Sequence[Optional[torch.Tensor]]], None],
Callable[[torch.Tensor], None],
],
*,
mode: Literal["all", "any"] = "all",
) -> RemovableHandle:
r"""Register a multi-grad backward hook.
There are two supported modes: ``"all"`` and ``"any"``.
Under the ``"all"`` mode, the hook will be called after gradients with respect to every tensor in
:attr:`tensors` have been computed. If a tensor is in :attr:`tensors` but
is not part of the graph, or if a tensor is not needed to compute the gradients
for any ``inputs`` specified for the current ``.backward()`` or ``.grad()`` call,
this tensor will be ignored and the hook will not wait for its gradient to be
computed.
After every non-ignored tensor's gradient has been computed, :attr:`fn` will be
called with those gradients. ``None`` will be passed for tensors that did not
have their gradients computed.
Under the ``"any"`` mode, the hook will be called after the first gradient
with respect to a tensor in :attr:`tensors` has been computed. The hook
will be called with that gradient as its argument.
The hook should not modify its arguments.
This function returns a handle with a method ``handle.remove()`` that removes the hook.
.. note::
See :ref:`backward-hooks-execution` for more information on how when this hook
is executed, and how its execution is ordered relative to other hooks.
Example::
>>> import torch
>>>
>>> a = torch.rand(2, 3, requires_grad=True)
>>> b = torch.rand(2, 3, requires_grad=True)
>>> c = a * b
>>> d = a * b
>>>
>>> def fn(grads):
... print([g is not None for g in grads])
...
>>> torch.autograd.graph.register_multi_grad_hook((a, b, c, d), fn)
>>>
>>> c.sum().backward(retain_graph=True)
[True, True, True, False]
>>> c.sum().backward(inputs=(a,), retain_graph=True)
[True, False, True, False]
>>>
"""
supported_modes = ("all", "any")
lock = threading.Lock()
if mode not in supported_modes:
raise ValueError(f"Expects mode to be one of {supported_modes} but got {mode}")
if mode == "all":
count: dict[int, int] = {}
nb_calls = None
buffer: dict[int, list[Optional[torch.Tensor]]] = {}
grad_fns = list(map(_get_grad_fn_or_grad_acc, tensors))
len_tensors = len(tensors)
def get_inner_hook(idx: int) -> Callable[[torch.Tensor], None]:
def inner_hook(grad: torch.Tensor) -> None:
nonlocal count, nb_calls, buffer, fn
id = torch._C._current_graph_task_id()
if id == -1:
raise AssertionError(
"expected this hook to be called inside a backward call"
)
count[id] = count.get(id, 0)
# pyrefly: ignore [unsupported-operation]
buffer[id] = buffer.get(id, [None] * len_tensors)
with lock:
curr_count, count[id] = count[id], count[id] + 1
if curr_count == 0:
# On the first call, compute the actual nb_calls and buffer
nb_calls = sum(
map(torch._C._will_engine_execute_node, grad_fns)
)
buffer[id][idx] = grad
if nb_calls is None:
raise AssertionError("Expected nb_calls to be set")
if curr_count == nb_calls - 1:
fn = cast(Callable[[Sequence[Optional[torch.Tensor]]], None], fn)
fn(buffer[id])
del count[id]
del buffer[id]
return inner_hook
handles = tuple(
t.register_hook(get_inner_hook(i)) for i, t in enumerate(tensors)
)
elif mode == "any":
fn = cast(Callable[[torch.Tensor], None], fn)
ran_hook: dict[int, bool] = defaultdict(bool)
@functools.wraps(fn)
def wrapped_fn(grad: torch.Tensor) -> None:
nonlocal ran_hook
id = torch._C._current_graph_task_id()
if id == -1:
raise AssertionError(
"expected this hook to be called inside a backward call"
)
with lock:
prev, ran_hook[id] = ran_hook[id], True
if prev:
return
fn(grad)
handles = tuple(
tensor.register_hook(wrapped_fn)
for tensor in tensors
if tensor.requires_grad
)
return _MultiHandle(handles) # type: ignore[possibly-undefined]
# NOTE [Allow mutation on tensors saved for backward]
#
# 1. Tensor gets saved for backward
# - remember the python object id and the version of the tensor
# - remember aliasing information (data_ptr of base + version)
# - save the original so we control its lifetime
# 2. Any time a tensor gets in-placed
# - for each tensor aliased to it:
# - check using its object id and version to see if it has been saved
# - if it has been saved, clone it
# - delete the reference to the original
# 3. during backward
# - if the clone exists, the tensor must've been modified in-place
_allow_mutation_on_saved_tensors_enabled: bool = False
_TID: TypeAlias = tuple[int, int, int]
_SID: TypeAlias = tuple[int, int]
def _get_tid(tensor: torch.Tensor) -> _TID:
# FIXME: This is almost definitely a bug.
if isinstance(
tensor,
(
torch._subclasses.fake_tensor.FakeTensor,
torch._subclasses.functional_tensor.FunctionalTensor,
),
):
data_ptr = 0
else:
data_ptr = tensor.data_ptr()
return (id(tensor), data_ptr, tensor._version)
def _get_sid(tensor: torch.Tensor) -> _SID:
# FIXME: This is almost definitely a bug.
if isinstance(
tensor,
(
torch._subclasses.fake_tensor.FakeTensor,
torch._subclasses.functional_tensor.FunctionalTensor,
),
):
data_ptr = 0
else:
data_ptr = tensor.data_ptr()
return (data_ptr, tensor._version)
| _MultiHandle |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/callbackProtocol10.py | {
"start": 520,
"end": 628
} | class ____(Protocol[P]):
def __call__(self, a: int, *args: P.args, **kwargs: P.kwargs) -> None: ...
| Proto4 |
python | celery__celery | celery/contrib/sphinx.py | {
"start": 2265,
"end": 3391
} | class ____(PyFunction):
"""Sphinx task directive."""
def get_signature_prefix(self, sig):
return [nodes.Text(self.env.config.celery_task_prefix)]
def autodoc_skip_member_handler(app, what, name, obj, skip, options):
"""Handler for autodoc-skip-member event."""
# Celery tasks created with the @task decorator have the property
# that *obj.__doc__* and *obj.__class__.__doc__* are equal, which
# trips up the logic in sphinx.ext.autodoc that is supposed to
# suppress repetition of class documentation in an instance of the
# class. This overrides that behavior.
if isinstance(obj, BaseTask) and getattr(obj, '__wrapped__'):
if skip:
return False
return None
def setup(app):
"""Setup Sphinx extension."""
app.setup_extension('sphinx.ext.autodoc')
app.add_autodocumenter(TaskDocumenter)
app.add_directive_to_domain('py', 'task', TaskDirective)
app.add_config_value('celery_task_prefix', '(task)', True)
app.connect('autodoc-skip-member', autodoc_skip_member_handler)
return {
'parallel_read_safe': True
}
| TaskDirective |
python | pypa__warehouse | warehouse/integrations/secrets/utils.py | {
"start": 2484,
"end": 3106
} | class ____(TokenLeakMatcher):
name = "pypi_api_token"
# Macaroons are urlsafe_b64 encodeded so non-alphanumeric chars are - and _
# https://github.com/ecordell/pymacaroons/blob/06b55110eda2fb192c130dee0bcedf8b124d1056/pymacaroons/serializers/binary_serializer.py#L32
pattern = re.compile(r"pypi-[A-Za-z0-9-_=]+")
def extract(self, text):
"""
From a string containing everything that was matched, extract the token
to check
"""
return text
TOKEN_LEAK_MATCHERS = {
matcher.name: matcher for matcher in [PlainTextTokenLeakMatcher()]
}
| PlainTextTokenLeakMatcher |
python | astropy__astropy | astropy/coordinates/tests/test_intermediate_transformations.py | {
"start": 41651,
"end": 43919
} | class ____:
# TETE and CIRS use get_location_gcrs to get obsgeoloc and obsgeovel
# with knowledge of some of the matrices. Check that this is consistent
# with a direct transformation.
def setup_class(cls):
cls.loc = loc = EarthLocation.from_geodetic(
np.linspace(0, 360, 6) * u.deg, np.linspace(-90, 90, 6) * u.deg, 100 * u.m
)
cls.obstime = obstime = Time(np.linspace(2000, 2010, 6), format="jyear")
# Get comparison via a full transformation. We do not use any methods
# of EarthLocation, since those depend on the fast transform.
loc_itrs = ITRS(loc.x, loc.y, loc.z, obstime=obstime)
zeros = np.broadcast_to(0.0 * (u.km / u.s), (3,) + loc_itrs.shape, subok=True)
loc_itrs.data.differentials["s"] = CartesianDifferential(zeros)
loc_gcrs_cart = loc_itrs.transform_to(GCRS(obstime=obstime)).cartesian
cls.obsgeoloc = loc_gcrs_cart.without_differentials()
cls.obsgeovel = loc_gcrs_cart.differentials["s"].to_cartesian()
def check_obsgeo(self, obsgeoloc, obsgeovel):
assert_allclose(obsgeoloc.xyz, self.obsgeoloc.xyz, atol=0.1 * u.um, rtol=0.0)
assert_allclose(
obsgeovel.xyz, self.obsgeovel.xyz, atol=0.1 * u.mm / u.s, rtol=0.0
)
def test_get_gcrs_posvel(self):
# Really just a sanity check
self.check_obsgeo(*self.loc.get_gcrs_posvel(self.obstime))
def test_tete_quick(self):
# Following copied from intermediate_rotation_transforms.gcrs_to_tete
rbpn = erfa.pnm06a(*get_jd12(self.obstime, "tt"))
loc_gcrs_frame = get_location_gcrs(
self.loc, self.obstime, tete_to_itrs_mat(self.obstime, rbpn=rbpn), rbpn
)
self.check_obsgeo(loc_gcrs_frame.obsgeoloc, loc_gcrs_frame.obsgeovel)
def test_cirs_quick(self):
cirs_frame = CIRS(location=self.loc, obstime=self.obstime)
# Following copied from intermediate_rotation_transforms.gcrs_to_cirs
pmat = gcrs_to_cirs_mat(cirs_frame.obstime)
loc_gcrs_frame = get_location_gcrs(
self.loc, self.obstime, cirs_to_itrs_mat(cirs_frame.obstime), pmat
)
self.check_obsgeo(loc_gcrs_frame.obsgeoloc, loc_gcrs_frame.obsgeovel)
| TestGetLocationGCRS |
python | wandb__wandb | wandb/vendor/pygments/style.py | {
"start": 4554,
"end": 4807
} | class ____(object):
#: overall background color (``None`` means transparent)
background_color = '#ffffff'
#: highlight background color
highlight_color = '#ffffcc'
#: Style definitions for individual token types.
styles = {}
| Style |
python | facelessuser__pymdown-extensions | pymdownx/tabbed.py | {
"start": 11414,
"end": 14955
} | class ____(Treeprocessor):
"""Tab tree processor."""
def __init__(self, md, config):
"""Initialize."""
super().__init__(md)
self.slugify = config["slugify"]
self.alternate = config["alternate_style"]
self.sep = config["separator"]
self.combine_header_slug = config["combine_header_slug"]
def get_parent_header_slug(self, root, header_map, parent_map, el):
"""Attempt retrieval of parent header slug."""
parent = el
last_parent = parent
while parent is not root:
last_parent = parent
parent = parent_map[parent]
if parent in header_map:
headers = header_map[parent]
header = None
for i in list(parent):
if i is el and header is None:
break
if i is last_parent and header is not None:
return header.attrib.get("id", '')
if i in headers:
header = i
return ''
def run(self, doc):
"""Update tab IDs."""
# Get a list of id attributes
used_ids = set()
parent_map = {}
header_map = {}
if self.combine_header_slug:
parent_map = {c: p for p in doc.iter() for c in p}
for el in doc.iter():
if "id" in el.attrib:
if self.combine_header_slug and el.tag in HEADERS:
parent = parent_map[el]
if parent in header_map:
header_map[parent].append(el)
else:
header_map[parent] = [el]
used_ids.add(el.attrib["id"])
for el in doc.iter():
if isinstance(el.tag, str) and el.tag.lower() == 'div':
classes = el.attrib.get('class', '').split()
if 'tabbed-set' in classes and (not self.alternate or 'tabbed-alternate' in classes):
inputs = []
labels = []
if self.alternate:
for i in list(el):
if i.tag == 'input':
inputs.append(i)
if i.tag == 'div' and i.attrib.get('class', '') == 'tabbed-labels':
labels = [j for j in list(i) if j.tag == 'label']
else:
for i in list(el):
if i.tag == 'input':
inputs.append(i)
if i.tag == 'label':
labels.append(i)
# Generate slugged IDs
for inpt, label in zip(inputs, labels):
innerhtml = toc.render_inner_html(toc.remove_fnrefs(label), self.md)
innertext = html.unescape(toc.strip_tags(innerhtml))
if self.combine_header_slug:
parent_slug = self.get_parent_header_slug(doc, header_map, parent_map, el)
else:
parent_slug = ''
slug = self.slugify(innertext, self.sep)
if parent_slug:
slug = parent_slug + self.sep + slug
slug = toc.unique(slug, used_ids)
inpt.attrib["id"] = slug
label.attrib["for"] = slug
| TabbedTreeprocessor |
python | plotly__plotly.py | plotly/graph_objs/barpolar/unselected/_textfont.py | {
"start": 233,
"end": 2587
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "barpolar.unselected"
_path_str = "barpolar.unselected.textfont"
_valid_props = {"color"}
@property
def color(self):
"""
Sets the text font color of unselected points, applied only
when a selection exists.
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 _prop_descriptions(self):
return """\
color
Sets the text font color of unselected points, applied
only when a selection exists.
"""
def __init__(self, arg=None, color=None, **kwargs):
"""
Construct a new Textfont object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.barpolar.unselected.Textfont`
color
Sets the text font color of unselected points, applied
only when a selection exists.
Returns
-------
Textfont
"""
super().__init__("textfont")
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.barpolar.unselected.Textfont
constructor must be a dict or
an instance of :class:`plotly.graph_objs.barpolar.unselected.Textfont`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("color", arg, color)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
| Textfont |
python | euske__pdfminer | setup.py | {
"start": 132,
"end": 2266
} | class ____(install):
def run(self):
import os.path
import pdfminer
from pdfminer.cmapdb import convert_cmap
outdir = os.path.join(os.path.join(self.install_lib, 'pdfminer'), 'cmap')
print('installing cmap: %r...' % outdir)
os.makedirs(outdir, exist_ok=True)
convert_cmap(
outdir, 'Adobe-CNS1',
{'B5':'cp950', 'UniCNS-UTF8':'utf-8'},
['cmaprsrc/cid2code_Adobe_CNS1.txt'])
convert_cmap(
outdir, 'Adobe-GB1',
{'GBK-EUC':'cp936', 'UniGB-UTF8':'utf-8'},
['cmaprsrc/cid2code_Adobe_GB1.txt'])
convert_cmap(
outdir, 'Adobe-Japan1',
{'RKSJ':'cp932', 'EUC':'euc-jp', 'UniJIS-UTF8':'utf-8'},
['cmaprsrc/cid2code_Adobe_Japan1.txt'])
convert_cmap(
outdir, 'Adobe-Korea1',
{'KSC-EUC':'euc-kr', 'KSC-Johab':'johab', 'KSCms-UHC':'cp949',
'UniKS-UTF8':'utf-8'},
['cmaprsrc/cid2code_Adobe_Korea1.txt'])
install.run(self)
return
with open('README.md') as fp:
long_description = fp.read()
setup(
cmdclass = { 'install': install_cmap },
name = 'pdfminer',
version = __version__,
description = 'PDF parser and analyzer',
long_description = long_description,
long_description_content_type = 'text/markdown',
license = 'MIT',
author = 'Yusuke Shinyama',
author_email = 'yusuke@shinyama.jp',
url = 'http://github.com/euske/pdfminer',
packages = [
'pdfminer',
],
python_requires = '>=3.6',
install_requires = [
'pycryptodome',
],
scripts = [
'tools/pdf2txt.py',
'tools/dumppdf.py',
],
keywords = [
'pdf parser',
'pdf converter',
'layout analysis',
'text mining'
],
classifiers = [
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Topic :: Text Processing',
],
)
| install_cmap |
python | pytorch__pytorch | torch/_higher_order_ops/flex_attention.py | {
"start": 21572,
"end": 44560
} | class ____(torch.autograd.Function):
@staticmethod
# pyrefly: ignore [bad-override]
def forward(
ctx: Any,
query: Tensor,
key: Tensor,
value: Tensor,
fw_graph: Callable,
joint_graph: Callable,
block_mask: tuple[Any, ...],
scale: float,
kernel_options: dict[str, Any],
mask_mod_other_buffers: tuple[Any, ...],
*score_mod_other_buffers: tuple[Any, ...],
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
any_buffer_requires_grad = any(
buffer.requires_grad
for buffer in mask_mod_other_buffers
if isinstance(buffer, torch.Tensor)
)
assert not any_buffer_requires_grad, (
"Captured buffers from mask mod that require grad are not supported."
)
ctx._fw_graph = fw_graph
ctx._joint_graph = joint_graph
ctx._mask_graph = block_mask[-1]
ctx.scale = scale
ctx.kernel_options = kernel_options
ctx._score_mod_other_buffers_len = len(score_mod_other_buffers)
with torch._C._AutoDispatchBelowAutograd():
out, logsumexp, max_scores = flex_attention(
query,
key,
value,
fw_graph,
block_mask,
scale,
kernel_options,
score_mod_other_buffers,
mask_mod_other_buffers,
)
# no grads for you sir
ctx.mark_non_differentiable(max_scores)
save_tensors_and_symints_for_backward(
ctx,
(
query,
key,
value,
out,
logsumexp,
max_scores,
*block_mask[:-1],
*score_mod_other_buffers,
*mask_mod_other_buffers,
),
)
return out, logsumexp, max_scores
@staticmethod
def backward( # type: ignore[override]
ctx: Any,
grad_out: Tensor,
grad_logsumexp: Tensor,
grad_max_scores: Tensor,
) -> tuple[Optional[Tensor], ...]:
fw_args = saved_tensors_and_symints(ctx)
(
query,
key,
value,
out,
logsumexp,
max_scores,
query_lengths,
kv_lengths,
kv_num_blocks,
kv_indices,
full_kv_num_blocks,
full_kv_indices,
q_num_blocks,
q_indices,
full_q_num_blocks,
full_q_indices,
Q_BLOCK_SIZE,
KV_BLOCK_SIZE,
*other_buffers,
) = fw_args
fw_graph = ctx._fw_graph
joint_graph = ctx._joint_graph
mask_graph = ctx._mask_graph
scale = ctx.scale
kernel_options = ctx.kernel_options
score_mod_other_buffers = tuple(
other_buffers[: ctx._score_mod_other_buffers_len]
)
mask_mod_other_buffers = tuple(
other_buffers[ctx._score_mod_other_buffers_len :]
)
# We have asserted that mask_mod_other_buffers do not require grad,
# but score_mod_other_buffers can require grad.
none_grads = [None] * 6
(
grad_query,
grad_key,
grad_value,
grad_score_mod_captured,
) = flex_attention_backward(
query,
key,
value,
out,
logsumexp,
grad_out,
grad_logsumexp,
fw_graph,
joint_graph,
(
query_lengths,
kv_lengths,
kv_num_blocks,
kv_indices,
full_kv_num_blocks,
full_kv_indices,
q_num_blocks,
q_indices,
full_q_num_blocks,
full_q_indices,
Q_BLOCK_SIZE,
KV_BLOCK_SIZE,
mask_graph,
),
scale,
kernel_options,
score_mod_other_buffers,
mask_mod_other_buffers,
)
return grad_query, grad_key, grad_value, *none_grads, *grad_score_mod_captured
# TODO: Rework DispatchKey.Autograd to py_autograd_impl
@flex_attention.py_impl(DispatchKey.Autograd)
def flex_attention_autograd(
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
score_mod: Callable,
block_mask: tuple,
scale: float,
kernel_options: dict[str, Any],
score_mod_other_buffers: tuple[Tensor, ...] = (),
mask_mod_other_buffers: tuple[Tensor, ...] = (),
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
from torch._dynamo._trace_wrapped_higher_order_op import TransformGetItemToIndex
with TransformGetItemToIndex():
input_requires_grad = any(
isinstance(t, torch.Tensor) and t.requires_grad
for t in (query, key, value, *score_mod_other_buffers)
)
if torch.is_grad_enabled() and input_requires_grad:
if block_mask[7] is None:
raise RuntimeError(
"BlockMask q_indices is None. Backward pass requires q_indices to be computed. "
"Please create the BlockMask with compute_q_blocks=True"
)
example_vals = (
query.new_zeros((), requires_grad=input_requires_grad),
query.new_zeros((), dtype=torch.int),
query.new_zeros((), dtype=torch.int),
query.new_zeros((), dtype=torch.int),
query.new_zeros((), dtype=torch.int),
)
fw_graph, bw_graph = create_fw_bw_graph(
score_mod, example_vals, score_mod_other_buffers
)
else:
fw_graph, bw_graph = score_mod, None
out, logsumexp, max_scores = FlexAttentionAutogradOp.apply(
query,
key,
value,
fw_graph,
bw_graph,
block_mask,
scale,
kernel_options,
mask_mod_other_buffers,
*score_mod_other_buffers,
)
return out, logsumexp, max_scores
# ---------------------------- Backward HOP Implementation ----------------------------
@flex_attention_backward.py_impl(DispatchKey.CompositeExplicitAutograd)
def sdpa_dense_backward(
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
out: torch.Tensor,
logsumexp: torch.Tensor,
grad_out: torch.Tensor,
grad_logsumexp: torch.Tensor,
fw_graph: Callable, # GraphModule type hint?
joint_graph: Callable,
block_mask: tuple,
scale: float,
kernel_options: dict[str, Any],
score_mod_other_buffers: tuple,
mask_mod_other_buffers: tuple,
) -> tuple[
torch.Tensor, torch.Tensor, torch.Tensor, tuple[Optional[torch.Tensor], ...]
]:
from torch._dynamo._trace_wrapped_higher_order_op import TransformGetItemToIndex
Bq, Hq, seq_len_q, qk_head_dim = query.shape
Bkv, Hkv, seq_len_kv, v_head_dim = value.shape
# Get outputs before calling repeat interleave and permute to input stride orders
actual_grad_query = query.new_empty((Bq, Hq, seq_len_q, qk_head_dim))
actual_grad_query = _permute_strides(actual_grad_query, query.stride())
actual_grad_key = key.new_empty((Bq, Hkv, seq_len_kv, qk_head_dim))
actual_grad_key = _permute_strides(actual_grad_key, key.stride())
actual_grad_value = value.new_empty((Bq, Hkv, seq_len_kv, v_head_dim))
actual_grad_value = _permute_strides(actual_grad_value, value.stride())
def _maybe_new_buffer(
buffer: Union[torch.Tensor, torch.SymInt, int],
) -> Optional[Union[torch.Tensor, torch.SymInt, int]]:
if isinstance(buffer, torch.Tensor):
return (
torch.empty_like(buffer, memory_format=torch.contiguous_format)
if buffer.requires_grad
else None
)
return buffer
actual_grad_score_mod_captured = [
_maybe_new_buffer(buffer) for buffer in score_mod_other_buffers
]
Bq, Bkv = query.size(0), key.size(0)
if not ((Bq == Bkv) or (Bq > 1 and Bkv == 1)):
raise RuntimeError(f"Bq and Bkv must broadcast. Got Bq={Bq} and Bkv={Bkv}")
key = key.expand((Bq, *key.size()[1:]))
value = value.expand((Bq, *value.size()[1:]))
G = query.size(1) // key.size(1)
key = torch.repeat_interleave(key, G, dim=1)
value = torch.repeat_interleave(value, G, dim=1)
# We're undoing the log -> log2 change of base in the forwards
logsumexp = logsumexp * math.log(2)
# The backwards formula for the log -> log2 change of base in the forwards
grad_logsumexp = grad_logsumexp / math.log(2)
scores, post_mod_scores = _math_attention_inner(
query,
key,
value,
fw_graph,
block_mask,
scale,
kernel_options,
score_mod_other_buffers,
mask_mod_other_buffers,
)
masked_out_rows = logsumexp == -float("inf")
softmax_scores = torch.exp(post_mod_scores - logsumexp.unsqueeze(-1))
softmax_scores = torch.where(masked_out_rows.unsqueeze(-1), 0, softmax_scores)
grad_value = softmax_scores.to(query.dtype).transpose(-2, -1) @ grad_out
grad_softmax_scores = grad_out.to(dtype=softmax_scores.dtype) @ value.to(
dtype=softmax_scores.dtype
).transpose(-2, -1)
sum_scores = torch.sum(
out.to(dtype=softmax_scores.dtype) * grad_out.to(dtype=softmax_scores.dtype),
-1,
keepdim=True,
)
grad_score_mod = softmax_scores * (
grad_softmax_scores - sum_scores + grad_logsumexp.unsqueeze(-1)
)
b = torch.arange(0, scores.size(0), device=scores.device)
h = torch.arange(0, scores.size(1), device=scores.device)
m = torch.arange(0, scores.size(2), device=scores.device)
n = torch.arange(0, scores.size(3), device=scores.device)
mask_graph = block_mask[-1]
# Gradient of the inline score_mod function, with respect to the scores
captured_buffers_in_dim = (None,) * len(score_mod_other_buffers)
out_dims = [0, None, None, None, None] + [None] * len(score_mod_other_buffers)
from torch.nn.attention.flex_attention import _vmap_for_bhqkv
# inputs are [score, b, h, q_idx, kv_idx, gradOut, ...]
# score and gradOut are "fully" batched
joint_score_mod = _vmap_for_bhqkv(
joint_graph,
prefix=(0,),
suffix=(0,) + captured_buffers_in_dim,
out_dims=out_dims,
)
with TransformGetItemToIndex():
grad_scores, _, _, _, _, *grad_score_mod_captured = joint_score_mod(
scores, b, h, m, n, grad_score_mod, *score_mod_other_buffers
)
grad_scores = grad_scores * scale
grad_scores = grad_scores.to(query.dtype)
mask_mod = _vmap_for_bhqkv(
mask_graph, prefix=(), suffix=(None,) * len(mask_mod_other_buffers)
)
with TransformGetItemToIndex():
mask_scores = mask_mod(b, h, m, n, *mask_mod_other_buffers)
grad_scores = torch.where(
mask_scores, grad_scores, torch.tensor(0, dtype=query.dtype)
)
grad_query = grad_scores @ key
grad_key = grad_scores.transpose(-2, -1) @ query
# Reduce DK, DV along broadcasted heads.
grad_key = grad_key.view(
grad_key.size(0), -1, G, grad_key.size(-2), grad_key.size(-1)
)
grad_value = grad_value.view(
grad_value.size(0), -1, G, grad_value.size(-2), grad_value.size(-1)
)
grad_key = torch.sum(grad_key, 2, keepdim=False)
grad_value = torch.sum(grad_value, 2, keepdim=False)
# Fill to correctly strided outputs
actual_grad_query.copy_(grad_query)
actual_grad_key.copy_(grad_key)
actual_grad_value.copy_(grad_value)
if Bq != Bkv:
assert Bq > 1 and Bkv == 1, (
f"Bq and Bkv must broadcast. Got Bq={Bq} and Bkv={Bkv}"
)
actual_grad_key = torch.sum(actual_grad_key, 0, keepdim=True)
actual_grad_value = torch.sum(actual_grad_value, 0, keepdim=True)
score_mod_other_buffer_grads = [
actual_grad.copy_(grad) if isinstance(actual_grad, torch.Tensor) else None
for actual_grad, grad in zip(
actual_grad_score_mod_captured, grad_score_mod_captured
)
]
return (
actual_grad_query,
actual_grad_key,
actual_grad_value,
tuple(score_mod_other_buffer_grads),
)
def trace_flex_attention_backward(
proxy_mode: ProxyTorchDispatchMode,
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
out: torch.Tensor,
logsumexp: torch.Tensor,
grad_out: torch.Tensor,
grad_logsumexp: torch.Tensor,
fw_graph: Union[Callable, GraphModule],
joint_graph: GraphModule,
block_mask: tuple,
scale: float,
kernel_options: dict[str, Any],
score_mod_other_buffers: tuple = (),
mask_mod_other_buffers: tuple = (),
) -> tuple[
torch.Tensor, torch.Tensor, torch.Tensor, tuple[Optional[torch.Tensor], ...]
]:
"""We already have the forward graph and joint graph from the forward pass, so we create a proxy attach both graphs"""
from torch._dynamo._trace_wrapped_higher_order_op import TransformGetItemToIndex
example_out = flex_attention_backward(
query,
key,
value,
out,
logsumexp,
grad_out,
grad_logsumexp,
fw_graph,
joint_graph,
block_mask,
scale,
kernel_options,
score_mod_other_buffers,
mask_mod_other_buffers,
)
requires_grad = any(pytree.tree_map(lambda x: x.requires_grad, (query, key)))
fw_example_vals = [query.new_zeros((), requires_grad=requires_grad)] + [
query.new_zeros((), dtype=torch.int) for _ in range(4)
]
bw_example_vals = fw_example_vals + [query.new_zeros(())]
mask_example_vals = [query.new_zeros((), dtype=torch.int) for _ in range(4)]
mask_graph = block_mask[-1]
with TransformGetItemToIndex():
# There's no active make_fx during the compiled autograd graph's initial capture
fw_graph = _maybe_reenter_make_fx(fw_graph)(
*fw_example_vals, *score_mod_other_buffers
)
joint_graph = _maybe_reenter_make_fx(joint_graph)(
*bw_example_vals, *score_mod_other_buffers
)
mask_graph = _maybe_reenter_make_fx(mask_graph)(
*mask_example_vals, *mask_mod_other_buffers
)
assert isinstance(proxy_mode.tracer, torch.fx.Tracer)
block_mask = block_mask[:-1] + (mask_graph,)
qualname = proxy_mode.tracer.get_fresh_qualname("fw_graph")
proxy_mode.tracer.root.register_module(qualname, fw_graph) # type: ignore[arg-type]
qualname = proxy_mode.tracer.get_fresh_qualname("joint_graph")
proxy_mode.tracer.root.register_module(qualname, joint_graph)
qualname = proxy_mode.tracer.get_fresh_qualname("mask_graph")
proxy_mode.tracer.root.register_module(qualname, mask_graph)
node_args = (
query,
key,
value,
out,
logsumexp,
grad_out,
grad_logsumexp,
fw_graph,
joint_graph,
block_mask,
scale,
kernel_options,
score_mod_other_buffers,
mask_mod_other_buffers,
)
# pyrefly: ignore [missing-attribute]
proxy_args = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, node_args)
out_proxy = proxy_mode.tracer.create_proxy(
"call_function",
flex_attention_backward,
proxy_args,
{},
name="flex_attention_backward",
)
return track_tensor_tree(
example_out,
out_proxy,
constant=None,
# pyrefly: ignore [bad-argument-type]
tracer=proxy_mode.tracer,
)
@flex_attention_backward.py_impl(ProxyTorchDispatchMode)
def flex_attention_backward_proxy_torch_dispatch_mode(
mode: ProxyTorchDispatchMode,
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
out: torch.Tensor,
logsumexp: torch.Tensor,
grad_out: torch.Tensor,
grad_logsumexp: torch.Tensor,
fw_graph: Union[Callable, GraphModule],
joint_graph: GraphModule,
block_mask: tuple,
scale: float,
kernel_options: dict[str, Any],
score_mod_other_buffers: tuple = (),
mask_mod_other_buffers: tuple = (),
) -> tuple[
torch.Tensor, torch.Tensor, torch.Tensor, tuple[Optional[torch.Tensor], ...]
]:
assert mode is not None, "Mode should always be enabled for python fallback key"
with torch.fx.experimental.proxy_tensor.set_original_aten_op(
flex_attention_backward
):
return trace_flex_attention_backward(
mode,
query,
key,
value,
out,
logsumexp,
grad_out,
grad_logsumexp,
fw_graph,
joint_graph,
block_mask,
scale,
kernel_options,
score_mod_other_buffers,
mask_mod_other_buffers,
)
@flex_attention_backward.py_functionalize_impl
def flex_attention_backward_functionalize(
ctx: torch._subclasses.functional_tensor.BaseFunctionalizeAPI,
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
out: torch.Tensor,
logsumexp: torch.Tensor,
grad_out: torch.Tensor,
grad_logsumexp: torch.Tensor,
fw_graph: Union[Callable, GraphModule],
joint_graph: GraphModule,
block_mask: tuple,
scale: float,
kernel_options: dict[str, Any],
score_mod_other_buffers: tuple = (),
mask_mod_other_buffers: tuple = (),
) -> tuple[
torch.Tensor, torch.Tensor, torch.Tensor, tuple[Optional[torch.Tensor], ...]
]:
"""Defines the functionalization rules for the flex_attention operator.
Write now we are unwrapping each tensor and then redispatching to the next,
since we know that the forward score mod function is assured to be free of mutations
to the other_buffers, we skip that mutate check and go straight to redispatching.
"""
if has_user_subclass(
(
query,
key,
value,
out,
logsumexp,
grad_out,
grad_logsumexp,
block_mask,
scale,
kernel_options,
score_mod_other_buffers,
mask_mod_other_buffers,
),
allowed_subclasses=(FakeTensor, FunctionalTensor),
):
return NotImplemented
query_unwrapped = ctx.unwrap_tensors(query)
key_unwrapped = ctx.unwrap_tensors(key)
value_unwrapped = ctx.unwrap_tensors(value)
out_unwrapped = ctx.unwrap_tensors(out)
logsumexp_unwrapped = ctx.unwrap_tensors(logsumexp)
grad_out_unwrapped = ctx.unwrap_tensors(grad_out)
grad_logsumexp_unwrapped = ctx.unwrap_tensors(grad_logsumexp)
block_mask_unwrapped = ctx.unwrap_tensors(block_mask)
score_mod_other_buffers_unwrapped = ctx.unwrap_tensors(score_mod_other_buffers)
mask_mod_other_buffers_unwrapped = ctx.unwrap_tensors(mask_mod_other_buffers)
# Appease the mypy overlords
assert isinstance(query_unwrapped, torch.Tensor)
assert isinstance(key_unwrapped, torch.Tensor)
assert isinstance(value_unwrapped, torch.Tensor)
assert isinstance(out_unwrapped, torch.Tensor)
assert isinstance(logsumexp_unwrapped, torch.Tensor)
assert isinstance(grad_out_unwrapped, torch.Tensor)
assert isinstance(grad_logsumexp_unwrapped, torch.Tensor)
assert isinstance(block_mask_unwrapped, tuple)
assert isinstance(score_mod_other_buffers_unwrapped, tuple)
assert isinstance(mask_mod_other_buffers_unwrapped, tuple)
with ctx.redispatch_to_next():
functional_fw_graph = ctx.functionalize(fw_graph)
functional_joint_graph = ctx.functionalize(joint_graph)
(
grad_query,
grad_key,
grad_value,
grad_score_mod_captured,
) = flex_attention_backward(
query_unwrapped,
key_unwrapped,
value_unwrapped,
out_unwrapped,
logsumexp_unwrapped,
grad_out_unwrapped,
grad_logsumexp_unwrapped,
functional_fw_graph, # type: ignore[arg-type]
functional_joint_graph, # type: ignore[arg-type]
block_mask_unwrapped,
scale,
kernel_options,
score_mod_other_buffers_unwrapped,
mask_mod_other_buffers_unwrapped,
)
return ctx.wrap_tensors((grad_query, grad_key, grad_value, grad_score_mod_captured)) # type: ignore[return-value,arg-type]
@register_fake(flex_attention_backward)
def flex_attention_backward_fake_tensor_mode(
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
out: torch.Tensor,
logsumexp: torch.Tensor,
grad_out: torch.Tensor,
grad_logsumexp: torch.Tensor,
fw_graph: Union[Callable, GraphModule],
joint_graph: GraphModule,
block_mask: tuple,
scale: float,
kernel_options: dict[str, Any],
score_mod_other_buffers: tuple = (),
mask_mod_other_buffers: tuple = (),
) -> tuple[
torch.Tensor, torch.Tensor, torch.Tensor, tuple[Optional[torch.Tensor], ...]
]:
if has_user_subclass(
(
query,
key,
value,
out,
logsumexp,
grad_out,
grad_logsumexp,
block_mask,
scale,
kernel_options,
score_mod_other_buffers,
mask_mod_other_buffers,
),
allowed_subclasses=(FakeTensor,),
):
return NotImplemented
Bq, _, _, qk_head_dim = query.shape
Bkv, Hkv, seq_len_kv, v_head_dim = value.shape
grad_query = torch.empty_like(query)
# zeros_and_scatter creates a contiguous zeros tensor -> contiguous_format
grad_score_mod_captured = tuple(
(
torch.empty_like(buffer, memory_format=torch.contiguous_format)
if isinstance(buffer, torch.Tensor)
else None
)
for buffer in score_mod_other_buffers
)
broadcasted_grad_key = key.new_empty((Bq, Hkv, seq_len_kv, qk_head_dim))
broadcasted_grad_key = _permute_strides(broadcasted_grad_key, key.stride())
broadcasted_grad_value = value.new_empty((Bq, Hkv, seq_len_kv, v_head_dim))
broadcasted_grad_value = _permute_strides(broadcasted_grad_value, value.stride())
if Bq > 1 and Bkv == 1:
grad_key = torch.sum(broadcasted_grad_key, dim=0, keepdim=True)
grad_value = torch.sum(broadcasted_grad_value, dim=0, keepdim=True)
else:
grad_key = broadcasted_grad_key
grad_value = broadcasted_grad_value
return grad_query, grad_key, grad_value, grad_score_mod_captured
flex_attention_backward.py_autograd_impl(
autograd_not_implemented(flex_attention_backward, deferred_error=True)
)
| FlexAttentionAutogradOp |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/mssql/base.py | {
"start": 37620,
"end": 37971
} | class ____(sqltypes.REAL):
"""the SQL Server REAL datatype."""
def __init__(self, **kw):
# REAL is a synonym for FLOAT(24) on SQL server.
# it is only accepted as the word "REAL" in DDL, the numeric
# precision value is not allowed to be present
kw.setdefault("precision", 24)
super().__init__(**kw)
| REAL |
python | pandas-dev__pandas | pandas/tests/indexes/interval/test_constructors.py | {
"start": 528,
"end": 7757
} | class ____:
"""
Common tests for all variations of IntervalIndex construction. Input data
to be supplied in breaks format, then converted by the subclass method
get_kwargs_from_breaks to the expected format.
"""
@pytest.mark.parametrize(
"breaks_and_expected_subtype",
[
([3, 14, 15, 92, 653], np.int64),
(np.arange(10, dtype="int64"), np.int64),
(Index(np.arange(-10, 11, dtype=np.int64)), np.int64),
(Index(np.arange(10, 31, dtype=np.uint64)), np.uint64),
(Index(np.arange(20, 30, 0.5), dtype=np.float64), np.float64),
(date_range("20180101", periods=10, unit="ns"), "M8[ns]"),
(
date_range("20180101", periods=10, tz="US/Eastern", unit="ns"),
"datetime64[ns, US/Eastern]",
),
(timedelta_range("1 day", periods=10), "m8[ns]"),
],
)
@pytest.mark.parametrize("name", [None, "foo"])
def test_constructor(self, constructor, breaks_and_expected_subtype, closed, name):
breaks, expected_subtype = breaks_and_expected_subtype
result_kwargs = self.get_kwargs_from_breaks(breaks, closed)
result = constructor(closed=closed, name=name, **result_kwargs)
assert result.closed == closed
assert result.name == name
assert result.dtype.subtype == expected_subtype
tm.assert_index_equal(result.left, Index(breaks[:-1], dtype=expected_subtype))
tm.assert_index_equal(result.right, Index(breaks[1:], dtype=expected_subtype))
@pytest.mark.parametrize(
"breaks, subtype",
[
(Index([0, 1, 2, 3, 4], dtype=np.int64), "float64"),
(Index([0, 1, 2, 3, 4], dtype=np.int64), "datetime64[ns]"),
(Index([0, 1, 2, 3, 4], dtype=np.int64), "timedelta64[ns]"),
(Index([0, 1, 2, 3, 4], dtype=np.float64), "int64"),
(date_range("2017-01-01", periods=5, unit="ns"), "int64"),
(timedelta_range("1 day", periods=5), "int64"),
],
)
def test_constructor_dtype(self, constructor, breaks, subtype):
# GH 19262: conversion via dtype parameter
expected_kwargs = self.get_kwargs_from_breaks(breaks.astype(subtype))
expected = constructor(**expected_kwargs)
result_kwargs = self.get_kwargs_from_breaks(breaks)
iv_dtype = IntervalDtype(subtype, "right")
for dtype in (iv_dtype, str(iv_dtype)):
result = constructor(dtype=dtype, **result_kwargs)
tm.assert_index_equal(result, expected)
@pytest.mark.parametrize(
"breaks",
[
Index([0, 1, 2, 3, 4], dtype=np.int64),
Index([0, 1, 2, 3, 4], dtype=np.uint64),
Index([0, 1, 2, 3, 4], dtype=np.float64),
date_range("2017-01-01", periods=5, unit="ns"),
timedelta_range("1 day", periods=5),
],
)
def test_constructor_pass_closed(self, constructor, breaks):
# not passing closed to IntervalDtype, but to IntervalArray constructor
iv_dtype = IntervalDtype(breaks.dtype)
result_kwargs = self.get_kwargs_from_breaks(breaks)
for dtype in (iv_dtype, str(iv_dtype)):
with tm.assert_produces_warning(None):
result = constructor(dtype=dtype, closed="left", **result_kwargs)
assert result.dtype.closed == "left"
@pytest.mark.parametrize("breaks", [[np.nan] * 2, [np.nan] * 4, [np.nan] * 50])
def test_constructor_nan(self, constructor, breaks, closed):
# GH 18421
result_kwargs = self.get_kwargs_from_breaks(breaks)
result = constructor(closed=closed, **result_kwargs)
expected_subtype = np.float64
expected_values = np.array(breaks[:-1], dtype=object)
assert result.closed == closed
assert result.dtype.subtype == expected_subtype
tm.assert_numpy_array_equal(np.array(result), expected_values)
@pytest.mark.parametrize(
"breaks",
[
[],
np.array([], dtype="int64"),
np.array([], dtype="uint64"),
np.array([], dtype="float64"),
np.array([], dtype="datetime64[ns]"),
np.array([], dtype="timedelta64[ns]"),
],
)
def test_constructor_empty(self, constructor, breaks, closed):
# GH 18421
result_kwargs = self.get_kwargs_from_breaks(breaks)
result = constructor(closed=closed, **result_kwargs)
expected_values = np.array([], dtype=object)
expected_subtype = getattr(breaks, "dtype", np.int64)
assert result.empty
assert result.closed == closed
assert result.dtype.subtype == expected_subtype
tm.assert_numpy_array_equal(np.array(result), expected_values)
@pytest.mark.parametrize(
"breaks",
[
tuple("0123456789"),
list("abcdefghij"),
np.array(list("abcdefghij"), dtype=object),
np.array(list("abcdefghij"), dtype="<U1"),
],
)
def test_constructor_string(self, constructor, breaks):
# GH 19016
msg = (
"category, object, and string subtypes are not supported for IntervalIndex"
)
with pytest.raises(TypeError, match=msg):
constructor(**self.get_kwargs_from_breaks(breaks))
@pytest.mark.parametrize("cat_constructor", [Categorical, CategoricalIndex])
def test_constructor_categorical_valid(self, constructor, cat_constructor):
# GH 21243/21253
breaks = np.arange(10, dtype="int64")
expected = IntervalIndex.from_breaks(breaks)
cat_breaks = cat_constructor(breaks)
result_kwargs = self.get_kwargs_from_breaks(cat_breaks)
result = constructor(**result_kwargs)
tm.assert_index_equal(result, expected)
def test_generic_errors(self, constructor):
# filler input data to be used when supplying invalid kwargs
filler = self.get_kwargs_from_breaks(range(10))
# invalid closed
msg = "closed must be one of 'right', 'left', 'both', 'neither'"
with pytest.raises(ValueError, match=msg):
constructor(closed="invalid", **filler)
# unsupported dtype
msg = "dtype must be an IntervalDtype, got int64"
with pytest.raises(TypeError, match=msg):
constructor(dtype="int64", **filler)
# invalid dtype
msg = "data type [\"']invalid[\"'] not understood"
with pytest.raises(TypeError, match=msg):
constructor(dtype="invalid", **filler)
# no point in nesting periods in an IntervalIndex
periods = period_range("2000-01-01", periods=10)
periods_kwargs = self.get_kwargs_from_breaks(periods)
msg = "Period dtypes are not supported, use a PeriodIndex instead"
with pytest.raises(ValueError, match=msg):
constructor(**periods_kwargs)
# decreasing values
decreasing_kwargs = self.get_kwargs_from_breaks(range(10, -1, -1))
msg = "left side of interval must be <= right side"
with pytest.raises(ValueError, match=msg):
constructor(**decreasing_kwargs)
| ConstructorTests |
python | geekcomputers__Python | venv/Lib/site-packages/pip/_internal/models/wheel.py | {
"start": 259,
"end": 3601
} | class ____:
"""A wheel file"""
wheel_file_re = re.compile(
r"""^(?P<namever>(?P<name>[^\s-]+?)-(?P<ver>[^\s-]*?))
((-(?P<build>\d[^-]*?))?-(?P<pyver>[^\s-]+?)-(?P<abi>[^\s-]+?)-(?P<plat>[^\s-]+?)
\.whl|\.dist-info)$""",
re.VERBOSE,
)
def __init__(self, filename: str) -> None:
"""
:raises InvalidWheelFilename: when the filename is invalid for a wheel
"""
wheel_info = self.wheel_file_re.match(filename)
if not wheel_info:
raise InvalidWheelFilename(f"{filename} is not a valid wheel filename.")
self.filename = filename
self.name = wheel_info.group("name").replace("_", "-")
# we'll assume "_" means "-" due to wheel naming scheme
# (https://github.com/pypa/pip/issues/1150)
self.version = wheel_info.group("ver").replace("_", "-")
self.build_tag = wheel_info.group("build")
self.pyversions = wheel_info.group("pyver").split(".")
self.abis = wheel_info.group("abi").split(".")
self.plats = wheel_info.group("plat").split(".")
# All the tag combinations from this file
self.file_tags = {
Tag(x, y, z) for x in self.pyversions for y in self.abis for z in self.plats
}
def get_formatted_file_tags(self) -> List[str]:
"""Return the wheel's tags as a sorted list of strings."""
return sorted(str(tag) for tag in self.file_tags)
def support_index_min(self, tags: List[Tag]) -> int:
"""Return the lowest index that one of the wheel's file_tag combinations
achieves in the given list of supported tags.
For example, if there are 8 supported tags and one of the file tags
is first in the list, then return 0.
:param tags: the PEP 425 tags to check the wheel against, in order
with most preferred first.
:raises ValueError: If none of the wheel's file tags match one of
the supported tags.
"""
try:
return next(i for i, t in enumerate(tags) if t in self.file_tags)
except StopIteration:
raise ValueError()
def find_most_preferred_tag(
self, tags: List[Tag], tag_to_priority: Dict[Tag, int]
) -> int:
"""Return the priority of the most preferred tag that one of the wheel's file
tag combinations achieves in the given list of supported tags using the given
tag_to_priority mapping, where lower priorities are more-preferred.
This is used in place of support_index_min in some cases in order to avoid
an expensive linear scan of a large list of tags.
:param tags: the PEP 425 tags to check the wheel against.
:param tag_to_priority: a mapping from tag to priority of that tag, where
lower is more preferred.
:raises ValueError: If none of the wheel's file tags match one of
the supported tags.
"""
return min(
tag_to_priority[tag] for tag in self.file_tags if tag in tag_to_priority
)
def supported(self, tags: Iterable[Tag]) -> bool:
"""Return whether the wheel is compatible with one of the given tags.
:param tags: the PEP 425 tags to check the wheel against.
"""
return not self.file_tags.isdisjoint(tags)
| Wheel |
python | neetcode-gh__leetcode | python/0042-trapping-rain-water.py | {
"start": 0,
"end": 534
} | class ____:
def trap(self, height: List[int]) -> int:
if not height:
return 0
l, r = 0, len(height) - 1
leftMax, rightMax = height[l], height[r]
res = 0
while l < r:
if leftMax < rightMax:
l += 1
leftMax = max(leftMax, height[l])
res += leftMax - height[l]
else:
r -= 1
rightMax = max(rightMax, height[r])
res += rightMax - height[r]
return res
| Solution |
python | sqlalchemy__sqlalchemy | test/orm/test_session.py | {
"start": 13135,
"end": 20725
} | class ____(_fixtures.FixtureTest):
run_inserts = None
def test_close_all_sessions(self):
users, User = self.tables.users, self.classes.User
self.mapper_registry.map_imperatively(User, users)
s1 = fixture_session()
u1 = User()
s1.add(u1)
s2 = fixture_session()
u2 = User()
s2.add(u2)
assert u1 in s1
assert u2 in s2
close_all_sessions()
assert u1 not in s1
assert u2 not in s2
def test_session_close_all_deprecated(self):
users, User = self.tables.users, self.classes.User
self.mapper_registry.map_imperatively(User, users)
s1 = fixture_session()
u1 = User()
s1.add(u1)
s2 = fixture_session()
u2 = User()
s2.add(u2)
assert u1 in s1
assert u2 in s2
close_all_sessions()
assert u1 not in s1
assert u2 not in s2
@testing.combinations((object_session,), (Session.object_session,))
def test_object_session_raises(self, objsession):
User = self.classes.User
assert_raises(orm_exc.UnmappedInstanceError, objsession, object())
assert_raises(orm_exc.UnmappedInstanceError, objsession, User())
def test_make_transient(self):
users, User = self.tables.users, self.classes.User
self.mapper_registry.map_imperatively(User, users)
sess = fixture_session(autoflush=False)
sess.add(User(name="test"))
sess.flush()
u1 = sess.query(User).first()
make_transient(u1)
assert u1 not in sess
sess.add(u1)
assert u1 in sess.new
u1 = sess.query(User).first()
sess.expunge(u1)
make_transient(u1)
sess.add(u1)
assert u1 in sess.new
# test expired attributes
# get unexpired
u1 = sess.query(User).first()
sess.expire(u1)
make_transient(u1)
assert u1.id is None
assert u1.name is None
# works twice
make_transient(u1)
sess.close()
u1.name = "test2"
sess.add(u1)
sess.flush()
assert u1 in sess
sess.delete(u1)
sess.flush()
assert u1 not in sess
assert_raises(exc.InvalidRequestError, sess.add, u1)
make_transient(u1)
sess.add(u1)
sess.flush()
assert u1 in sess
def test_make_transient_plus_rollback(self):
# test for [ticket:2182]
users, User = self.tables.users, self.classes.User
self.mapper_registry.map_imperatively(User, users)
sess = fixture_session()
u1 = User(name="test")
sess.add(u1)
sess.commit()
sess.delete(u1)
sess.flush()
make_transient(u1)
sess.rollback()
assert attributes.instance_state(u1).transient
def test_make_transient_to_detached(self):
users, User = self.tables.users, self.classes.User
self.mapper_registry.map_imperatively(User, users)
sess = fixture_session()
u1 = User(id=1, name="test")
sess.add(u1)
sess.commit()
sess.close()
u2 = User(id=1)
make_transient_to_detached(u2)
assert "id" in u2.__dict__
sess.add(u2)
eq_(u2.name, "test")
def test_make_transient_to_detached_no_session_allowed(self):
users, User = self.tables.users, self.classes.User
self.mapper_registry.map_imperatively(User, users)
sess = fixture_session()
u1 = User(id=1, name="test")
sess.add(u1)
assert_raises_message(
exc.InvalidRequestError,
"Given object must be transient",
make_transient_to_detached,
u1,
)
def test_make_transient_to_detached_no_key_allowed(self):
users, User = self.tables.users, self.classes.User
self.mapper_registry.map_imperatively(User, users)
sess = fixture_session()
u1 = User(id=1, name="test")
sess.add(u1)
sess.commit()
sess.expunge(u1)
assert_raises_message(
exc.InvalidRequestError,
"Given object must be transient",
make_transient_to_detached,
u1,
)
@testing.variation(
"arg", ["execution_options", "identity_token", "bind_arguments"]
)
def test_get_arguments(self, arg: testing.Variation) -> None:
users, User = self.tables.users, self.classes.User
self.mapper_registry.map_imperatively(User, users)
sess = fixture_session()
called = False
@event.listens_for(sess, "do_orm_execute")
def check(ctx: ORMExecuteState) -> None:
nonlocal called
called = True
if arg.execution_options:
eq_(ctx.execution_options["foo"], "bar")
elif arg.bind_arguments:
eq_(ctx.bind_arguments["foo"], "bar")
elif arg.identity_token:
eq_(ctx.load_options._identity_token, "foobar")
else:
arg.fail()
if arg.execution_options:
sess.get(User, 42, execution_options={"foo": "bar"})
elif arg.bind_arguments:
sess.get(User, 42, bind_arguments={"foo": "bar"})
elif arg.identity_token:
sess.get(User, 42, identity_token="foobar")
else:
arg.fail()
sess.close()
is_true(called)
def test_get(self):
users, User = self.tables.users, self.classes.User
self.mapper_registry.map_imperatively(User, users)
s = fixture_session()
s.execute(
insert(self.tables.users),
[{"id": 7, "name": "7"}, {"id": 19, "name": "19"}],
)
assertions.is_not_none(s.get(User, 19))
u = s.get(User, 7)
u2 = s.get(User, 7)
assertions.is_not_none(u)
is_(u, u2)
s.expunge_all()
u2 = s.get(User, 7)
is_not(u, u2)
def test_get_one(self):
users, User = self.tables.users, self.classes.User
self.mapper_registry.map_imperatively(User, users)
s = fixture_session()
s.execute(
insert(self.tables.users),
[{"id": 7, "name": "7"}, {"id": 19, "name": "19"}],
)
u = s.get_one(User, 7)
u2 = s.get_one(User, 7)
assertions.is_not_none(u)
is_(u, u2)
s.expunge_all()
u2 = s.get_one(User, 7)
is_not(u, u2)
def test_get_one_2(self):
users, User = self.tables.users, self.classes.User
self.mapper_registry.map_imperatively(User, users)
sess = fixture_session()
user1 = User(id=1, name="u1")
sess.add(user1)
sess.commit()
u1 = sess.get_one(User, user1.id)
eq_(user1.name, u1.name)
with expect_raises_message(
sa.exc.NoResultFound, "No row was found when one was required"
):
sess.get_one(User, 2)
def test_delete_all(self):
users, User = self.tables.users, self.classes.User
self.mapper_registry.map_imperatively(User, users)
sess = fixture_session()
sess.add_all([User(id=1, name="u1"), User(id=2, name="u2")])
sess.commit()
sess.close()
ua, ub = sess.scalars(select(User)).all()
eq_([ua in sess, ub in sess], [True, True])
sess.delete_all([ua, ub])
sess.flush()
eq_([ua in sess, ub in sess], [False, False])
eq_(sess.scalars(select(User)).all(), [])
| SessionUtilTest |
python | django__django | tests/m2m_regress/models.py | {
"start": 570,
"end": 857
} | class ____(Tag):
tags = models.ManyToManyField(Tag, related_name="tag_collections")
def __str__(self):
return self.name
# A related_name is required on one of the ManyToManyField entries here because
# they are both addressable as reverse relations from Tag.
| TagCollection |
python | arrow-py__arrow | arrow/locales.py | {
"start": 42436,
"end": 44648
} | class ____(SlavicBaseLocale):
names = ["mk-latn", "mk-mk-latn"]
past = "pred {0}"
future = "za {0}"
timeframes: ClassVar[Mapping[TimeFrameLiteral, Union[str, Mapping[str, str]]]] = {
"now": "sega",
"second": "edna sekunda",
"seconds": {
"singular": "{0} sekunda",
"dual": "{0} sekundi",
"plural": "{0} sekundi",
},
"minute": "edna minuta",
"minutes": {
"singular": "{0} minuta",
"dual": "{0} minuti",
"plural": "{0} minuti",
},
"hour": "eden saat",
"hours": {"singular": "{0} saat", "dual": "{0} saati", "plural": "{0} saati"},
"day": "eden den",
"days": {"singular": "{0} den", "dual": "{0} dena", "plural": "{0} dena"},
"week": "edna nedela",
"weeks": {
"singular": "{0} nedela",
"dual": "{0} nedeli",
"plural": "{0} nedeli",
},
"month": "eden mesec",
"months": {
"singular": "{0} mesec",
"dual": "{0} meseci",
"plural": "{0} meseci",
},
"year": "edna godina",
"years": {
"singular": "{0} godina",
"dual": "{0} godini",
"plural": "{0} godini",
},
}
meridians = {"am": "dp", "pm": "pp", "AM": "pretpladne", "PM": "popladne"}
month_names = [
"",
"Januari",
"Fevruari",
"Mart",
"April",
"Maj",
"Juni",
"Juli",
"Avgust",
"Septemvri",
"Oktomvri",
"Noemvri",
"Dekemvri",
]
month_abbreviations = [
"",
"Jan",
"Fev",
"Mar",
"Apr",
"Maj",
"Jun",
"Jul",
"Avg",
"Sep",
"Okt",
"Noe",
"Dek",
]
day_names = [
"",
"Ponedelnik",
"Vtornik",
"Sreda",
"Chetvrtok",
"Petok",
"Sabota",
"Nedela",
]
day_abbreviations = [
"",
"Pon",
"Vt",
"Sre",
"Chet",
"Pet",
"Sab",
"Ned",
]
| MacedonianLatinLocale |
python | matplotlib__matplotlib | lib/matplotlib/backends/backend_webagg_core.py | {
"start": 3746,
"end": 4690
} | class ____(backend_bases.TimerBase):
def __init__(self, *args, **kwargs):
self._task = None
super().__init__(*args, **kwargs)
async def _timer_task(self, interval):
while True:
try:
await asyncio.sleep(interval)
self._on_timer()
if self._single:
break
except asyncio.CancelledError:
break
def _timer_start(self):
self._timer_stop()
self._task = asyncio.ensure_future(
self._timer_task(max(self.interval / 1_000., 1e-6))
)
def _timer_stop(self):
if self._task is not None:
self._task.cancel()
self._task = None
def _timer_set_interval(self):
# Only stop and restart it if the timer has already been started
if self._task is not None:
self._timer_stop()
self._timer_start()
| TimerAsyncio |
python | getsentry__sentry | src/sentry/issues/endpoints/organization_group_suspect_flags.py | {
"start": 631,
"end": 780
} | class ____(TypedDict):
flag: str
score: float
baseline_percent: float
distribution: Distribution
is_filtered: bool
| ResponseDataItem |
python | huggingface__transformers | src/transformers/models/minimax/modular_minimax.py | {
"start": 28838,
"end": 28917
} | class ____(MixtralForTokenClassification):
pass
| MiniMaxForTokenClassification |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/sensors/test_bedrock.py | {
"start": 5638,
"end": 7858
} | class ____:
SENSOR = BedrockKnowledgeBaseActiveSensor
def setup_method(self):
self.default_op_kwargs = dict(
task_id="test_bedrock_knowledge_base_active_sensor",
knowledge_base_id="knowledge_base_id",
poke_interval=5,
max_retries=1,
)
self.sensor = self.SENSOR(**self.default_op_kwargs, aws_conn_id=None)
def test_base_aws_op_attributes(self):
op = self.SENSOR(**self.default_op_kwargs)
assert op.hook.aws_conn_id == "aws_default"
assert op.hook._region_name is None
assert op.hook._verify is None
assert op.hook._config is None
op = self.SENSOR(
**self.default_op_kwargs,
aws_conn_id="aws-test-custom-conn",
region_name="eu-west-1",
verify=False,
botocore_config={"read_timeout": 42},
)
assert op.hook.aws_conn_id == "aws-test-custom-conn"
assert op.hook._region_name == "eu-west-1"
assert op.hook._verify is False
assert op.hook._config is not None
assert op.hook._config.read_timeout == 42
@pytest.mark.parametrize("state", SENSOR.SUCCESS_STATES)
@mock.patch.object(BedrockAgentHook, "conn")
def test_poke_success_states(self, mock_conn, state):
mock_conn.get_knowledge_base.return_value = {"knowledgeBase": {"status": state}}
assert self.sensor.poke({}) is True
@pytest.mark.parametrize("state", SENSOR.INTERMEDIATE_STATES)
@mock.patch.object(BedrockAgentHook, "conn")
def test_poke_intermediate_states(self, mock_conn, state):
mock_conn.get_knowledge_base.return_value = {"knowledgeBase": {"status": state}}
assert self.sensor.poke({}) is False
@pytest.mark.parametrize("state", SENSOR.FAILURE_STATES)
@mock.patch.object(BedrockAgentHook, "conn")
def test_poke_failure_states(self, mock_conn, state):
mock_conn.get_knowledge_base.return_value = {"knowledgeBase": {"status": state}}
sensor = self.SENSOR(**self.default_op_kwargs, aws_conn_id=None)
with pytest.raises(AirflowException, match=sensor.FAILURE_MESSAGE):
sensor.poke({})
| TestBedrockKnowledgeBaseActiveSensor |
python | huggingface__transformers | tests/models/mobilevit/test_modeling_mobilevit.py | {
"start": 1391,
"end": 1751
} | class ____(ConfigTester):
def create_and_test_config_common_properties(self):
config = self.config_class(**self.inputs_dict)
self.parent.assertTrue(hasattr(config, "hidden_sizes"))
self.parent.assertTrue(hasattr(config, "neck_hidden_sizes"))
self.parent.assertTrue(hasattr(config, "num_attention_heads"))
| MobileViTConfigTester |
python | python-openxml__python-docx | src/docx/oxml/coreprops.py | {
"start": 442,
"end": 10768
} | class ____(BaseOxmlElement):
"""`<cp:coreProperties>` element, the root element of the Core Properties part.
Stored as `/docProps/core.xml`. Implements many of the Dublin Core document metadata
elements. String elements resolve to an empty string ("") if the element is not
present in the XML. String elements are limited in length to 255 unicode characters.
"""
get_or_add_revision: Callable[[], etree_Element]
category = ZeroOrOne("cp:category", successors=())
contentStatus = ZeroOrOne("cp:contentStatus", successors=())
created = ZeroOrOne("dcterms:created", successors=())
creator = ZeroOrOne("dc:creator", successors=())
description = ZeroOrOne("dc:description", successors=())
identifier = ZeroOrOne("dc:identifier", successors=())
keywords = ZeroOrOne("cp:keywords", successors=())
language = ZeroOrOne("dc:language", successors=())
lastModifiedBy = ZeroOrOne("cp:lastModifiedBy", successors=())
lastPrinted = ZeroOrOne("cp:lastPrinted", successors=())
modified = ZeroOrOne("dcterms:modified", successors=())
revision: etree_Element | None = ZeroOrOne( # pyright: ignore[reportAssignmentType]
"cp:revision", successors=()
)
subject = ZeroOrOne("dc:subject", successors=())
title = ZeroOrOne("dc:title", successors=())
version = ZeroOrOne("cp:version", successors=())
_coreProperties_tmpl = "<cp:coreProperties %s/>\n" % nsdecls("cp", "dc", "dcterms")
@classmethod
def new(cls) -> CT_CoreProperties:
"""Return a new `<cp:coreProperties>` element."""
xml = cls._coreProperties_tmpl
coreProperties = cast(CT_CoreProperties, parse_xml(xml))
return coreProperties
@property
def author_text(self) -> str:
"""The text in the `dc:creator` child element."""
return self._text_of_element("creator")
@author_text.setter
def author_text(self, value: str):
self._set_element_text("creator", value)
@property
def category_text(self) -> str:
return self._text_of_element("category")
@category_text.setter
def category_text(self, value: str):
self._set_element_text("category", value)
@property
def comments_text(self) -> str:
return self._text_of_element("description")
@comments_text.setter
def comments_text(self, value: str):
self._set_element_text("description", value)
@property
def contentStatus_text(self) -> str:
return self._text_of_element("contentStatus")
@contentStatus_text.setter
def contentStatus_text(self, value: str):
self._set_element_text("contentStatus", value)
@property
def created_datetime(self) -> dt.datetime | None:
return self._datetime_of_element("created")
@created_datetime.setter
def created_datetime(self, value: dt.datetime):
self._set_element_datetime("created", value)
@property
def identifier_text(self) -> str:
return self._text_of_element("identifier")
@identifier_text.setter
def identifier_text(self, value: str):
self._set_element_text("identifier", value)
@property
def keywords_text(self) -> str:
return self._text_of_element("keywords")
@keywords_text.setter
def keywords_text(self, value: str):
self._set_element_text("keywords", value)
@property
def language_text(self) -> str:
return self._text_of_element("language")
@language_text.setter
def language_text(self, value: str):
self._set_element_text("language", value)
@property
def lastModifiedBy_text(self) -> str:
return self._text_of_element("lastModifiedBy")
@lastModifiedBy_text.setter
def lastModifiedBy_text(self, value: str):
self._set_element_text("lastModifiedBy", value)
@property
def lastPrinted_datetime(self) -> dt.datetime | None:
return self._datetime_of_element("lastPrinted")
@lastPrinted_datetime.setter
def lastPrinted_datetime(self, value: dt.datetime):
self._set_element_datetime("lastPrinted", value)
@property
def modified_datetime(self) -> dt.datetime | None:
return self._datetime_of_element("modified")
@modified_datetime.setter
def modified_datetime(self, value: dt.datetime):
self._set_element_datetime("modified", value)
@property
def revision_number(self) -> int:
"""Integer value of revision property."""
revision = self.revision
if revision is None:
return 0
revision_str = str(revision.text)
try:
revision = int(revision_str)
except ValueError:
# non-integer revision strings also resolve to 0
revision = 0
# as do negative integers
if revision < 0:
revision = 0
return revision
@revision_number.setter
def revision_number(self, value: int):
"""Set revision property to string value of integer `value`."""
if not isinstance(value, int) or value < 1: # pyright: ignore[reportUnnecessaryIsInstance]
tmpl = "revision property requires positive int, got '%s'"
raise ValueError(tmpl % value)
revision = self.get_or_add_revision()
revision.text = str(value)
@property
def subject_text(self) -> str:
return self._text_of_element("subject")
@subject_text.setter
def subject_text(self, value: str):
self._set_element_text("subject", value)
@property
def title_text(self) -> str:
return self._text_of_element("title")
@title_text.setter
def title_text(self, value: str):
self._set_element_text("title", value)
@property
def version_text(self) -> str:
return self._text_of_element("version")
@version_text.setter
def version_text(self, value: str):
self._set_element_text("version", value)
def _datetime_of_element(self, property_name: str) -> dt.datetime | None:
element = getattr(self, property_name)
if element is None:
return None
datetime_str = element.text
try:
return self._parse_W3CDTF_to_datetime(datetime_str)
except ValueError:
# invalid datetime strings are ignored
return None
def _get_or_add(self, prop_name: str) -> BaseOxmlElement:
"""Return element returned by "get_or_add_" method for `prop_name`."""
get_or_add_method_name = "get_or_add_%s" % prop_name
get_or_add_method = getattr(self, get_or_add_method_name)
element = get_or_add_method()
return element
@classmethod
def _offset_dt(cls, dt_: dt.datetime, offset_str: str) -> dt.datetime:
"""A |datetime| instance offset from `dt_` by timezone offset in `offset_str`.
`offset_str` is like `"-07:00"`.
"""
match = cls._offset_pattern.match(offset_str)
if match is None:
raise ValueError("'%s' is not a valid offset string" % offset_str)
sign, hours_str, minutes_str = match.groups()
sign_factor = -1 if sign == "+" else 1
hours = int(hours_str) * sign_factor
minutes = int(minutes_str) * sign_factor
td = dt.timedelta(hours=hours, minutes=minutes)
return dt_ + td
_offset_pattern = re.compile(r"([+-])(\d\d):(\d\d)")
@classmethod
def _parse_W3CDTF_to_datetime(cls, w3cdtf_str: str) -> dt.datetime:
# valid W3CDTF date cases:
# yyyy e.g. "2003"
# yyyy-mm e.g. "2003-12"
# yyyy-mm-dd e.g. "2003-12-31"
# UTC timezone e.g. "2003-12-31T10:14:55Z"
# numeric timezone e.g. "2003-12-31T10:14:55-08:00"
templates = (
"%Y-%m-%dT%H:%M:%S",
"%Y-%m-%d",
"%Y-%m",
"%Y",
)
# strptime isn't smart enough to parse literal timezone offsets like
# "-07:30", so we have to do it ourselves
parseable_part = w3cdtf_str[:19]
offset_str = w3cdtf_str[19:]
dt_ = None
for tmpl in templates:
try:
dt_ = dt.datetime.strptime(parseable_part, tmpl)
except ValueError:
continue
if dt_ is None:
tmpl = "could not parse W3CDTF datetime string '%s'"
raise ValueError(tmpl % w3cdtf_str)
if len(offset_str) == 6:
dt_ = cls._offset_dt(dt_, offset_str)
return dt_.replace(tzinfo=dt.timezone.utc)
def _set_element_datetime(self, prop_name: str, value: dt.datetime) -> None:
"""Set date/time value of child element having `prop_name` to `value`."""
if not isinstance(value, dt.datetime): # pyright: ignore[reportUnnecessaryIsInstance]
tmpl = "property requires <type 'datetime.datetime'> object, got %s"
raise ValueError(tmpl % type(value))
element = self._get_or_add(prop_name)
dt_str = value.strftime("%Y-%m-%dT%H:%M:%SZ")
element.text = dt_str
if prop_name in ("created", "modified"):
# These two require an explicit "xsi:type="dcterms:W3CDTF""
# attribute. The first and last line are a hack required to add
# the xsi namespace to the root element rather than each child
# element in which it is referenced
self.set(qn("xsi:foo"), "bar")
element.set(qn("xsi:type"), "dcterms:W3CDTF")
del self.attrib[qn("xsi:foo")]
def _set_element_text(self, prop_name: str, value: Any) -> None:
"""Set string value of `name` property to `value`."""
if not isinstance(value, str):
value = str(value)
if len(value) > 255:
tmpl = "exceeded 255 char limit for property, got:\n\n'%s'"
raise ValueError(tmpl % value)
element = self._get_or_add(prop_name)
element.text = value
def _text_of_element(self, property_name: str) -> str:
"""The text in the element matching `property_name`.
The empty string if the element is not present or contains no text.
"""
element = getattr(self, property_name)
if element is None:
return ""
if element.text is None:
return ""
return element.text
| CT_CoreProperties |
python | scikit-learn__scikit-learn | sklearn/externals/_arff.py | {
"start": 20361,
"end": 21753
} | class ____:
def decode_rows(self, stream, conversors):
for row in stream:
values = _parse_values(row)
if not isinstance(values, dict):
raise BadLayout()
try:
yield {key: None if value is None else conversors[key](value)
for key, value in values.items()}
except ValueError as exc:
if 'float: ' in str(exc):
raise BadNumericalValue()
raise
except IndexError:
# conversor out of range
raise BadDataFormat(row)
def encode_data(self, data, attributes):
current_row = 0
num_attributes = len(attributes)
for row in data:
new_data = []
if len(row) > 0 and max(row) >= num_attributes:
raise BadObject(
'Instance %d has %d attributes, expected %d' %
(current_row, max(row) + 1, num_attributes)
)
for col in sorted(row):
v = row[col]
if v is None or v == '' or v != v:
s = '?'
else:
s = encode_string(str(v))
new_data.append("%d %s" % (col, s))
current_row += 1
yield " ".join(["{", ','.join(new_data), "}"])
| LODGeneratorData |
python | apache__airflow | airflow-core/src/airflow/api_fastapi/core_api/datamodels/ui/dashboard.py | {
"start": 1029,
"end": 1169
} | class ____(BaseModel):
"""DAG Run States for responses."""
queued: int
running: int
success: int
failed: int
| DAGRunStates |
python | pypa__hatch | src/hatch/project/frontend/core.py | {
"start": 332,
"end": 5430
} | class ____:
def __init__(self, project: Project, env: EnvironmentInterface) -> None:
self.__project = project
self.__env = env
self.__scripts = StandardBuildFrontendScripts(self.__project, self.__env)
self.__hatch = HatchBuildFrontend(self.__project, self.__env)
@property
def scripts(self) -> StandardBuildFrontendScripts:
return self.__scripts
@property
def hatch(self) -> HatchBuildFrontend:
return self.__hatch
def build_sdist(self, directory: Path) -> Path:
with self.__env.fs_context() as fs_context:
output_context = fs_context.join("output")
output_context.local_path.ensure_dir_exists()
script = self.scripts.build_sdist(project_root=self.__env.project_root, output_dir=output_context.env_path)
script_context = fs_context.join("build_sdist.py")
script_context.local_path.parent.ensure_dir_exists()
script_context.local_path.write_text(script)
script_context.sync_env()
context = ExecutionContext(self.__env)
context.add_shell_command(["python", "-u", script_context.env_path])
self.__env.app.execute_context(context)
output_context.sync_local()
output_path = output_context.local_path / "output.json"
output = json.loads(output_path.read_text())
work_dir = output_context.local_path / "work"
artifact_path = Path(work_dir / output["return_val"])
artifact_path.move(directory)
return directory / artifact_path.name
def build_wheel(self, directory: Path) -> Path:
with self.__env.fs_context() as fs_context:
output_context = fs_context.join("output")
output_context.local_path.ensure_dir_exists()
script = self.scripts.build_wheel(project_root=self.__env.project_root, output_dir=output_context.env_path)
script_context = fs_context.join("build_wheel.py")
script_context.local_path.parent.ensure_dir_exists()
script_context.local_path.write_text(script)
script_context.sync_env()
context = ExecutionContext(self.__env)
context.add_shell_command(["python", "-u", script_context.env_path])
self.__env.app.execute_context(context)
output_context.sync_local()
output_path = output_context.local_path / "output.json"
output = json.loads(output_path.read_text())
work_dir = output_context.local_path / "work"
artifact_path = Path(work_dir / output["return_val"])
artifact_path.move(directory)
return directory / artifact_path.name
def get_requires(self, build: Literal["sdist", "wheel", "editable"]) -> list[str]:
with self.__env.fs_context() as fs_context:
output_context = fs_context.join("output")
output_context.local_path.ensure_dir_exists()
script = self.scripts.get_requires(
project_root=self.__env.project_root, output_dir=output_context.env_path, build=build
)
script_context = fs_context.join(f"get_requires_{build}.py")
script_context.local_path.parent.ensure_dir_exists()
script_context.local_path.write_text(script)
script_context.sync_env()
context = ExecutionContext(self.__env)
context.add_shell_command(["python", "-u", script_context.env_path])
self.__env.app.execute_context(context)
output_context.sync_local()
output_path = output_context.local_path / "output.json"
output = json.loads(output_path.read_text())
return output["return_val"]
def get_core_metadata(self, *, editable: bool = False) -> dict[str, Any]:
from hatchling.metadata.spec import project_metadata_from_core_metadata
with self.__env.fs_context() as fs_context:
output_context = fs_context.join("output")
output_context.local_path.ensure_dir_exists()
script = self.scripts.prepare_metadata(
project_root=self.__env.project_root, output_dir=output_context.env_path, editable=editable
)
script_context = fs_context.join("get_core_metadata.py")
script_context.local_path.parent.ensure_dir_exists()
script_context.local_path.write_text(script)
script_context.sync_env()
context = ExecutionContext(self.__env)
context.add_shell_command(["python", "-u", script_context.env_path])
self.__env.app.execute_context(context)
output_context.sync_local()
output_path = output_context.local_path / "output.json"
output = json.loads(output_path.read_text())
work_dir = output_context.local_path / "work"
metadata_file = Path(work_dir) / output["return_val"] / "METADATA"
return project_metadata_from_core_metadata(metadata_file.read_text())
| BuildFrontend |
python | django-guardian__django-guardian | guardian/testapp/tests/test_indexes.py | {
"start": 604,
"end": 7292
} | class ____(TransactionTestCase):
"""Test database indexes for Guardian models."""
def setUp(self):
"""Set up test data."""
self.user = User.objects.create_user(username="testuser", email="test@example.com")
self.group = Group.objects.create(name="testgroup")
self.project = Project.objects.create(name="Test Project")
self.content_type = ContentType.objects.get_for_model(Project)
self.permission = Permission.objects.get(content_type=self.content_type, codename="add_project")
def test_userobjectpermission_indexes_exist(self):
"""Test that UserObjectPermission has the expected indexes."""
# Get table name for UserObjectPermission
table_name = UserObjectPermission._meta.db_table
# Get all indexes for the table
with connection.cursor() as cursor:
indexes = connection.introspection.get_constraints(cursor, table_name)
# Look for our specific indexes
index_fields_sets = []
for constraint_name, constraint_info in indexes.items():
if constraint_info.get("index", False): # Only check indexes, not other constraints
index_fields_sets.append(set(constraint_info["columns"]))
# Check if our expected indexes exist (using sets to ignore order)
expected_indexes = [
{"permission_id", "user_id", "content_type_id", "object_pk"},
{"user_id", "content_type_id", "object_pk"},
]
for expected_index in expected_indexes:
found = any(expected_index.issubset(index_set) for index_set in index_fields_sets)
self.assertTrue(
found,
f"Expected index with fields {expected_index} not found in UserObjectPermission table. "
f"Available indexes: {index_fields_sets}",
)
def test_groupobjectpermission_indexes_exist(self):
"""Test that GroupObjectPermission has the expected indexes."""
# Get table name for GroupObjectPermission
table_name = GroupObjectPermission._meta.db_table
# Get all indexes for the table
with connection.cursor() as cursor:
indexes = connection.introspection.get_constraints(cursor, table_name)
# Look for our specific indexes
index_fields_sets = []
for constraint_name, constraint_info in indexes.items():
if constraint_info.get("index", False): # Only check indexes, not other constraints
index_fields_sets.append(set(constraint_info["columns"]))
# Check if our expected indexes exist (using sets to ignore order)
expected_indexes = [
{"permission_id", "group_id", "content_type_id", "object_pk"},
{"group_id", "content_type_id", "object_pk"},
]
for expected_index in expected_indexes:
found = any(expected_index.issubset(index_set) for index_set in index_fields_sets)
self.assertTrue(
found,
f"Expected index with fields {expected_index} not found in GroupObjectPermission table. "
f"Available indexes: {index_fields_sets}",
)
def test_userobjectpermission_query_uses_index(self):
"""Test that queries on UserObjectPermission use the indexes efficiently."""
# Create some test data
UserObjectPermission.objects.create(
user=self.user, permission=self.permission, content_type=self.content_type, object_pk=str(self.project.pk)
)
# Test query that should use the first index (permission, user, content_type, object_pk)
with self.assertNumQueries(1):
exists = UserObjectPermission.objects.filter(
permission=self.permission,
user=self.user,
content_type=self.content_type,
object_pk=str(self.project.pk),
).exists()
self.assertTrue(exists)
# Test query that should use the second index (user, content_type, object_pk)
with self.assertNumQueries(1):
permissions = list(
UserObjectPermission.objects.filter(
user=self.user, content_type=self.content_type, object_pk=str(self.project.pk)
)
)
self.assertEqual(len(permissions), 1)
def test_groupobjectpermission_query_uses_index(self):
"""Test that queries on GroupObjectPermission use the indexes efficiently."""
# Create some test data
GroupObjectPermission.objects.create(
group=self.group, permission=self.permission, content_type=self.content_type, object_pk=str(self.project.pk)
)
# Test query that should use the first index (permission, group, content_type, object_pk)
with self.assertNumQueries(1):
exists = GroupObjectPermission.objects.filter(
permission=self.permission,
group=self.group,
content_type=self.content_type,
object_pk=str(self.project.pk),
).exists()
self.assertTrue(exists)
# Test query that should use the second index (group, content_type, object_pk)
with self.assertNumQueries(1):
permissions = list(
GroupObjectPermission.objects.filter(
group=self.group, content_type=self.content_type, object_pk=str(self.project.pk)
)
)
self.assertEqual(len(permissions), 1)
def test_basegenericobjectpermission_index_exists(self):
"""Test that BaseGenericObjectPermission has the expected index."""
# Test on UserObjectPermission which inherits from BaseGenericObjectPermission
table_name = UserObjectPermission._meta.db_table
with connection.cursor() as cursor:
indexes = connection.introspection.get_constraints(cursor, table_name)
# Look for the base index
index_fields_sets = []
for constraint_name, constraint_info in indexes.items():
if constraint_info.get("index", False):
index_fields_sets.append(set(constraint_info["columns"]))
# Check if the base index exists (content_type_id, object_pk should be part of some index)
expected_base_fields = {"content_type_id", "object_pk"}
found = any(expected_base_fields.issubset(index_set) for index_set in index_fields_sets)
self.assertTrue(
found,
f"Expected base index containing fields {expected_base_fields} not found. "
f"Available indexes: {index_fields_sets}",
)
| IndexTestCase |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/postgresql/base.py | {
"start": 115860,
"end": 202175
} | class ____(default.DefaultDialect):
name = "postgresql"
supports_statement_cache = True
supports_alter = True
max_identifier_length = 63
supports_sane_rowcount = True
bind_typing = interfaces.BindTyping.RENDER_CASTS
supports_native_enum = True
supports_native_boolean = True
supports_native_uuid = True
supports_smallserial = True
supports_virtual_generated_columns = True
supports_sequences = True
sequences_optional = True
preexecute_autoincrement_sequences = True
postfetch_lastrowid = False
use_insertmanyvalues = True
returns_native_bytes = True
insertmanyvalues_implicit_sentinel = (
InsertmanyvaluesSentinelOpts.ANY_AUTOINCREMENT
| InsertmanyvaluesSentinelOpts.USE_INSERT_FROM_SELECT
| InsertmanyvaluesSentinelOpts.RENDER_SELECT_COL_CASTS
)
supports_comments = True
supports_constraint_comments = True
supports_default_values = True
supports_default_metavalue = True
supports_empty_insert = False
supports_multivalues_insert = True
supports_identity_columns = True
default_paramstyle = "pyformat"
ischema_names = ischema_names
colspecs = colspecs
statement_compiler = PGCompiler
ddl_compiler = PGDDLCompiler
type_compiler_cls = PGTypeCompiler
preparer = PGIdentifierPreparer
execution_ctx_cls = PGExecutionContext
inspector = PGInspector
update_returning = True
delete_returning = True
insert_returning = True
update_returning_multifrom = True
delete_returning_multifrom = True
connection_characteristics = (
default.DefaultDialect.connection_characteristics
)
connection_characteristics = connection_characteristics.union(
{
"postgresql_readonly": PGReadOnlyConnectionCharacteristic(),
"postgresql_deferrable": PGDeferrableConnectionCharacteristic(),
}
)
construct_arguments = [
(
schema.Index,
{
"using": False,
"include": None,
"where": None,
"ops": {},
"concurrently": False,
"with": {},
"tablespace": None,
"nulls_not_distinct": None,
},
),
(
schema.Table,
{
"ignore_search_path": False,
"tablespace": None,
"partition_by": None,
"with_oids": None,
"with": None,
"on_commit": None,
"inherits": None,
"using": None,
},
),
(
schema.CheckConstraint,
{
"not_valid": False,
},
),
(
schema.ForeignKeyConstraint,
{
"not_valid": False,
},
),
(
schema.PrimaryKeyConstraint,
{"include": None},
),
(
schema.UniqueConstraint,
{
"include": None,
"nulls_not_distinct": None,
},
),
]
reflection_options = ("postgresql_ignore_search_path",)
_backslash_escapes = True
_supports_create_index_concurrently = True
_supports_drop_index_concurrently = True
_supports_jsonb_subscripting = True
_pg_am_btree_oid = -1
def __init__(
self,
native_inet_types=None,
json_serializer=None,
json_deserializer=None,
**kwargs,
):
default.DefaultDialect.__init__(self, **kwargs)
self._native_inet_types = native_inet_types
self._json_deserializer = json_deserializer
self._json_serializer = json_serializer
def initialize(self, connection):
super().initialize(connection)
# https://www.postgresql.org/docs/9.3/static/release-9-2.html#AEN116689
self.supports_smallserial = self.server_version_info >= (9, 2)
self._set_backslash_escapes(connection)
self._supports_drop_index_concurrently = self.server_version_info >= (
9,
2,
)
self.supports_identity_columns = self.server_version_info >= (10,)
self._supports_jsonb_subscripting = self.server_version_info >= (14,)
self.supports_virtual_generated_columns = self.server_version_info >= (
18,
)
def get_isolation_level_values(self, dbapi_conn):
# note the generic dialect doesn't have AUTOCOMMIT, however
# all postgresql dialects should include AUTOCOMMIT.
return (
"SERIALIZABLE",
"READ UNCOMMITTED",
"READ COMMITTED",
"REPEATABLE READ",
)
def set_isolation_level(self, dbapi_connection, level):
cursor = dbapi_connection.cursor()
cursor.execute(
"SET SESSION CHARACTERISTICS AS TRANSACTION "
f"ISOLATION LEVEL {level}"
)
cursor.execute("COMMIT")
cursor.close()
def get_isolation_level(self, dbapi_connection):
cursor = dbapi_connection.cursor()
cursor.execute("show transaction isolation level")
val = cursor.fetchone()[0]
cursor.close()
return val.upper()
def set_readonly(self, connection, value):
raise NotImplementedError()
def get_readonly(self, connection):
raise NotImplementedError()
def set_deferrable(self, connection, value):
raise NotImplementedError()
def get_deferrable(self, connection):
raise NotImplementedError()
def _split_multihost_from_url(self, url: URL) -> Union[
Tuple[None, None],
Tuple[Tuple[Optional[str], ...], Tuple[Optional[int], ...]],
]:
hosts: Optional[Tuple[Optional[str], ...]] = None
ports_str: Union[str, Tuple[Optional[str], ...], None] = None
integrated_multihost = False
if "host" in url.query:
if isinstance(url.query["host"], (list, tuple)):
integrated_multihost = True
hosts, ports_str = zip(
*[
token.split(":") if ":" in token else (token, None)
for token in url.query["host"]
]
)
elif isinstance(url.query["host"], str):
hosts = tuple(url.query["host"].split(","))
if (
"port" not in url.query
and len(hosts) == 1
and ":" in hosts[0]
):
# internet host is alphanumeric plus dots or hyphens.
# this is essentially rfc1123, which refers to rfc952.
# https://stackoverflow.com/questions/3523028/
# valid-characters-of-a-hostname
host_port_match = re.match(
r"^([a-zA-Z0-9\-\.]*)(?:\:(\d*))?$", hosts[0]
)
if host_port_match:
integrated_multihost = True
h, p = host_port_match.group(1, 2)
if TYPE_CHECKING:
assert isinstance(h, str)
assert isinstance(p, str)
hosts = (h,)
ports_str = cast(
"Tuple[Optional[str], ...]", (p,) if p else (None,)
)
if "port" in url.query:
if integrated_multihost:
raise exc.ArgumentError(
"Can't mix 'multihost' formats together; use "
'"host=h1,h2,h3&port=p1,p2,p3" or '
'"host=h1:p1&host=h2:p2&host=h3:p3" separately'
)
if isinstance(url.query["port"], (list, tuple)):
ports_str = url.query["port"]
elif isinstance(url.query["port"], str):
ports_str = tuple(url.query["port"].split(","))
ports: Optional[Tuple[Optional[int], ...]] = None
if ports_str:
try:
ports = tuple(int(x) if x else None for x in ports_str)
except ValueError:
raise exc.ArgumentError(
f"Received non-integer port arguments: {ports_str}"
) from None
if ports and (
(not hosts and len(ports) > 1)
or (
hosts
and ports
and len(hosts) != len(ports)
and (len(hosts) > 1 or len(ports) > 1)
)
):
raise exc.ArgumentError("number of hosts and ports don't match")
if hosts is not None:
if ports is None:
ports = tuple(None for _ in hosts)
return hosts, ports # type: ignore
def do_begin_twophase(self, connection, xid):
self.do_begin(connection.connection)
def do_prepare_twophase(self, connection, xid):
connection.exec_driver_sql("PREPARE TRANSACTION '%s'" % xid)
def do_rollback_twophase(
self, connection, xid, is_prepared=True, recover=False
):
if is_prepared:
if recover:
# FIXME: ugly hack to get out of transaction
# context when committing recoverable transactions
# Must find out a way how to make the dbapi not
# open a transaction.
connection.exec_driver_sql("ROLLBACK")
connection.exec_driver_sql("ROLLBACK PREPARED '%s'" % xid)
connection.exec_driver_sql("BEGIN")
self.do_rollback(connection.connection)
else:
self.do_rollback(connection.connection)
def do_commit_twophase(
self, connection, xid, is_prepared=True, recover=False
):
if is_prepared:
if recover:
connection.exec_driver_sql("ROLLBACK")
connection.exec_driver_sql("COMMIT PREPARED '%s'" % xid)
connection.exec_driver_sql("BEGIN")
self.do_rollback(connection.connection)
else:
self.do_commit(connection.connection)
def do_recover_twophase(self, connection):
return connection.scalars(
sql.text("SELECT gid FROM pg_prepared_xacts")
).all()
def _get_default_schema_name(self, connection):
return connection.exec_driver_sql("select current_schema()").scalar()
@reflection.cache
def has_schema(self, connection, schema, **kw):
query = select(pg_catalog.pg_namespace.c.nspname).where(
pg_catalog.pg_namespace.c.nspname == schema
)
return bool(connection.scalar(query))
def _pg_class_filter_scope_schema(
self, query, schema, scope, pg_class_table=None
):
if pg_class_table is None:
pg_class_table = pg_catalog.pg_class
query = query.join(
pg_catalog.pg_namespace,
pg_catalog.pg_namespace.c.oid == pg_class_table.c.relnamespace,
)
if scope is ObjectScope.DEFAULT:
query = query.where(pg_class_table.c.relpersistence != "t")
elif scope is ObjectScope.TEMPORARY:
query = query.where(pg_class_table.c.relpersistence == "t")
if schema is None:
query = query.where(
pg_catalog.pg_table_is_visible(pg_class_table.c.oid),
# ignore pg_catalog schema
pg_catalog.pg_namespace.c.nspname != "pg_catalog",
)
else:
query = query.where(pg_catalog.pg_namespace.c.nspname == schema)
return query
def _pg_class_relkind_condition(self, relkinds, pg_class_table=None):
if pg_class_table is None:
pg_class_table = pg_catalog.pg_class
# uses the any form instead of in otherwise postgresql complaings
# that 'IN could not convert type character to "char"'
return pg_class_table.c.relkind == sql.any_(_array.array(relkinds))
@lru_cache()
def _has_table_query(self, schema):
query = select(pg_catalog.pg_class.c.relname).where(
pg_catalog.pg_class.c.relname == bindparam("table_name"),
self._pg_class_relkind_condition(
pg_catalog.RELKINDS_ALL_TABLE_LIKE
),
)
return self._pg_class_filter_scope_schema(
query, schema, scope=ObjectScope.ANY
)
@reflection.cache
def has_table(self, connection, table_name, schema=None, **kw):
self._ensure_has_table_connection(connection)
query = self._has_table_query(schema)
return bool(connection.scalar(query, {"table_name": table_name}))
@reflection.cache
def has_sequence(self, connection, sequence_name, schema=None, **kw):
query = select(pg_catalog.pg_class.c.relname).where(
pg_catalog.pg_class.c.relkind == "S",
pg_catalog.pg_class.c.relname == sequence_name,
)
query = self._pg_class_filter_scope_schema(
query, schema, scope=ObjectScope.ANY
)
return bool(connection.scalar(query))
@reflection.cache
def has_type(self, connection, type_name, schema=None, **kw):
query = (
select(pg_catalog.pg_type.c.typname)
.join(
pg_catalog.pg_namespace,
pg_catalog.pg_namespace.c.oid
== pg_catalog.pg_type.c.typnamespace,
)
.where(pg_catalog.pg_type.c.typname == type_name)
)
if schema is None:
query = query.where(
pg_catalog.pg_type_is_visible(pg_catalog.pg_type.c.oid),
# ignore pg_catalog schema
pg_catalog.pg_namespace.c.nspname != "pg_catalog",
)
elif schema != "*":
query = query.where(pg_catalog.pg_namespace.c.nspname == schema)
return bool(connection.scalar(query))
def _get_server_version_info(self, connection):
v = connection.exec_driver_sql("select pg_catalog.version()").scalar()
m = re.match(
r".*(?:PostgreSQL|EnterpriseDB) "
r"(\d+)\.?(\d+)?(?:\.(\d+))?(?:\.\d+)?(?:devel|beta)?",
v,
)
if not m:
raise AssertionError(
"Could not determine version from string '%s'" % v
)
return tuple([int(x) for x in m.group(1, 2, 3) if x is not None])
@reflection.cache
def get_table_oid(self, connection, table_name, schema=None, **kw):
"""Fetch the oid for schema.table_name."""
query = select(pg_catalog.pg_class.c.oid).where(
pg_catalog.pg_class.c.relname == table_name,
self._pg_class_relkind_condition(
pg_catalog.RELKINDS_ALL_TABLE_LIKE
),
)
query = self._pg_class_filter_scope_schema(
query, schema, scope=ObjectScope.ANY
)
table_oid = connection.scalar(query)
if table_oid is None:
raise exc.NoSuchTableError(
f"{schema}.{table_name}" if schema else table_name
)
return table_oid
@reflection.cache
def get_schema_names(self, connection, **kw):
query = (
select(pg_catalog.pg_namespace.c.nspname)
.where(pg_catalog.pg_namespace.c.nspname.not_like("pg_%"))
.order_by(pg_catalog.pg_namespace.c.nspname)
)
return connection.scalars(query).all()
def _get_relnames_for_relkinds(self, connection, schema, relkinds, scope):
query = select(pg_catalog.pg_class.c.relname).where(
self._pg_class_relkind_condition(relkinds)
)
query = self._pg_class_filter_scope_schema(query, schema, scope=scope)
return connection.scalars(query).all()
@reflection.cache
def get_table_names(self, connection, schema=None, **kw):
return self._get_relnames_for_relkinds(
connection,
schema,
pg_catalog.RELKINDS_TABLE_NO_FOREIGN,
scope=ObjectScope.DEFAULT,
)
@reflection.cache
def get_temp_table_names(self, connection, **kw):
return self._get_relnames_for_relkinds(
connection,
schema=None,
relkinds=pg_catalog.RELKINDS_TABLE_NO_FOREIGN,
scope=ObjectScope.TEMPORARY,
)
@reflection.cache
def _get_foreign_table_names(self, connection, schema=None, **kw):
return self._get_relnames_for_relkinds(
connection, schema, relkinds=("f",), scope=ObjectScope.ANY
)
@reflection.cache
def get_view_names(self, connection, schema=None, **kw):
return self._get_relnames_for_relkinds(
connection,
schema,
pg_catalog.RELKINDS_VIEW,
scope=ObjectScope.DEFAULT,
)
@reflection.cache
def get_materialized_view_names(self, connection, schema=None, **kw):
return self._get_relnames_for_relkinds(
connection,
schema,
pg_catalog.RELKINDS_MAT_VIEW,
scope=ObjectScope.DEFAULT,
)
@reflection.cache
def get_temp_view_names(self, connection, schema=None, **kw):
return self._get_relnames_for_relkinds(
connection,
schema,
# NOTE: do not include temp materialzied views (that do not
# seem to be a thing at least up to version 14)
pg_catalog.RELKINDS_VIEW,
scope=ObjectScope.TEMPORARY,
)
@reflection.cache
def get_sequence_names(self, connection, schema=None, **kw):
return self._get_relnames_for_relkinds(
connection, schema, relkinds=("S",), scope=ObjectScope.ANY
)
@reflection.cache
def get_view_definition(self, connection, view_name, schema=None, **kw):
query = (
select(pg_catalog.pg_get_viewdef(pg_catalog.pg_class.c.oid))
.select_from(pg_catalog.pg_class)
.where(
pg_catalog.pg_class.c.relname == view_name,
self._pg_class_relkind_condition(
pg_catalog.RELKINDS_VIEW + pg_catalog.RELKINDS_MAT_VIEW
),
)
)
query = self._pg_class_filter_scope_schema(
query, schema, scope=ObjectScope.ANY
)
res = connection.scalar(query)
if res is None:
raise exc.NoSuchTableError(
f"{schema}.{view_name}" if schema else view_name
)
else:
return res
def _value_or_raise(self, data, table, schema):
try:
return dict(data)[(schema, table)]
except KeyError:
raise exc.NoSuchTableError(
f"{schema}.{table}" if schema else table
) from None
def _prepare_filter_names(self, filter_names):
if filter_names:
return True, {"filter_names": filter_names}
else:
return False, {}
def _kind_to_relkinds(self, kind: ObjectKind) -> Tuple[str, ...]:
if kind is ObjectKind.ANY:
return pg_catalog.RELKINDS_ALL_TABLE_LIKE
relkinds = ()
if ObjectKind.TABLE in kind:
relkinds += pg_catalog.RELKINDS_TABLE
if ObjectKind.VIEW in kind:
relkinds += pg_catalog.RELKINDS_VIEW
if ObjectKind.MATERIALIZED_VIEW in kind:
relkinds += pg_catalog.RELKINDS_MAT_VIEW
return relkinds
@reflection.cache
def get_table_options(self, connection, table_name, schema=None, **kw):
data = self.get_multi_table_options(
connection,
schema=schema,
filter_names=[table_name],
scope=ObjectScope.ANY,
kind=ObjectKind.ANY,
**kw,
)
return self._value_or_raise(data, table_name, schema)
@lru_cache()
def _table_options_query(self, schema, has_filter_names, scope, kind):
inherits_sq = (
select(
pg_catalog.pg_inherits.c.inhrelid,
sql.func.array_agg(
aggregate_order_by(
pg_catalog.pg_class.c.relname,
pg_catalog.pg_inherits.c.inhseqno,
)
).label("parent_table_names"),
)
.select_from(pg_catalog.pg_inherits)
.join(
pg_catalog.pg_class,
pg_catalog.pg_inherits.c.inhparent
== pg_catalog.pg_class.c.oid,
)
.group_by(pg_catalog.pg_inherits.c.inhrelid)
.subquery("inherits")
)
if self.server_version_info < (12,):
# this is not in the pg_catalog.pg_class since it was
# removed in PostgreSQL version 12
has_oids = sql.column("relhasoids", BOOLEAN)
else:
has_oids = sql.null().label("relhasoids")
relkinds = self._kind_to_relkinds(kind)
query = (
select(
pg_catalog.pg_class.c.oid,
pg_catalog.pg_class.c.relname,
pg_catalog.pg_class.c.reloptions,
has_oids,
sql.case(
(
sql.and_(
pg_catalog.pg_am.c.amname.is_not(None),
pg_catalog.pg_am.c.amname
!= sql.func.current_setting(
"default_table_access_method"
),
),
pg_catalog.pg_am.c.amname,
),
else_=sql.null(),
).label("access_method_name"),
pg_catalog.pg_tablespace.c.spcname.label("tablespace_name"),
inherits_sq.c.parent_table_names,
)
.select_from(pg_catalog.pg_class)
.outerjoin(
# NOTE: on postgresql < 12, this could be avoided
# since relam is always 0 so nothing is joined.
pg_catalog.pg_am,
pg_catalog.pg_class.c.relam == pg_catalog.pg_am.c.oid,
)
.outerjoin(
inherits_sq,
pg_catalog.pg_class.c.oid == inherits_sq.c.inhrelid,
)
.outerjoin(
pg_catalog.pg_tablespace,
pg_catalog.pg_tablespace.c.oid
== pg_catalog.pg_class.c.reltablespace,
)
.where(self._pg_class_relkind_condition(relkinds))
)
query = self._pg_class_filter_scope_schema(query, schema, scope=scope)
if has_filter_names:
query = query.where(
pg_catalog.pg_class.c.relname.in_(bindparam("filter_names"))
)
return query
def get_multi_table_options(
self, connection, schema, filter_names, scope, kind, **kw
):
has_filter_names, params = self._prepare_filter_names(filter_names)
query = self._table_options_query(
schema, has_filter_names, scope, kind
)
rows = connection.execute(query, params).mappings()
table_options = {}
for row in rows:
current: dict[str, Any] = {}
if row["access_method_name"] is not None:
current["postgresql_using"] = row["access_method_name"]
if row["parent_table_names"]:
current["postgresql_inherits"] = tuple(
row["parent_table_names"]
)
if row["reloptions"]:
current["postgresql_with"] = dict(
option.split("=", 1) for option in row["reloptions"]
)
if row["relhasoids"]:
current["postgresql_with_oids"] = True
if row["tablespace_name"] is not None:
current["postgresql_tablespace"] = row["tablespace_name"]
table_options[(schema, row["relname"])] = current
return table_options.items()
@reflection.cache
def get_columns(self, connection, table_name, schema=None, **kw):
data = self.get_multi_columns(
connection,
schema=schema,
filter_names=[table_name],
scope=ObjectScope.ANY,
kind=ObjectKind.ANY,
**kw,
)
return self._value_or_raise(data, table_name, schema)
@lru_cache()
def _columns_query(self, schema, has_filter_names, scope, kind):
# NOTE: the query with the default and identity options scalar
# subquery is faster than trying to use outer joins for them
generated = (
pg_catalog.pg_attribute.c.attgenerated.label("generated")
if self.server_version_info >= (12,)
else sql.null().label("generated")
)
if self.server_version_info >= (10,):
# join lateral performs worse (~2x slower) than a scalar_subquery
# also the subquery can be run only if the column is an identity
identity = sql.case(
( # attidentity != '' is required or it will reflect also
# serial columns as identity.
pg_catalog.pg_attribute.c.attidentity != "",
select(
sql.func.json_build_object(
"always",
pg_catalog.pg_attribute.c.attidentity == "a",
"start",
pg_catalog.pg_sequence.c.seqstart,
"increment",
pg_catalog.pg_sequence.c.seqincrement,
"minvalue",
pg_catalog.pg_sequence.c.seqmin,
"maxvalue",
pg_catalog.pg_sequence.c.seqmax,
"cache",
pg_catalog.pg_sequence.c.seqcache,
"cycle",
pg_catalog.pg_sequence.c.seqcycle,
type_=sqltypes.JSON(),
)
)
.select_from(pg_catalog.pg_sequence)
.where(
# not needed but pg seems to like it
pg_catalog.pg_attribute.c.attidentity != "",
pg_catalog.pg_sequence.c.seqrelid
== sql.cast(
sql.cast(
pg_catalog.pg_get_serial_sequence(
sql.cast(
sql.cast(
pg_catalog.pg_attribute.c.attrelid,
REGCLASS,
),
TEXT,
),
pg_catalog.pg_attribute.c.attname,
),
REGCLASS,
),
OID,
),
)
.correlate(pg_catalog.pg_attribute)
.scalar_subquery(),
),
else_=sql.null(),
).label("identity_options")
else:
identity = sql.null().label("identity_options")
# join lateral performs the same as scalar_subquery here, also
# the subquery can be run only if the column has a default
default = sql.case(
(
pg_catalog.pg_attribute.c.atthasdef,
select(
pg_catalog.pg_get_expr(
pg_catalog.pg_attrdef.c.adbin,
pg_catalog.pg_attrdef.c.adrelid,
)
)
.select_from(pg_catalog.pg_attrdef)
.where(
# not needed but pg seems to like it
pg_catalog.pg_attribute.c.atthasdef,
pg_catalog.pg_attrdef.c.adrelid
== pg_catalog.pg_attribute.c.attrelid,
pg_catalog.pg_attrdef.c.adnum
== pg_catalog.pg_attribute.c.attnum,
)
.correlate(pg_catalog.pg_attribute)
.scalar_subquery(),
),
else_=sql.null(),
).label("default")
# get the name of the collate when it's different from the default one
collate = sql.case(
(
sql.and_(
pg_catalog.pg_attribute.c.attcollation != 0,
select(pg_catalog.pg_type.c.typcollation)
.where(
pg_catalog.pg_type.c.oid
== pg_catalog.pg_attribute.c.atttypid,
)
.correlate(pg_catalog.pg_attribute)
.scalar_subquery()
!= pg_catalog.pg_attribute.c.attcollation,
),
select(pg_catalog.pg_collation.c.collname)
.where(
pg_catalog.pg_collation.c.oid
== pg_catalog.pg_attribute.c.attcollation
)
.correlate(pg_catalog.pg_attribute)
.scalar_subquery(),
),
else_=sql.null(),
).label("collation")
relkinds = self._kind_to_relkinds(kind)
query = (
select(
pg_catalog.pg_attribute.c.attname.label("name"),
pg_catalog.format_type(
pg_catalog.pg_attribute.c.atttypid,
pg_catalog.pg_attribute.c.atttypmod,
).label("format_type"),
default,
pg_catalog.pg_attribute.c.attnotnull.label("not_null"),
pg_catalog.pg_class.c.relname.label("table_name"),
pg_catalog.pg_description.c.description.label("comment"),
generated,
identity,
collate,
)
.select_from(pg_catalog.pg_class)
# NOTE: postgresql support table with no user column, meaning
# there is no row with pg_attribute.attnum > 0. use a left outer
# join to avoid filtering these tables.
.outerjoin(
pg_catalog.pg_attribute,
sql.and_(
pg_catalog.pg_class.c.oid
== pg_catalog.pg_attribute.c.attrelid,
pg_catalog.pg_attribute.c.attnum > 0,
~pg_catalog.pg_attribute.c.attisdropped,
),
)
.outerjoin(
pg_catalog.pg_description,
sql.and_(
pg_catalog.pg_description.c.objoid
== pg_catalog.pg_attribute.c.attrelid,
pg_catalog.pg_description.c.objsubid
== pg_catalog.pg_attribute.c.attnum,
),
)
.where(self._pg_class_relkind_condition(relkinds))
.order_by(
pg_catalog.pg_class.c.relname, pg_catalog.pg_attribute.c.attnum
)
)
query = self._pg_class_filter_scope_schema(query, schema, scope=scope)
if has_filter_names:
query = query.where(
pg_catalog.pg_class.c.relname.in_(bindparam("filter_names"))
)
return query
def get_multi_columns(
self, connection, schema, filter_names, scope, kind, **kw
):
has_filter_names, params = self._prepare_filter_names(filter_names)
query = self._columns_query(schema, has_filter_names, scope, kind)
rows = connection.execute(query, params).mappings()
named_type_loader = _NamedTypeLoader(self, connection, kw)
columns = self._get_columns_info(rows, named_type_loader, schema)
return columns.items()
_format_type_args_pattern = re.compile(r"\((.*)\)")
_format_type_args_delim = re.compile(r"\s*,\s*")
_format_array_spec_pattern = re.compile(r"((?:\[\])*)$")
def _reflect_type(
self,
format_type: Optional[str],
named_type_loader: _NamedTypeLoader,
type_description: str,
collation: Optional[str],
) -> sqltypes.TypeEngine[Any]:
"""
Attempts to reconstruct a column type defined in ischema_names based
on the information available in the format_type.
If the `format_type` cannot be associated with a known `ischema_names`,
it is treated as a reference to a known PostgreSQL named `ENUM` or
`DOMAIN` type.
"""
type_description = type_description or "unknown type"
if format_type is None:
util.warn(
"PostgreSQL format_type() returned NULL for %s"
% type_description
)
return sqltypes.NULLTYPE
attype_args_match = self._format_type_args_pattern.search(format_type)
if attype_args_match and attype_args_match.group(1):
attype_args = self._format_type_args_delim.split(
attype_args_match.group(1)
)
else:
attype_args = ()
match_array_dim = self._format_array_spec_pattern.search(format_type)
# Each "[]" in array specs corresponds to an array dimension
array_dim = len(match_array_dim.group(1) or "") // 2
# Remove all parameters and array specs from format_type to obtain an
# ischema_name candidate
attype = self._format_type_args_pattern.sub("", format_type)
attype = self._format_array_spec_pattern.sub("", attype)
schema_type = self.ischema_names.get(attype.lower(), None)
args, kwargs = (), {}
if attype == "numeric":
if len(attype_args) == 2:
precision, scale = map(int, attype_args)
args = (precision, scale)
elif attype == "double precision":
args = (53,)
elif attype == "integer":
args = ()
elif attype in ("timestamp with time zone", "time with time zone"):
kwargs["timezone"] = True
if len(attype_args) == 1:
kwargs["precision"] = int(attype_args[0])
elif attype in (
"timestamp without time zone",
"time without time zone",
"time",
):
kwargs["timezone"] = False
if len(attype_args) == 1:
kwargs["precision"] = int(attype_args[0])
elif attype == "bit varying":
kwargs["varying"] = True
if len(attype_args) == 1:
charlen = int(attype_args[0])
args = (charlen,)
# a domain or enum can start with interval, so be mindful of that.
elif attype == "interval" or attype.startswith("interval "):
schema_type = INTERVAL
field_match = re.match(r"interval (.+)", attype)
if field_match:
kwargs["fields"] = field_match.group(1)
if len(attype_args) == 1:
kwargs["precision"] = int(attype_args[0])
else:
enum_or_domain_key = tuple(util.quoted_token_parser(attype))
if (
schema_type is None
and enum_or_domain_key in named_type_loader.enums
):
schema_type = ENUM
enum = named_type_loader.enums[enum_or_domain_key]
kwargs["name"] = enum["name"]
if not enum["visible"]:
kwargs["schema"] = enum["schema"]
args = tuple(enum["labels"])
elif (
schema_type is None
and enum_or_domain_key in named_type_loader.domains
):
schema_type = DOMAIN
domain = named_type_loader.domains[enum_or_domain_key]
data_type = self._reflect_type(
domain["type"],
named_type_loader,
type_description="DOMAIN '%s'" % domain["name"],
collation=domain["collation"],
)
args = (domain["name"], data_type)
kwargs["collation"] = domain["collation"]
kwargs["default"] = domain["default"]
kwargs["not_null"] = not domain["nullable"]
kwargs["create_type"] = False
if domain["constraints"]:
# We only support a single constraint
check_constraint = domain["constraints"][0]
kwargs["constraint_name"] = check_constraint["name"]
kwargs["check"] = check_constraint["check"]
if not domain["visible"]:
kwargs["schema"] = domain["schema"]
else:
try:
charlen = int(attype_args[0])
args = (charlen, *attype_args[1:])
except (ValueError, IndexError):
args = attype_args
if not schema_type:
util.warn(
"Did not recognize type '%s' of %s"
% (attype, type_description)
)
return sqltypes.NULLTYPE
if collation is not None:
kwargs["collation"] = collation
data_type = schema_type(*args, **kwargs)
if array_dim >= 1:
# postgres does not preserve dimensionality or size of array types.
data_type = _array.ARRAY(data_type)
return data_type
def _get_columns_info(self, rows, named_type_loader, schema):
columns = defaultdict(list)
for row_dict in rows:
# ensure that each table has an entry, even if it has no columns
if row_dict["name"] is None:
columns[(schema, row_dict["table_name"])] = (
ReflectionDefaults.columns()
)
continue
table_cols = columns[(schema, row_dict["table_name"])]
collation = row_dict["collation"]
coltype = self._reflect_type(
row_dict["format_type"],
named_type_loader,
type_description="column '%s'" % row_dict["name"],
collation=collation,
)
default = row_dict["default"]
name = row_dict["name"]
generated = row_dict["generated"]
nullable = not row_dict["not_null"]
if isinstance(coltype, DOMAIN):
if not default:
# domain can override the default value but
# cant set it to None
if coltype.default is not None:
default = coltype.default
nullable = nullable and not coltype.not_null
identity = row_dict["identity_options"]
# If a zero byte or blank string depending on driver (is also
# absent for older PG versions), then not a generated column.
# Otherwise, s = stored, v = virtual.
if generated not in (None, "", b"\x00"):
computed = dict(
sqltext=default, persisted=generated in ("s", b"s")
)
default = None
else:
computed = None
# adjust the default value
autoincrement = False
if default is not None:
match = re.search(r"""(nextval\(')([^']+)('.*$)""", default)
if match is not None:
if issubclass(coltype._type_affinity, sqltypes.Integer):
autoincrement = True
# the default is related to a Sequence
if "." not in match.group(2) and schema is not None:
# unconditionally quote the schema name. this could
# later be enhanced to obey quoting rules /
# "quote schema"
default = (
match.group(1)
+ ('"%s"' % schema)
+ "."
+ match.group(2)
+ match.group(3)
)
column_info = {
"name": name,
"type": coltype,
"nullable": nullable,
"default": default,
"autoincrement": autoincrement or identity is not None,
"comment": row_dict["comment"],
}
if computed is not None:
column_info["computed"] = computed
if identity is not None:
column_info["identity"] = identity
table_cols.append(column_info)
return columns
@lru_cache()
def _table_oids_query(self, schema, has_filter_names, scope, kind):
relkinds = self._kind_to_relkinds(kind)
oid_q = select(
pg_catalog.pg_class.c.oid, pg_catalog.pg_class.c.relname
).where(self._pg_class_relkind_condition(relkinds))
oid_q = self._pg_class_filter_scope_schema(oid_q, schema, scope=scope)
if has_filter_names:
oid_q = oid_q.where(
pg_catalog.pg_class.c.relname.in_(bindparam("filter_names"))
)
return oid_q
@reflection.flexi_cache(
("schema", InternalTraversal.dp_string),
("filter_names", InternalTraversal.dp_string_list),
("kind", InternalTraversal.dp_plain_obj),
("scope", InternalTraversal.dp_plain_obj),
)
def _get_table_oids(
self, connection, schema, filter_names, scope, kind, **kw
):
has_filter_names, params = self._prepare_filter_names(filter_names)
oid_q = self._table_oids_query(schema, has_filter_names, scope, kind)
result = connection.execute(oid_q, params)
return result.all()
@util.memoized_property
def _constraint_query(self):
if self.server_version_info >= (11, 0):
indnkeyatts = pg_catalog.pg_index.c.indnkeyatts
else:
indnkeyatts = pg_catalog.pg_index.c.indnatts.label("indnkeyatts")
if self.server_version_info >= (15,):
indnullsnotdistinct = pg_catalog.pg_index.c.indnullsnotdistinct
else:
indnullsnotdistinct = sql.false().label("indnullsnotdistinct")
con_sq = (
select(
pg_catalog.pg_constraint.c.conrelid,
pg_catalog.pg_constraint.c.conname,
sql.func.unnest(pg_catalog.pg_index.c.indkey).label("attnum"),
sql.func.generate_subscripts(
pg_catalog.pg_index.c.indkey, 1
).label("ord"),
indnkeyatts,
indnullsnotdistinct,
pg_catalog.pg_description.c.description,
)
.join(
pg_catalog.pg_index,
pg_catalog.pg_constraint.c.conindid
== pg_catalog.pg_index.c.indexrelid,
)
.outerjoin(
pg_catalog.pg_description,
pg_catalog.pg_description.c.objoid
== pg_catalog.pg_constraint.c.oid,
)
.where(
pg_catalog.pg_constraint.c.contype == bindparam("contype"),
pg_catalog.pg_constraint.c.conrelid.in_(bindparam("oids")),
# NOTE: filtering also on pg_index.indrelid for oids does
# not seem to have a performance effect, but it may be an
# option if perf problems are reported
)
.subquery("con")
)
attr_sq = (
select(
con_sq.c.conrelid,
con_sq.c.conname,
con_sq.c.description,
con_sq.c.ord,
con_sq.c.indnkeyatts,
con_sq.c.indnullsnotdistinct,
pg_catalog.pg_attribute.c.attname,
)
.select_from(pg_catalog.pg_attribute)
.join(
con_sq,
sql.and_(
pg_catalog.pg_attribute.c.attnum == con_sq.c.attnum,
pg_catalog.pg_attribute.c.attrelid == con_sq.c.conrelid,
),
)
.where(
# NOTE: restate the condition here, since pg15 otherwise
# seems to get confused on pscopg2 sometimes, doing
# a sequential scan of pg_attribute.
# The condition in the con_sq subquery is not actually needed
# in pg15, but it may be needed in older versions. Keeping it
# does not seems to have any inpact in any case.
con_sq.c.conrelid.in_(bindparam("oids"))
)
.subquery("attr")
)
return (
select(
attr_sq.c.conrelid,
sql.func.array_agg(
# NOTE: cast since some postgresql derivatives may
# not support array_agg on the name type
aggregate_order_by(
attr_sq.c.attname.cast(TEXT), attr_sq.c.ord
)
).label("cols"),
attr_sq.c.conname,
sql.func.min(attr_sq.c.description).label("description"),
sql.func.min(attr_sq.c.indnkeyatts).label("indnkeyatts"),
sql.func.bool_and(attr_sq.c.indnullsnotdistinct).label(
"indnullsnotdistinct"
),
)
.group_by(attr_sq.c.conrelid, attr_sq.c.conname)
.order_by(attr_sq.c.conrelid, attr_sq.c.conname)
)
def _reflect_constraint(
self, connection, contype, schema, filter_names, scope, kind, **kw
):
# used to reflect primary and unique constraint
table_oids = self._get_table_oids(
connection, schema, filter_names, scope, kind, **kw
)
batches = list(table_oids)
is_unique = contype == "u"
while batches:
batch = batches[0:3000]
batches[0:3000] = []
result = connection.execute(
self._constraint_query,
{"oids": [r[0] for r in batch], "contype": contype},
).mappings()
result_by_oid = defaultdict(list)
for row_dict in result:
result_by_oid[row_dict["conrelid"]].append(row_dict)
for oid, tablename in batch:
for_oid = result_by_oid.get(oid, ())
if for_oid:
for row in for_oid:
# See note in get_multi_indexes
all_cols = row["cols"]
indnkeyatts = row["indnkeyatts"]
if len(all_cols) > indnkeyatts:
inc_cols = all_cols[indnkeyatts:]
cst_cols = all_cols[:indnkeyatts]
else:
inc_cols = []
cst_cols = all_cols
opts = {}
if self.server_version_info >= (11,):
opts["postgresql_include"] = inc_cols
if is_unique:
opts["postgresql_nulls_not_distinct"] = row[
"indnullsnotdistinct"
]
yield (
tablename,
cst_cols,
row["conname"],
row["description"],
opts,
)
else:
yield tablename, None, None, None, None
@reflection.cache
def get_pk_constraint(self, connection, table_name, schema=None, **kw):
data = self.get_multi_pk_constraint(
connection,
schema=schema,
filter_names=[table_name],
scope=ObjectScope.ANY,
kind=ObjectKind.ANY,
**kw,
)
return self._value_or_raise(data, table_name, schema)
def get_multi_pk_constraint(
self, connection, schema, filter_names, scope, kind, **kw
):
result = self._reflect_constraint(
connection, "p", schema, filter_names, scope, kind, **kw
)
# only a single pk can be present for each table. Return an entry
# even if a table has no primary key
default = ReflectionDefaults.pk_constraint
def pk_constraint(pk_name, cols, comment, opts):
info = {
"constrained_columns": cols,
"name": pk_name,
"comment": comment,
}
if opts:
info["dialect_options"] = opts
return info
return (
(
(schema, table_name),
(
pk_constraint(pk_name, cols, comment, opts)
if pk_name is not None
else default()
),
)
for table_name, cols, pk_name, comment, opts in result
)
@reflection.cache
def get_foreign_keys(
self,
connection,
table_name,
schema=None,
postgresql_ignore_search_path=False,
**kw,
):
data = self.get_multi_foreign_keys(
connection,
schema=schema,
filter_names=[table_name],
postgresql_ignore_search_path=postgresql_ignore_search_path,
scope=ObjectScope.ANY,
kind=ObjectKind.ANY,
**kw,
)
return self._value_or_raise(data, table_name, schema)
@lru_cache()
def _foreing_key_query(self, schema, has_filter_names, scope, kind):
pg_class_ref = pg_catalog.pg_class.alias("cls_ref")
pg_namespace_ref = pg_catalog.pg_namespace.alias("nsp_ref")
relkinds = self._kind_to_relkinds(kind)
query = (
select(
pg_catalog.pg_class.c.relname,
pg_catalog.pg_constraint.c.conname,
# NOTE: avoid calling pg_get_constraintdef when not needed
# to speed up the query
sql.case(
(
pg_catalog.pg_constraint.c.oid.is_not(None),
pg_catalog.pg_get_constraintdef(
pg_catalog.pg_constraint.c.oid, True
),
),
else_=None,
),
pg_namespace_ref.c.nspname,
pg_catalog.pg_description.c.description,
)
.select_from(pg_catalog.pg_class)
.outerjoin(
pg_catalog.pg_constraint,
sql.and_(
pg_catalog.pg_class.c.oid
== pg_catalog.pg_constraint.c.conrelid,
pg_catalog.pg_constraint.c.contype == "f",
),
)
.outerjoin(
pg_class_ref,
pg_class_ref.c.oid == pg_catalog.pg_constraint.c.confrelid,
)
.outerjoin(
pg_namespace_ref,
pg_class_ref.c.relnamespace == pg_namespace_ref.c.oid,
)
.outerjoin(
pg_catalog.pg_description,
pg_catalog.pg_description.c.objoid
== pg_catalog.pg_constraint.c.oid,
)
.order_by(
pg_catalog.pg_class.c.relname,
pg_catalog.pg_constraint.c.conname,
)
.where(self._pg_class_relkind_condition(relkinds))
)
query = self._pg_class_filter_scope_schema(query, schema, scope)
if has_filter_names:
query = query.where(
pg_catalog.pg_class.c.relname.in_(bindparam("filter_names"))
)
return query
@util.memoized_property
def _fk_regex_pattern(self):
# optionally quoted token
qtoken = '(?:"[^"]+"|[A-Za-z0-9_]+?)'
# https://www.postgresql.org/docs/current/static/sql-createtable.html
return re.compile(
r"FOREIGN KEY \((.*?)\) "
rf"REFERENCES (?:({qtoken})\.)?({qtoken})\(((?:{qtoken}(?: *, *)?)+)\)" # noqa: E501
r"[\s]?(MATCH (FULL|PARTIAL|SIMPLE)+)?"
r"[\s]?(ON UPDATE "
r"(CASCADE|RESTRICT|NO ACTION|SET NULL|SET DEFAULT)+)?"
r"[\s]?(ON DELETE "
r"(CASCADE|RESTRICT|NO ACTION|"
r"SET (?:NULL|DEFAULT)(?:\s\(.+\))?)+)?"
r"[\s]?(DEFERRABLE|NOT DEFERRABLE)?"
r"[\s]?(INITIALLY (DEFERRED|IMMEDIATE)+)?"
)
def get_multi_foreign_keys(
self,
connection,
schema,
filter_names,
scope,
kind,
postgresql_ignore_search_path=False,
**kw,
):
preparer = self.identifier_preparer
has_filter_names, params = self._prepare_filter_names(filter_names)
query = self._foreing_key_query(schema, has_filter_names, scope, kind)
result = connection.execute(query, params)
FK_REGEX = self._fk_regex_pattern
fkeys = defaultdict(list)
default = ReflectionDefaults.foreign_keys
for table_name, conname, condef, conschema, comment in result:
# ensure that each table has an entry, even if it has
# no foreign keys
if conname is None:
fkeys[(schema, table_name)] = default()
continue
table_fks = fkeys[(schema, table_name)]
m = re.search(FK_REGEX, condef).groups()
(
constrained_columns,
referred_schema,
referred_table,
referred_columns,
_,
match,
_,
onupdate,
_,
ondelete,
deferrable,
_,
initially,
) = m
if deferrable is not None:
deferrable = True if deferrable == "DEFERRABLE" else False
constrained_columns = [
preparer._unquote_identifier(x)
for x in re.split(r"\s*,\s*", constrained_columns)
]
if postgresql_ignore_search_path:
# when ignoring search path, we use the actual schema
# provided it isn't the "default" schema
if conschema != self.default_schema_name:
referred_schema = conschema
else:
referred_schema = schema
elif referred_schema:
# referred_schema is the schema that we regexp'ed from
# pg_get_constraintdef(). If the schema is in the search
# path, pg_get_constraintdef() will give us None.
referred_schema = preparer._unquote_identifier(referred_schema)
elif schema is not None and schema == conschema:
# If the actual schema matches the schema of the table
# we're reflecting, then we will use that.
referred_schema = schema
referred_table = preparer._unquote_identifier(referred_table)
referred_columns = [
preparer._unquote_identifier(x)
for x in re.split(r"\s*,\s", referred_columns)
]
options = {
k: v
for k, v in [
("onupdate", onupdate),
("ondelete", ondelete),
("initially", initially),
("deferrable", deferrable),
("match", match),
]
if v is not None and v != "NO ACTION"
}
fkey_d = {
"name": conname,
"constrained_columns": constrained_columns,
"referred_schema": referred_schema,
"referred_table": referred_table,
"referred_columns": referred_columns,
"options": options,
"comment": comment,
}
table_fks.append(fkey_d)
return fkeys.items()
@reflection.cache
def get_indexes(self, connection, table_name, schema=None, **kw):
data = self.get_multi_indexes(
connection,
schema=schema,
filter_names=[table_name],
scope=ObjectScope.ANY,
kind=ObjectKind.ANY,
**kw,
)
return self._value_or_raise(data, table_name, schema)
@util.memoized_property
def _index_query(self):
# NOTE: pg_index is used as from two times to improve performance,
# since extraing all the index information from `idx_sq` to avoid
# the second pg_index use leads to a worse performing query in
# particular when querying for a single table (as of pg 17)
# NOTE: repeating oids clause improve query performance
# subquery to get the columns
idx_sq = (
select(
pg_catalog.pg_index.c.indexrelid,
pg_catalog.pg_index.c.indrelid,
sql.func.unnest(pg_catalog.pg_index.c.indkey).label("attnum"),
sql.func.unnest(pg_catalog.pg_index.c.indclass).label(
"att_opclass"
),
sql.func.generate_subscripts(
pg_catalog.pg_index.c.indkey, 1
).label("ord"),
)
.where(
~pg_catalog.pg_index.c.indisprimary,
pg_catalog.pg_index.c.indrelid.in_(bindparam("oids")),
)
.subquery("idx")
)
attr_sq = (
select(
idx_sq.c.indexrelid,
idx_sq.c.indrelid,
idx_sq.c.ord,
# NOTE: always using pg_get_indexdef is too slow so just
# invoke when the element is an expression
sql.case(
(
idx_sq.c.attnum == 0,
pg_catalog.pg_get_indexdef(
idx_sq.c.indexrelid, idx_sq.c.ord + 1, True
),
),
# NOTE: need to cast this since attname is of type "name"
# that's limited to 63 bytes, while pg_get_indexdef
# returns "text" so its output may get cut
else_=pg_catalog.pg_attribute.c.attname.cast(TEXT),
).label("element"),
(idx_sq.c.attnum == 0).label("is_expr"),
# since it's converted to array cast it to bigint (oid are
# "unsigned four-byte integer") to make it easier for
# dialects to interpret
idx_sq.c.att_opclass.cast(BIGINT),
)
.select_from(idx_sq)
.outerjoin(
# do not remove rows where idx_sq.c.attnum is 0
pg_catalog.pg_attribute,
sql.and_(
pg_catalog.pg_attribute.c.attnum == idx_sq.c.attnum,
pg_catalog.pg_attribute.c.attrelid == idx_sq.c.indrelid,
),
)
.where(idx_sq.c.indrelid.in_(bindparam("oids")))
.subquery("idx_attr")
)
cols_sq = (
select(
attr_sq.c.indexrelid,
sql.func.min(attr_sq.c.indrelid),
sql.func.array_agg(
aggregate_order_by(attr_sq.c.element, attr_sq.c.ord)
).label("elements"),
sql.func.array_agg(
aggregate_order_by(attr_sq.c.is_expr, attr_sq.c.ord)
).label("elements_is_expr"),
sql.func.array_agg(
aggregate_order_by(attr_sq.c.att_opclass, attr_sq.c.ord)
).label("elements_opclass"),
)
.group_by(attr_sq.c.indexrelid)
.subquery("idx_cols")
)
if self.server_version_info >= (11, 0):
indnkeyatts = pg_catalog.pg_index.c.indnkeyatts
else:
indnkeyatts = pg_catalog.pg_index.c.indnatts.label("indnkeyatts")
if self.server_version_info >= (15,):
nulls_not_distinct = pg_catalog.pg_index.c.indnullsnotdistinct
else:
nulls_not_distinct = sql.false().label("indnullsnotdistinct")
return (
select(
pg_catalog.pg_index.c.indrelid,
pg_catalog.pg_class.c.relname,
pg_catalog.pg_index.c.indisunique,
pg_catalog.pg_constraint.c.conrelid.is_not(None).label(
"has_constraint"
),
pg_catalog.pg_index.c.indoption,
pg_catalog.pg_class.c.reloptions,
# will get the value using the pg_am cached dict
pg_catalog.pg_class.c.relam,
# NOTE: pg_get_expr is very fast so this case has almost no
# performance impact
sql.case(
(
pg_catalog.pg_index.c.indpred.is_not(None),
pg_catalog.pg_get_expr(
pg_catalog.pg_index.c.indpred,
pg_catalog.pg_index.c.indrelid,
),
),
else_=None,
).label("filter_definition"),
indnkeyatts,
nulls_not_distinct,
cols_sq.c.elements,
cols_sq.c.elements_is_expr,
# will get the value using the pg_opclass cached dict
cols_sq.c.elements_opclass,
)
.select_from(pg_catalog.pg_index)
.where(
pg_catalog.pg_index.c.indrelid.in_(bindparam("oids")),
~pg_catalog.pg_index.c.indisprimary,
)
.join(
pg_catalog.pg_class,
pg_catalog.pg_index.c.indexrelid == pg_catalog.pg_class.c.oid,
)
.outerjoin(
cols_sq,
pg_catalog.pg_index.c.indexrelid == cols_sq.c.indexrelid,
)
.outerjoin(
pg_catalog.pg_constraint,
sql.and_(
pg_catalog.pg_index.c.indrelid
== pg_catalog.pg_constraint.c.conrelid,
pg_catalog.pg_index.c.indexrelid
== pg_catalog.pg_constraint.c.conindid,
pg_catalog.pg_constraint.c.contype
== sql.any_(_array.array(("p", "u", "x"))),
),
)
.order_by(
pg_catalog.pg_index.c.indrelid, pg_catalog.pg_class.c.relname
)
)
def get_multi_indexes(
self, connection, schema, filter_names, scope, kind, **kw
):
table_oids = self._get_table_oids(
connection, schema, filter_names, scope, kind, **kw
)
pg_am_btree_oid = self._load_pg_am_btree_oid(connection)
# lazy load only if needed, the assumption is that most indexes
# will use btree so it may not be needed at all
pg_am_dict = None
pg_opclass_dict = self._load_pg_opclass_notdefault_dict(
connection, **kw
)
indexes = defaultdict(list)
default = ReflectionDefaults.indexes
batches = list(table_oids)
while batches:
batch = batches[0:3000]
batches[0:3000] = []
result = connection.execute(
self._index_query, {"oids": [r[0] for r in batch]}
).mappings()
result_by_oid = defaultdict(list)
for row_dict in result:
result_by_oid[row_dict["indrelid"]].append(row_dict)
for oid, table_name in batch:
if oid not in result_by_oid:
# ensure that each table has an entry, even if reflection
# is skipped because not supported
indexes[(schema, table_name)] = default()
continue
for row in result_by_oid[oid]:
index_name = row["relname"]
table_indexes = indexes[(schema, table_name)]
all_elements = row["elements"]
all_elements_is_expr = row["elements_is_expr"]
all_elements_opclass = row["elements_opclass"]
indnkeyatts = row["indnkeyatts"]
# "The number of key columns in the index, not counting any
# included columns, which are merely stored and do not
# participate in the index semantics"
if len(all_elements) > indnkeyatts:
# this is a "covering index" which has INCLUDE columns
# as well as regular index columns
inc_cols = all_elements[indnkeyatts:]
idx_elements = all_elements[:indnkeyatts]
idx_elements_is_expr = all_elements_is_expr[
:indnkeyatts
]
# postgresql does not support expression on included
# columns as of v14: "ERROR: expressions are not
# supported in included columns".
assert all(
not is_expr
for is_expr in all_elements_is_expr[indnkeyatts:]
)
idx_elements_opclass = all_elements_opclass[
:indnkeyatts
]
else:
idx_elements = all_elements
idx_elements_is_expr = all_elements_is_expr
inc_cols = []
idx_elements_opclass = all_elements_opclass
index = {"name": index_name, "unique": row["indisunique"]}
if any(idx_elements_is_expr):
index["column_names"] = [
None if is_expr else expr
for expr, is_expr in zip(
idx_elements, idx_elements_is_expr
)
]
index["expressions"] = idx_elements
else:
index["column_names"] = idx_elements
dialect_options = {}
postgresql_ops = {}
for name, opclass in zip(
idx_elements, idx_elements_opclass
):
# is not in the dict if the opclass is the default one
opclass_name = pg_opclass_dict.get(opclass)
if opclass_name is not None:
postgresql_ops[name] = opclass_name
if postgresql_ops:
dialect_options["postgresql_ops"] = postgresql_ops
sorting = {}
for col_index, col_flags in enumerate(row["indoption"]):
col_sorting = ()
# try to set flags only if they differ from PG
# defaults...
if col_flags & 0x01:
col_sorting += ("desc",)
if not (col_flags & 0x02):
col_sorting += ("nulls_last",)
else:
if col_flags & 0x02:
col_sorting += ("nulls_first",)
if col_sorting:
sorting[idx_elements[col_index]] = col_sorting
if sorting:
index["column_sorting"] = sorting
if row["has_constraint"]:
index["duplicates_constraint"] = index_name
if row["reloptions"]:
dialect_options["postgresql_with"] = dict(
[
option.split("=", 1)
for option in row["reloptions"]
]
)
# it *might* be nice to include that this is 'btree' in the
# reflection info. But we don't want an Index object
# to have a ``postgresql_using`` in it that is just the
# default, so for the moment leaving this out.
if row["relam"] != pg_am_btree_oid:
if pg_am_dict is None:
pg_am_dict = self._load_pg_am_dict(
connection, **kw
)
dialect_options["postgresql_using"] = pg_am_dict[
row["relam"]
]
if row["filter_definition"]:
dialect_options["postgresql_where"] = row[
"filter_definition"
]
if self.server_version_info >= (11,):
# NOTE: this is legacy, this is part of
# dialect_options now as of #7382
index["include_columns"] = inc_cols
dialect_options["postgresql_include"] = inc_cols
if row["indnullsnotdistinct"]:
# the default is False, so ignore it.
dialect_options["postgresql_nulls_not_distinct"] = row[
"indnullsnotdistinct"
]
if dialect_options:
index["dialect_options"] = dialect_options
table_indexes.append(index)
return indexes.items()
@reflection.cache
def get_unique_constraints(
self, connection, table_name, schema=None, **kw
):
data = self.get_multi_unique_constraints(
connection,
schema=schema,
filter_names=[table_name],
scope=ObjectScope.ANY,
kind=ObjectKind.ANY,
**kw,
)
return self._value_or_raise(data, table_name, schema)
def get_multi_unique_constraints(
self,
connection,
schema,
filter_names,
scope,
kind,
**kw,
):
result = self._reflect_constraint(
connection, "u", schema, filter_names, scope, kind, **kw
)
# each table can have multiple unique constraints
uniques = defaultdict(list)
default = ReflectionDefaults.unique_constraints
for table_name, cols, con_name, comment, options in result:
# ensure a list is created for each table. leave it empty if
# the table has no unique cosntraint
if con_name is None:
uniques[(schema, table_name)] = default()
continue
uc_dict = {
"column_names": cols,
"name": con_name,
"comment": comment,
}
if options:
uc_dict["dialect_options"] = options
uniques[(schema, table_name)].append(uc_dict)
return uniques.items()
@reflection.cache
def get_table_comment(self, connection, table_name, schema=None, **kw):
data = self.get_multi_table_comment(
connection,
schema,
[table_name],
scope=ObjectScope.ANY,
kind=ObjectKind.ANY,
**kw,
)
return self._value_or_raise(data, table_name, schema)
@lru_cache()
def _comment_query(self, schema, has_filter_names, scope, kind):
relkinds = self._kind_to_relkinds(kind)
query = (
select(
pg_catalog.pg_class.c.relname,
pg_catalog.pg_description.c.description,
)
.select_from(pg_catalog.pg_class)
.outerjoin(
pg_catalog.pg_description,
sql.and_(
pg_catalog.pg_class.c.oid
== pg_catalog.pg_description.c.objoid,
pg_catalog.pg_description.c.objsubid == 0,
pg_catalog.pg_description.c.classoid
== sql.func.cast("pg_catalog.pg_class", REGCLASS),
),
)
.where(self._pg_class_relkind_condition(relkinds))
)
query = self._pg_class_filter_scope_schema(query, schema, scope)
if has_filter_names:
query = query.where(
pg_catalog.pg_class.c.relname.in_(bindparam("filter_names"))
)
return query
def get_multi_table_comment(
self, connection, schema, filter_names, scope, kind, **kw
):
has_filter_names, params = self._prepare_filter_names(filter_names)
query = self._comment_query(schema, has_filter_names, scope, kind)
result = connection.execute(query, params)
default = ReflectionDefaults.table_comment
return (
(
(schema, table),
{"text": comment} if comment is not None else default(),
)
for table, comment in result
)
@reflection.cache
def get_check_constraints(self, connection, table_name, schema=None, **kw):
data = self.get_multi_check_constraints(
connection,
schema,
[table_name],
scope=ObjectScope.ANY,
kind=ObjectKind.ANY,
**kw,
)
return self._value_or_raise(data, table_name, schema)
@lru_cache()
def _check_constraint_query(self, schema, has_filter_names, scope, kind):
relkinds = self._kind_to_relkinds(kind)
query = (
select(
pg_catalog.pg_class.c.relname,
pg_catalog.pg_constraint.c.conname,
# NOTE: avoid calling pg_get_constraintdef when not needed
# to speed up the query
sql.case(
(
pg_catalog.pg_constraint.c.oid.is_not(None),
pg_catalog.pg_get_constraintdef(
pg_catalog.pg_constraint.c.oid, True
),
),
else_=None,
),
pg_catalog.pg_description.c.description,
)
.select_from(pg_catalog.pg_class)
.outerjoin(
pg_catalog.pg_constraint,
sql.and_(
pg_catalog.pg_class.c.oid
== pg_catalog.pg_constraint.c.conrelid,
pg_catalog.pg_constraint.c.contype == "c",
),
)
.outerjoin(
pg_catalog.pg_description,
pg_catalog.pg_description.c.objoid
== pg_catalog.pg_constraint.c.oid,
)
.order_by(
pg_catalog.pg_class.c.relname,
pg_catalog.pg_constraint.c.conname,
)
.where(self._pg_class_relkind_condition(relkinds))
)
query = self._pg_class_filter_scope_schema(query, schema, scope)
if has_filter_names:
query = query.where(
pg_catalog.pg_class.c.relname.in_(bindparam("filter_names"))
)
return query
def get_multi_check_constraints(
self, connection, schema, filter_names, scope, kind, **kw
):
has_filter_names, params = self._prepare_filter_names(filter_names)
query = self._check_constraint_query(
schema, has_filter_names, scope, kind
)
result = connection.execute(query, params)
check_constraints = defaultdict(list)
default = ReflectionDefaults.check_constraints
for table_name, check_name, src, comment in result:
# only two cases for check_name and src: both null or both defined
if check_name is None and src is None:
check_constraints[(schema, table_name)] = default()
continue
# samples:
# "CHECK (((a > 1) AND (a < 5)))"
# "CHECK (((a = 1) OR ((a > 2) AND (a < 5))))"
# "CHECK (((a > 1) AND (a < 5))) NOT VALID"
# "CHECK (some_boolean_function(a))"
# "CHECK (((a\n < 1)\n OR\n (a\n >= 5))\n)"
# "CHECK (a NOT NULL) NO INHERIT"
# "CHECK (a NOT NULL) NO INHERIT NOT VALID"
m = re.match(
r"^CHECK *\((.+)\)( NO INHERIT)?( NOT VALID)?$",
src,
flags=re.DOTALL,
)
if not m:
util.warn("Could not parse CHECK constraint text: %r" % src)
sqltext = ""
else:
sqltext = re.compile(
r"^[\s\n]*\((.+)\)[\s\n]*$", flags=re.DOTALL
).sub(r"\1", m.group(1))
entry = {
"name": check_name,
"sqltext": sqltext,
"comment": comment,
}
if m:
do = {}
if " NOT VALID" in m.groups():
do["not_valid"] = True
if " NO INHERIT" in m.groups():
do["no_inherit"] = True
if do:
entry["dialect_options"] = do
check_constraints[(schema, table_name)].append(entry)
return check_constraints.items()
def _pg_type_filter_schema(self, query, schema):
if schema is None:
query = query.where(
pg_catalog.pg_type_is_visible(pg_catalog.pg_type.c.oid),
# ignore pg_catalog schema
pg_catalog.pg_namespace.c.nspname != "pg_catalog",
)
elif schema != "*":
query = query.where(pg_catalog.pg_namespace.c.nspname == schema)
return query
@lru_cache()
def _enum_query(self, schema):
lbl_agg_sq = (
select(
pg_catalog.pg_enum.c.enumtypid,
sql.func.array_agg(
aggregate_order_by(
# NOTE: cast since some postgresql derivatives may
# not support array_agg on the name type
pg_catalog.pg_enum.c.enumlabel.cast(TEXT),
pg_catalog.pg_enum.c.enumsortorder,
)
).label("labels"),
)
.group_by(pg_catalog.pg_enum.c.enumtypid)
.subquery("lbl_agg")
)
query = (
select(
pg_catalog.pg_type.c.typname.label("name"),
pg_catalog.pg_type_is_visible(pg_catalog.pg_type.c.oid).label(
"visible"
),
pg_catalog.pg_namespace.c.nspname.label("schema"),
lbl_agg_sq.c.labels.label("labels"),
)
.join(
pg_catalog.pg_namespace,
pg_catalog.pg_namespace.c.oid
== pg_catalog.pg_type.c.typnamespace,
)
.outerjoin(
lbl_agg_sq, pg_catalog.pg_type.c.oid == lbl_agg_sq.c.enumtypid
)
.where(pg_catalog.pg_type.c.typtype == "e")
.order_by(
pg_catalog.pg_namespace.c.nspname, pg_catalog.pg_type.c.typname
)
)
return self._pg_type_filter_schema(query, schema)
@reflection.cache
def _load_enums(self, connection, schema=None, **kw):
if not self.supports_native_enum:
return []
result = connection.execute(self._enum_query(schema))
enums = []
for name, visible, schema, labels in result:
enums.append(
{
"name": name,
"schema": schema,
"visible": visible,
"labels": [] if labels is None else labels,
}
)
return enums
@lru_cache()
def _domain_query(self, schema):
con_sq = (
select(
pg_catalog.pg_constraint.c.contypid,
sql.func.array_agg(
pg_catalog.pg_get_constraintdef(
pg_catalog.pg_constraint.c.oid, True
)
).label("condefs"),
sql.func.array_agg(
# NOTE: cast since some postgresql derivatives may
# not support array_agg on the name type
pg_catalog.pg_constraint.c.conname.cast(TEXT)
).label("connames"),
)
# The domain this constraint is on; zero if not a domain constraint
.where(pg_catalog.pg_constraint.c.contypid != 0)
.group_by(pg_catalog.pg_constraint.c.contypid)
.subquery("domain_constraints")
)
query = (
select(
pg_catalog.pg_type.c.typname.label("name"),
pg_catalog.format_type(
pg_catalog.pg_type.c.typbasetype,
pg_catalog.pg_type.c.typtypmod,
).label("attype"),
(~pg_catalog.pg_type.c.typnotnull).label("nullable"),
pg_catalog.pg_type.c.typdefault.label("default"),
pg_catalog.pg_type_is_visible(pg_catalog.pg_type.c.oid).label(
"visible"
),
pg_catalog.pg_namespace.c.nspname.label("schema"),
con_sq.c.condefs,
con_sq.c.connames,
pg_catalog.pg_collation.c.collname,
)
.join(
pg_catalog.pg_namespace,
pg_catalog.pg_namespace.c.oid
== pg_catalog.pg_type.c.typnamespace,
)
.outerjoin(
pg_catalog.pg_collation,
pg_catalog.pg_type.c.typcollation
== pg_catalog.pg_collation.c.oid,
)
.outerjoin(
con_sq,
pg_catalog.pg_type.c.oid == con_sq.c.contypid,
)
.where(pg_catalog.pg_type.c.typtype == "d")
.order_by(
pg_catalog.pg_namespace.c.nspname, pg_catalog.pg_type.c.typname
)
)
return self._pg_type_filter_schema(query, schema)
@reflection.cache
def _load_domains(self, connection, schema=None, **kw):
result = connection.execute(self._domain_query(schema))
domains: List[ReflectedDomain] = []
for domain in result.mappings():
# strip (30) from character varying(30)
attype = re.search(r"([^\(]+)", domain["attype"]).group(1)
constraints: List[ReflectedDomainConstraint] = []
if domain["connames"]:
# When a domain has multiple CHECK constraints, they will
# be tested in alphabetical order by name.
sorted_constraints = sorted(
zip(domain["connames"], domain["condefs"]),
key=lambda t: t[0],
)
for name, def_ in sorted_constraints:
# constraint is in the form "CHECK (expression)"
# or "NOT NULL". Ignore the "NOT NULL" and
# remove "CHECK (" and the tailing ")".
if def_.casefold().startswith("check"):
check = def_[7:-1]
constraints.append({"name": name, "check": check})
domain_rec: ReflectedDomain = {
"name": domain["name"],
"schema": domain["schema"],
"visible": domain["visible"],
"type": attype,
"nullable": domain["nullable"],
"default": domain["default"],
"constraints": constraints,
"collation": domain["collname"],
}
domains.append(domain_rec)
return domains
@util.memoized_property
def _pg_am_query(self):
return sql.select(pg_catalog.pg_am.c.oid, pg_catalog.pg_am.c.amname)
@reflection.cache
def _load_pg_am_dict(self, connection, **kw) -> dict[int, str]:
rows = connection.execute(self._pg_am_query)
return dict(rows.all())
def _load_pg_am_btree_oid(self, connection):
# this oid is assumed to be stable
if self._pg_am_btree_oid == -1:
self._pg_am_btree_oid = connection.scalar(
self._pg_am_query.where(pg_catalog.pg_am.c.amname == "btree")
)
return self._pg_am_btree_oid
@util.memoized_property
def _pg_opclass_notdefault_query(self):
return sql.select(
pg_catalog.pg_opclass.c.oid, pg_catalog.pg_opclass.c.opcname
).where(~pg_catalog.pg_opclass.c.opcdefault)
@reflection.cache
def _load_pg_opclass_notdefault_dict(
self, connection, **kw
) -> dict[int, str]:
rows = connection.execute(self._pg_opclass_notdefault_query)
return dict(rows.all())
def _set_backslash_escapes(self, connection):
# this method is provided as an override hook for descendant
# dialects (e.g. Redshift), so removing it may break them
std_string = connection.exec_driver_sql(
"show standard_conforming_strings"
).scalar()
self._backslash_escapes = std_string == "off"
| PGDialect |
python | streamlit__streamlit | lib/streamlit/watcher/polling_path_watcher.py | {
"start": 1157,
"end": 4402
} | class ____:
"""Watches a path on disk via a polling loop."""
_executor = ThreadPoolExecutor(max_workers=_MAX_WORKERS)
@staticmethod
def close_all() -> None:
"""Close top-level watcher object.
This is a no-op, and exists for interface parity with
EventBasedPathWatcher.
"""
_LOGGER.debug("Watcher closed")
def __init__(
self,
path: str,
on_changed: Callable[[str], None],
*, # keyword-only arguments:
glob_pattern: str | None = None,
allow_nonexistent: bool = False,
) -> None:
"""Constructor.
You do not need to retain a reference to a PollingPathWatcher to
prevent it from being garbage collected. (The global _executor object
retains references to all active instances.)
"""
# TODO(vdonato): Modernize this by switching to pathlib.
self._path = Path(path) # Changed to pathlib.Path
self._on_changed = on_changed
self._glob_pattern = glob_pattern
self._allow_nonexistent = allow_nonexistent
self._active = True
self._modification_time = util.path_modification_time(
str(self._path), self._allow_nonexistent
)
self._md5 = util.calc_md5_with_blocking_retries(
str(self._path),
glob_pattern=self._glob_pattern,
allow_nonexistent=self._allow_nonexistent,
)
self._schedule()
def __repr__(self) -> str:
return repr_(self)
def _schedule(self) -> None:
def task() -> None:
time.sleep(_POLLING_PERIOD_SECS)
self._check_if_path_changed()
PollingPathWatcher._executor.submit(task)
def _check_if_path_changed(self) -> None:
if not self._active:
# Don't call self._schedule()
return
try:
modification_time = util.path_modification_time(
str(self._path), self._allow_nonexistent
)
# We add modification_time != 0.0 check since on some file systems (s3fs/fuse)
# modification_time is always 0.0 because of file system limitations.
if (
modification_time != 0.0
and modification_time <= self._modification_time
):
self._schedule()
return
self._modification_time = modification_time
md5 = util.calc_md5_with_blocking_retries(
str(self._path),
glob_pattern=self._glob_pattern,
allow_nonexistent=self._allow_nonexistent,
)
if md5 == self._md5:
self._schedule()
return
except StreamlitMaxRetriesError as ex:
_LOGGER.debug(
"Ignoring file change. Failed to calculate MD5 for path %s",
self._path,
exc_info=ex,
)
return
self._md5 = md5
_LOGGER.debug("Change detected: %s", self._path)
self._on_changed(str(self._path))
self._schedule()
def close(self) -> None:
"""Stop watching the file system."""
self._active = False
| PollingPathWatcher |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/coercions.py | {
"start": 33287,
"end": 34190
} | class ____(_CoerceLiterals, RoleImpl):
__slots__ = ()
def _post_coercion(
self, resolved, *, original_element, argname=None, **kw
):
if resolved is not original_element and not isinstance(
original_element, str
):
# use same method as Connection uses
try:
original_element._execute_on_connection
except AttributeError as err:
raise exc.ObjectNotExecutableError(original_element) from err
return resolved
def _implicit_coercions(
self,
element: Any,
resolved: Any,
argname: Optional[str] = None,
**kw: Any,
) -> Any:
if resolved._is_lambda_element:
return resolved
else:
return super()._implicit_coercions(
element, resolved, argname=argname, **kw
)
| StatementImpl |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/decorator4.py | {
"start": 183,
"end": 406
} | class ____:
pass
def decorator1(fn):
# This decorator returns a value that is
# inferred to be a union containing an Unknown type.
if fn:
return my_module.unknown
return Class2
@decorator1
| Class2 |
python | pikepdf__pikepdf | src/pikepdf/_methods.py | {
"start": 27229,
"end": 27707
} | class ____:
def keys(self):
return KeysView(self._as_map())
def values(self):
return ValuesView(self._as_map())
def items(self):
return ItemsView(self._as_map())
get = MutableMapping.get
pop = MutableMapping.pop
popitem = MutableMapping.popitem
clear = MutableMapping.clear
update = MutableMapping.update
setdefault = MutableMapping.setdefault
MutableMapping.register(NameTree)
@augments(NumberTree)
| Extend_NameTree |
python | allegroai__clearml | clearml/task.py | {
"start": 4643,
"end": 256599
} | class ____(_Task):
"""
The ``Task`` class is a code template for a Task object which, together with its connected experiment components,
represents the current running experiment. These connected components include hyperparameters, loggers,
configuration, label enumeration, models, and other artifacts.
The term "main execution Task" refers to the Task context for current running experiment. Python experiment scripts
can create one, and only one, main execution Task. It is traceable, and after a script runs and ClearML stores
the Task in the **ClearML Server** (backend), it is modifiable, reproducible, executable by a worker, and you
can duplicate it for further experimentation.
The ``Task`` class and its methods allow you to create and manage experiments, as well as perform
advanced experimentation functions, such as autoML.
.. warning::
Do not construct Task objects directly. Use one of the methods listed below to create experiments or
reference existing experiments.
Do not define `CLEARML_TASK_*` and `CLEARML_PROC_*` OS environments, they are used internally
for bookkeeping between processes and agents.
For detailed information about creating Task objects, see the following methods:
- Create a new reproducible Task - :meth:`Task.init`
.. important::
In some cases, ``Task.init`` may return a Task object which is already stored in **ClearML Server** (already
initialized), instead of creating a new Task. For a detailed explanation of those cases, see the ``Task.init``
method.
- Manually create a new Task (no auto-logging will apply) - :meth:`Task.create`
- Get the current running Task - :meth:`Task.current_task`
- Get another (different) Task - :meth:`Task.get_task`
.. note::
The **ClearML** documentation often refers to a Task as, "Task (experiment)".
"Task" refers to the class in the ClearML Python Client Package, the object in your Python experiment script,
and the entity with which **ClearML Server** and **ClearML Agent** work.
"Experiment" refers to your deep learning solution, including its connected components, inputs, and outputs,
and is the experiment you can view, analyze, compare, modify, duplicate, and manage using the ClearML
**Web-App** (UI).
Therefore, a "Task" is effectively an "experiment", and "Task (experiment)" encompasses its usage throughout
the ClearML.
The exception to this Task behavior is sub-tasks (non-reproducible Tasks), which do not use the main execution
Task. Creating a sub-task always creates a new Task with a new Task ID.
"""
TaskTypes = _Task.TaskTypes
NotSet = object()
__create_protection = object()
__main_task: Optional["Task"] = None
__exit_hook = None
__forked_proc_main_pid = None
__task_id_reuse_time_window_in_hours = deferred_config("development.task_reuse_time_window_in_hours", 24.0, float)
__detect_repo_async = deferred_config("development.vcs_repo_detect_async", False)
__default_output_uri = DEV_DEFAULT_OUTPUT_URI.get() or deferred_config("development.default_output_uri", None)
__hidden_tag = "hidden"
_launch_multi_node_section = "launch_multi_node"
_launch_multi_node_instance_tag = "multi_node_instance"
_external_endpoint_port_map = {"http": "_PORT", "tcp": "external_tcp_port"}
_external_endpoint_address_map = {"http": "_ADDRESS", "tcp": "external_address"}
_external_endpoint_service_map = {"http": "EXTERNAL", "tcp": "EXTERNAL_TCP"}
_external_endpoint_internal_port_map = {
"http": "_PORT",
"tcp": "upstream_task_port",
}
_external_endpoint_host_tcp_port_mapping = {"tcp_host_mapping": "_external_host_tcp_port_mapping"}
class _ConnectedParametersType(object):
argparse = "argument_parser"
dictionary = "dictionary"
task_parameters = "task_parameters"
@classmethod
def _options(cls):
return {var for var, val in vars(cls).items() if isinstance(val, six.string_types)}
def __init__(self, private: Optional[Any] = None, **kwargs: Any) -> None:
"""
.. warning::
**Do not construct Task manually!**
Please use :meth:`Task.init` or :meth:`Task.get_task`
"""
if private is not Task.__create_protection:
raise UsageError(
"Task object cannot be instantiated externally, use Task.current_task() or Task.get_task(...)"
)
self._repo_detect_lock = threading.RLock()
super(Task, self).__init__(**kwargs)
self._arguments = _Arguments(self)
self._logger = None
self._connected_output_model = None
self._dev_worker = None
self._connected_parameter_type = None
self._detect_repo_async_thread = None
self._resource_monitor = None
self._calling_filename = None
self._remote_functions_generated = {}
self._external_endpoint_ports = {}
self._http_router = None
# register atexit, so that we mark the task as stopped
self._at_exit_called = False
@classmethod
def current_task(cls) -> TaskInstance:
"""
Get the current running Task (experiment). This is the main execution Task (task context) returned as a Task
object.
:return: The current running Task (experiment).
:rtype: Task
"""
# check if we have no main Task, but the main process created one.
if not cls.__main_task and cls.__get_master_id_task_id():
# initialize the Task, connect to stdout
cls.init()
# return main Task
return cls.__main_task
@classmethod
def init(
cls,
project_name: Optional[str] = None,
task_name: Optional[str] = None,
task_type: "Task.TaskTypes" = TaskTypes.training,
tags: Optional[Sequence[str]] = None,
reuse_last_task_id: Union[bool, str] = True,
continue_last_task: Union[bool, str, int] = False,
output_uri: Optional[Union[str, bool]] = None,
auto_connect_arg_parser: Union[bool, Mapping[str, bool]] = True,
auto_connect_frameworks: Union[bool, Mapping[str, Union[bool, str, list]]] = True,
auto_resource_monitoring: Union[bool, Mapping[str, Any]] = True,
auto_connect_streams: Union[bool, Mapping[str, bool]] = True,
deferred_init: bool = False,
) -> TaskInstance:
"""
Creates a new Task (experiment) if:
- The Task never ran before. No Task with the same ``task_name`` and ``project_name`` is stored in
**ClearML Server**.
- The Task has run before (the same ``task_name`` and ``project_name``), and (a) it stored models and / or
artifacts, or (b) its status is Published , or (c) it is Archived.
- A new Task is forced by calling ``Task.init`` with ``reuse_last_task_id=False``.
Otherwise, the already initialized Task object for the same ``task_name`` and ``project_name`` is returned,
or, when being executed remotely on a clearml-agent, the task returned is the existing task from the backend.
.. note::
To reference another Task, instead of initializing the same Task more than once, call
:meth:`Task.get_task`. For example, to "share" the same experiment in more than one script,
call ``Task.get_task``. See the ``Task.get_task`` method for an example.
For example:
The first time the following code runs, it will create a new Task. The status will be Completed.
.. code-block:: py
from clearml import Task
task = Task.init('myProject', 'myTask')
If this code runs again, it will not create a new Task. It does not store a model or artifact,
it is not Published (its status Completed) , it was not Archived, and a new Task is not forced.
If the Task is Published or Archived, and run again, it will create a new Task with a new Task ID.
The following code will create a new Task every time it runs, because it stores an artifact.
.. code-block:: py
task = Task.init('myProject', 'myOtherTask')
d = {'a': '1'}
task.upload_artifact('myArtifact', d)
:param str project_name: The name of the project in which the experiment will be created. If the project does
not exist, it is created. If ``project_name`` is ``None``, the repository name is used. (Optional)
:param str task_name: The name of Task (experiment). If ``task_name`` is ``None``, the Python experiment
script's file name is used. (Optional)
:param TaskTypes task_type: The task type. Valid task types:
- ``TaskTypes.training`` (default)
- ``TaskTypes.testing``
- ``TaskTypes.inference``
- ``TaskTypes.data_processing``
- ``TaskTypes.application``
- ``TaskTypes.monitor``
- ``TaskTypes.controller``
- ``TaskTypes.optimizer``
- ``TaskTypes.service``
- ``TaskTypes.qc``
- ``TaskTypes.custom``
:param tags: Add a list of tags (str) to the created Task. For example: tags=['512x512', 'yolov3']
:param bool reuse_last_task_id: Force a new Task (experiment) with a previously used Task ID,
and the same project and Task name. If the previously executed Task has artifacts or models, it will not be
reused (overwritten), and a new Task will be created. When a Task is reused, the previous execution outputs
are deleted, including console outputs and logs. The values are:
- ``True`` - Reuse the last Task ID. (default)
- ``False`` - Force a new Task (experiment).
- A string - You can also specify a Task ID (string) to be reused, instead of the cached ID based on the project/name combination.
:param bool continue_last_task: Continue the execution of a previously executed Task (experiment). When
continuing the executing of a previously executed Task,
all previous artifacts / models / logs remain intact.
New logs will continue iteration/step based on the previous-execution maximum iteration value.
For example, The last train/loss scalar reported was iteration 100, the next report will be iteration 101.
The values are:
- ``True`` - Continue the last Task ID. Specified explicitly by reuse_last_task_id or implicitly with the same logic as reuse_last_task_id
- ``False`` - Overwrite the execution of previous Task (default).
- A string - You can also specify a Task ID (string) to be continued. This is equivalent to `continue_last_task=True` and `reuse_last_task_id=a_task_id_string`.
- An integer - Specify initial iteration offset (override the auto automatic last_iteration_offset). Pass 0, to disable the automatic last_iteration_offset or specify a different initial offset. You can specify a Task ID to be used with `reuse_last_task_id='task_id_here'`
:param str output_uri: The default location for output models and other artifacts. If True, the default
files_server will be used for model storage. In the default location, ClearML creates a subfolder for the
output. If set to False, local runs will not upload output models and artifacts,
and remote runs will not use any default values provided using ``default_output_uri``.
The subfolder structure is the following: \\<output destination name\\> / \\<project name\\> / \\<task name\\>.\\<Task ID\\>.
Note that for cloud storage, you must install the **ClearML** package for your cloud storage type,
and then configure your storage credentials. For detailed information, see "Storage" in the ClearML
Documentation.
The following are examples of ``output_uri`` values for the supported locations:
- A shared folder: ``/mnt/share/folder``
- S3: ``s3://bucket/folder``
- Google Cloud Storage: ``gs://bucket-name/folder``
- Azure Storage: ``azure://company.blob.core.windows.net/folder/``
- Default file server: True
:param auto_connect_arg_parser: Automatically connect an argparse object to the Task. Supported argument
parser packages are: argparse, click, python-fire, jsonargparse. The values are:
- ``True`` - Automatically connect. (default)
- ``False`` - Do not automatically connect.
- A dictionary - In addition to a boolean, you can use a dictionary for fined grained control of connected
arguments. The dictionary keys are argparse variable names and the values are booleans.
The ``False`` value excludes the specified argument from the Task's parameter section.
Keys missing from the dictionary default to ``True``, you can change it to be ``False`` by adding
``*`` key as ``False`` to the dictionary.
An empty dictionary defaults to ``False``.
For example:
.. code-block:: py
auto_connect_arg_parser={"do_not_include_me": False, }
.. code-block:: py
auto_connect_arg_parser={"only_include_me": True, "*": False}
.. note::
To manually connect an argparse, use :meth:`Task.connect`.
:param auto_connect_frameworks: Automatically connect frameworks This includes patching MatplotLib, XGBoost,
scikit-learn, Keras callbacks, and TensorBoard/X to serialize plots, graphs, and the model location to
the **ClearML Server** (backend), in addition to original output destination.
The values are:
- ``True`` - Automatically connect (default)
- ``False`` - Do not automatically connect
- A dictionary - In addition to a boolean, you can use a dictionary for fined grained control of connected
frameworks. The dictionary keys are frameworks and the values are booleans, other dictionaries used for
finer control or wildcard strings.
In case of wildcard strings, the local path of a model file has to match at least one wildcard to be
saved/loaded by ClearML. Example: ``{'pytorch' : '*.pt', 'tensorflow': ['*.h5', '*']}``
Keys missing from the dictionary default to ``True``, and an empty dictionary defaults to ``False``.
Supported keys for finer control: ``{'tensorboard': {'report_hparams': bool}}`` # whether to report TensorBoard hyperparameters
For example:
.. code-block:: py
auto_connect_frameworks={
'matplotlib': True, 'tensorflow': ['*.hdf5, 'something_else*], 'tensorboard': True,
'pytorch': ['*.pt'], 'xgboost': True, 'scikit': True, 'fastai': True,
'lightgbm': True, 'hydra': True, 'detect_repository': True, 'tfdefines': True,
'joblib': True, 'megengine': True, 'catboost': True, 'gradio': True
}
.. code-block:: py
auto_connect_frameworks={'tensorboard': {'report_hparams': False}}
:param bool auto_resource_monitoring: Automatically create machine resource monitoring plots
These plots appear in the **ClearML Web-App (UI)**, **RESULTS** tab, **SCALARS** sub-tab,
with a title of **:resource monitor:**.
The values are:
- ``True`` - Automatically create resource monitoring plots. (default)
- ``False`` - Do not automatically create.
- Class Type - Create ResourceMonitor object of the specified class type.
- dict - Dictionary of kwargs to be passed to the ResourceMonitor instance. The keys can be:
- `report_start_sec` OR `first_report_sec` OR `seconds_from_start` - Maximum number of seconds
to wait for scalar/plot reporting before defaulting
to machine statistics reporting based on seconds from experiment start time
- `wait_for_first_iteration_to_start_sec` - Set the initial time (seconds) to wait for iteration
reporting to be used as x-axis for the resource monitoring,
if timeout exceeds then reverts to `seconds_from_start`
- `max_wait_for_first_iteration_to_start_sec` - Set the maximum time (seconds) to allow the resource
monitoring to revert back to iteration reporting x-axis after starting to report `seconds_from_start`
- `report_mem_used_per_process` OR `report_global_mem_used` - Compatibility feature,
report memory usage for the entire machine.
Default (false), report only on the running process and its sub-processes
:param auto_connect_streams: Control the automatic logging of stdout and stderr.
The values are:
- ``True`` - Automatically connect (default)
- ``False`` - Do not automatically connect
- A dictionary - In addition to a boolean, you can use a dictionary for fined grained control of stdout and
stderr. The dictionary keys are 'stdout' , 'stderr' and 'logging', the values are booleans.
Keys missing from the dictionary default to ``False``, and an empty dictionary defaults to ``False``.
Notice, the default behaviour is logging stdout/stderr. The `logging` module is logged as a by product
of the stderr logging
For example:
.. code-block:: py
auto_connect_streams={'stdout': True, 'stderr': True, 'logging': False}
:param deferred_init: (default: False) Wait for Task to be fully initialized (regular behaviour).
** BETA feature! use with care **.
If set to True, `Task.init` function returns immediately and all initialization / communication
to the clearml-server is running in a background thread. The returned object is
a full proxy to the regular Task object, hence everything will be working as expected.
Default behaviour can be controlled with: ``CLEARML_DEFERRED_TASK_INIT=1``. Notes:
- Any access to the returned proxy `Task` object will essentially wait for the `Task.init` to be completed.
For example: `print(task.name)` will wait for `Task.init` to complete in the
background and then return the `name` property of the task original object
- Before `Task.init` completes in the background, auto-magic logging (console/metric) might be missed
- If running via an agent, this argument is ignored, and Task init is called synchronously (default)
:return: The main execution Task (Task context)
:rtype: Task
"""
def verify_defaults_match() -> None:
validate = [
("project name", project_name, cls.__main_task.get_project_name()),
("task name", task_name, cls.__main_task.name),
(
"task type",
str(task_type) if task_type else task_type,
str(cls.__main_task.task_type),
),
]
for field, default, current in validate:
if default is not None and default != current:
raise UsageError(
"Current task already created "
"and requested {field} '{default}' does not match current {field} '{current}'. "
"If you wish to create additional tasks use `Task.create`, "
"or close the current task with `task.close()` before calling `Task.init(...)`".format(
field=field,
default=default,
current=current,
)
)
if cls.__main_task is not None and deferred_init != cls.__nested_deferred_init_flag:
# if this is a subprocess, regardless of what the init was called for,
# we have to fix the main task hooks and stdout bindings
if cls.__forked_proc_main_pid != os.getpid() and cls.__is_subprocess():
if task_type is None:
task_type = cls.__main_task.task_type
# make sure we only do it once per process
cls.__forked_proc_main_pid = os.getpid()
# make sure we do not wait for the repo detect thread
cls.__main_task._detect_repo_async_thread = None
cls.__main_task._dev_worker = None
cls.__main_task._resource_monitor = None
# if we are using threads to send the reports,
# after forking there are no threads, so we will need to recreate them
if not getattr(cls, "_report_subprocess_enabled"):
# remove the logger from the previous process
cls.__main_task.get_logger()
# create a new logger (to catch stdout/err)
cls.__main_task._logger = None
cls.__main_task.__reporter = None
# noinspection PyProtectedMember
cls.__main_task._get_logger(auto_connect_streams=auto_connect_streams)
cls.__main_task._artifacts_manager = Artifacts(cls.__main_task)
# unregister signal hooks, they cause subprocess to hang
# noinspection PyProtectedMember
cls.__main_task.__register_at_exit(cls.__main_task._at_exit)
# if we are using threads to send the reports,
# after forking there are no threads, so we will need to recreate them
if not getattr(cls, "_report_subprocess_enabled"):
# start all reporting threads
BackgroundMonitor.start_all(task=cls.__main_task)
if not running_remotely():
verify_defaults_match()
return cls.__main_task
is_sub_process_task_id = None
# check that we are not a child process, in that case do nothing.
# we should not get here unless this is Windows/macOS platform, linux support fork
if cls.__is_subprocess():
is_sub_process_task_id = cls.__get_master_id_task_id()
# we could not find a task ID, revert to old stub behaviour
if not is_sub_process_task_id:
return _TaskStub() # noqa
elif running_remotely() and not get_is_master_node():
# make sure we only do it once per process
cls.__forked_proc_main_pid = os.getpid()
# make sure everyone understands we should act as if we are a subprocess (fake pid 1)
cls.__update_master_pid_task(pid=1, task=get_remote_task_id())
else:
# set us as master process (without task ID)
cls.__update_master_pid_task()
is_sub_process_task_id = None
if task_type is None:
# Backwards compatibility: if called from Task.current_task and task_type
# was not specified, keep legacy default value of TaskTypes.training
task_type = cls.TaskTypes.training
elif isinstance(task_type, six.string_types):
if task_type not in Task.TaskTypes.__members__:
raise ValueError(
"Task type '{}' not supported, options are: {}".format(task_type, Task.TaskTypes.__members__.keys())
)
task_type = Task.TaskTypes.__members__[str(task_type)]
def safe_project_default_output_destination(task_, default=None):
project_ = task_.get_project_object()
return project_.default_output_destination if project_ else default
is_deferred = False
try:
if not running_remotely():
# check remote status
_local_rank = get_torch_local_rank()
if _local_rank is not None and _local_rank > 0:
is_sub_process_task_id = get_torch_distributed_anchor_task_id(timeout=30)
# only allow if running locally and creating the first Task
# otherwise we ignore and perform in order
if ENV_DEFERRED_TASK_INIT.get():
deferred_init = True
if not is_sub_process_task_id and deferred_init and deferred_init != cls.__nested_deferred_init_flag:
def completed_cb(x):
Task.__forked_proc_main_pid = os.getpid()
Task.__main_task = x
getLogger().warning("ClearML initializing Task in the background")
task = FutureTaskCaller(
func=cls.init,
func_cb=completed_cb,
override_cls=cls,
project_name=project_name,
task_name=task_name,
tags=tags,
reuse_last_task_id=reuse_last_task_id,
continue_last_task=continue_last_task,
output_uri=output_uri,
auto_connect_arg_parser=auto_connect_arg_parser,
auto_connect_frameworks=auto_connect_frameworks,
auto_resource_monitoring=auto_resource_monitoring,
auto_connect_streams=auto_connect_streams,
deferred_init=cls.__nested_deferred_init_flag,
)
is_deferred = True
# mark as temp master
cls.__update_master_pid_task()
# if this is the main process, create the task
elif not is_sub_process_task_id:
try:
task = cls._create_dev_task(
default_project_name=project_name,
default_task_name=task_name,
default_task_type=task_type,
tags=tags,
reuse_last_task_id=reuse_last_task_id,
continue_last_task=continue_last_task,
detect_repo=(
False
if (
isinstance(auto_connect_frameworks, dict)
and not auto_connect_frameworks.get("detect_repository", True)
)
else True
),
auto_connect_streams=auto_connect_streams,
)
# check if we are local rank 0 (local master),
# create an anchor with task ID for the other processes
if _local_rank == 0:
create_torch_distributed_anchor(task_id=task.id)
except MissingConfigError as e:
if not ENV_IGNORE_MISSING_CONFIG.get():
raise
getLogger().warning(str(e))
# return a Task-stub instead of the original class
# this will make sure users can still call the Stub without code breaking
return _TaskStub() # noqa
# set defaults
if cls._offline_mode:
task.output_uri = None
# create target data folder for logger / artifacts
# noinspection PyProtectedMember
Path(task._get_default_report_storage_uri()).mkdir(parents=True, exist_ok=True)
elif output_uri is not None:
if output_uri is True:
output_uri = safe_project_default_output_destination(task) or True
task.output_uri = output_uri
elif safe_project_default_output_destination(task):
task.output_uri = safe_project_default_output_destination(task)
elif cls.__default_output_uri:
task.output_uri = str(cls.__default_output_uri)
# store new task ID
cls.__update_master_pid_task(task=task)
else:
# subprocess should get back the task info
task = cls.get_task(task_id=is_sub_process_task_id)
else:
# if this is the main process, create the task
if not is_sub_process_task_id:
task = cls(
private=cls.__create_protection,
task_id=get_remote_task_id(),
log_to_backend=False,
)
if output_uri is False and not task.output_uri:
# Setting output_uri=False argument will disable using any default when running remotely
pass
else:
if safe_project_default_output_destination(task) and not task.output_uri:
task.output_uri = safe_project_default_output_destination(task)
if cls.__default_output_uri and not task.output_uri:
task.output_uri = cls.__default_output_uri
# store new task ID
cls.__update_master_pid_task(task=task)
# make sure we are started
task.started(ignore_errors=True)
# continue last iteration if we had any (or we need to override it)
if isinstance(continue_last_task, int) and not isinstance(continue_last_task, bool):
task.set_initial_iteration(int(continue_last_task))
elif task.data.last_iteration:
task.set_initial_iteration(int(task.data.last_iteration) + 1)
else:
# subprocess should get back the task info
task = cls.get_task(task_id=is_sub_process_task_id)
except Exception:
raise
else:
Task.__forked_proc_main_pid = os.getpid()
Task.__main_task = task
# register at exist only on the real (none deferred) Task
if not is_deferred:
# register the main task for at exit hooks (there should only be one)
# noinspection PyProtectedMember
task.__register_at_exit(task._at_exit)
# noinspection PyProtectedMember
if cls.__exit_hook:
cls.__exit_hook.register_signal_and_exception_hooks()
# always patch OS forking because of ProcessPool and the alike
PatchOsFork.patch_fork(task)
if auto_connect_frameworks:
def should_connect(*keys):
"""
Evaluates value of auto_connect_frameworks[keys[0]]...[keys[-1]].
If at some point in the evaluation, the value of auto_connect_frameworks[keys[0]]...[keys[-1]]
is a bool, that value will be returned. If a dictionary is empty, it will be evaluated to False.
If a key will not be found in the current dictionary, True will be returned.
"""
should_bind_framework = auto_connect_frameworks
for key in keys:
if not isinstance(should_bind_framework, dict):
return bool(should_bind_framework)
if should_bind_framework == {}:
return False
should_bind_framework = should_bind_framework.get(key, True)
return bool(should_bind_framework)
if not is_deferred and should_connect("hydra"):
PatchHydra.update_current_task(task)
if should_connect("scikit") and should_connect("joblib"):
PatchedJoblib.update_current_task(task)
if should_connect("matplotlib"):
PatchedMatplotlib.update_current_task(task)
if should_connect("tensorflow") or should_connect("tensorboard"):
# allow disabling tfdefines
if not is_deferred and should_connect("tfdefines"):
PatchAbsl.update_current_task(task)
TensorflowBinding.update_current_task(
task,
patch_reporting=should_connect("tensorboard"),
patch_model_io=should_connect("tensorflow"),
report_hparams=should_connect("tensorboard", "report_hparams"),
)
if should_connect("pytorch"):
PatchPyTorchModelIO.update_current_task(task)
if should_connect("megengine"):
PatchMegEngineModelIO.update_current_task(task)
if should_connect("xgboost"):
PatchXGBoostModelIO.update_current_task(task)
if should_connect("catboost"):
PatchCatBoostModelIO.update_current_task(task)
if should_connect("fastai"):
PatchFastai.update_current_task(task)
if should_connect("lightgbm"):
PatchLIGHTgbmModelIO.update_current_task(task)
if should_connect("gradio"):
PatchGradio.update_current_task(task)
cls.__add_model_wildcards(auto_connect_frameworks)
# if we are deferred, stop here (the rest we do in the actual init)
if is_deferred:
from .backend_interface.logger import StdStreamPatch
# patch console outputs, we will keep them in memory until we complete the Task init
# notice we do not load config defaults, as they are not threadsafe
# we might also need to override them with the vault
StdStreamPatch.patch_std_streams(
task.get_logger(),
connect_stdout=(auto_connect_streams is True)
or (isinstance(auto_connect_streams, dict) and auto_connect_streams.get("stdout", False)),
connect_stderr=(auto_connect_streams is True)
or (isinstance(auto_connect_streams, dict) and auto_connect_streams.get("stderr", False)),
load_config_defaults=False,
)
return task # noqa
if auto_resource_monitoring and not is_sub_process_task_id:
resource_monitor_cls = (
auto_resource_monitoring
if isinstance(auto_resource_monitoring, six.class_types)
else ResourceMonitor
)
resource_monitor_kwargs = dict(
report_mem_used_per_process=not config.get("development.worker.report_global_mem_used", False),
first_report_sec=config.get("development.worker.report_start_sec", None),
wait_for_first_iteration_to_start_sec=config.get(
"development.worker.wait_for_first_iteration_to_start_sec", None
),
max_wait_for_first_iteration_to_start_sec=config.get(
"development.worker.max_wait_for_first_iteration_to_start_sec",
None,
),
)
if isinstance(auto_resource_monitoring, dict):
if "report_start_sec" in auto_resource_monitoring:
auto_resource_monitoring["first_report_sec"] = auto_resource_monitoring.pop("report_start_sec")
if "seconds_from_start" in auto_resource_monitoring:
auto_resource_monitoring["first_report_sec"] = auto_resource_monitoring.pop(
"seconds_from_start"
)
if "report_global_mem_used" in auto_resource_monitoring:
auto_resource_monitoring["report_mem_used_per_process"] = auto_resource_monitoring.pop(
"report_global_mem_used"
)
resource_monitor_kwargs.update(auto_resource_monitoring)
task._resource_monitor = resource_monitor_cls(task, **resource_monitor_kwargs)
task._resource_monitor.start()
# make sure all random generators are initialized with new seed
random_seed = task.get_random_seed()
if random_seed is not None:
make_deterministic(random_seed)
task._set_random_seed_used(random_seed)
if auto_connect_arg_parser:
EnvironmentBind.update_current_task(task)
PatchJsonArgParse.update_current_task(task)
# Patch ArgParser to be aware of the current task
argparser_update_currenttask(task)
PatchClick.patch(task)
PatchFire.patch(task)
# set excluded arguments
if isinstance(auto_connect_arg_parser, dict):
task._arguments.exclude_parser_args(auto_connect_arg_parser)
# Check if parse args already called. If so, sync task parameters with parser
if argparser_parseargs_called():
for parser, parsed_args in get_argparser_last_args():
task._connect_argparse(parser=parser, parsed_args=parsed_args)
PatchHydra.delete_overrides()
elif argparser_parseargs_called():
# actually we have nothing to do, in remote running, the argparser will ignore
# all non argparser parameters, only caveat if parameter connected with the same name
# as the argparser this will be solved once sections are introduced to parameters
pass
# Make sure we start the logger, it will patch the main logging object and pipe all output
# if we are running locally and using development mode worker, we will pipe all stdout to logger.
# The logger will automatically take care of all patching (we just need to make sure to initialize it)
logger = task._get_logger(auto_connect_streams=auto_connect_streams)
# show the debug metrics page in the log, it is very convenient
if not is_sub_process_task_id:
if cls._offline_mode:
logger.report_text(
"ClearML running in offline mode, session stored in {}".format(task.get_offline_mode_folder())
)
else:
logger.report_text("ClearML results page: {}".format(task.get_output_log_web_page()))
# Make sure we start the dev worker if required, otherwise it will only be started when we write
# something to the log.
task._dev_mode_setup_worker()
if (
(not task._reporter or not task._reporter.is_constructed())
and is_sub_process_task_id
and not cls._report_subprocess_enabled
):
task._setup_reporter()
# start monitoring in background process or background threads
# monitoring are: Resource monitoring and Dev Worker monitoring classes
BackgroundMonitor.start_all(task=task)
# noinspection PyProtectedMember
task._set_startup_info()
return task
def get_http_router(self) -> "HttpRouter":
"""
Retrieve an instance of `HttpRouter` to manage an external HTTP endpoint and intercept traffic.
The `HttpRouter` serves as a traffic manager, enabling the creation and configuration of local and external
routesto redirect, monitor, or manipulate HTTP requests and responses. It is designed to handle routing
needs such via a proxy setup which handles request/response interception and telemetry reporting for
applications that require HTTP endpoint management.
Example usage:
.. code-block:: py
def request_callback(request, persistent_state):
persistent_state["last_request_time"] = time.time()
def response_callback(response, request, persistent_state):
print("Latency:", time.time() - persistent_state["last_request_time"])
if urllib.parse.urlparse(str(request.url).rstrip("/")).path == "/modify":
new_content = response.body.replace(b"modify", b"modified")
headers = copy.deepcopy(response.headers)
headers["Content-Length"] = str(len(new_content))
return Response(status_code=response.status_code, headers=headers, content=new_content)
router = Task.current_task().get_http_router()
router.set_local_proxy_parameters(incoming_port=9000)
router.create_local_route(
source="/",
target="http://localhost:8000",
request_callback=request_callback,
response_callback=response_callback,
endpoint_telemetry={"model": "MyModel"}
)
router.deploy(wait=True)
"""
try:
from .router.router import HttpRouter # noqa
except ImportError:
raise UsageError("Could not import `HttpRouter`. Please run `pip install clearml[router]`")
if self._http_router is None:
self._http_router = HttpRouter(self)
return self._http_router
@staticmethod
def _compose_runtime_key(base_key: str, suffix: Optional[str]) -> str:
return base_key if not suffix else "{}__{}".format(base_key, suffix)
def _collect_endpoint_suffixes(self, protocol: str, runtime_props: Mapping[str, Any]) -> Dict[str, Any]:
port_key = self._external_endpoint_port_map[protocol]
prefix = port_key + "__"
results: Dict[str, Any] = {}
for key, value in runtime_props.items():
if key == port_key:
results[DEFAULT_ENDPOINT_NAME] = value
elif key.startswith(prefix):
results[key[len(prefix) :]] = value
return results
def request_external_endpoint(
self,
port: int,
protocol: str = "http",
wait: bool = False,
wait_interval_seconds: float = 3.0,
wait_timeout_seconds: float = 90.0,
static_route: Optional[str] = None,
endpoint_name: Optional[str] = None,
) -> Optional[Dict]:
"""
Request an external endpoint for an application
:param port: Port the application is listening to
:param protocol: `http` or `tcp`
:param wait: If True, wait for the endpoint to be assigned
:param wait_interval_seconds: The poll frequency when waiting for the endpoint
:param wait_timeout_seconds: If this timeout is exceeded while waiting for the endpoint,
the method will no longer wait and None will be returned
:param static_route: The static route name (not the route path).
When set, the external endpoint requested will use this route
instead of generating it based on the task ID. Useful for creating
persistent, load balanced routes.
:param endpoint_name: Optional identifier for this endpoint. Useful to distinguish
between multiple endpoints. If not provided, the endpoint_name is auto-generated
:return: If wait is False, this method will return None.
If no endpoint could be found while waiting, this method returns None.
Otherwise, it returns a dictionary containing the following values:
- endpoint - raw endpoint. One might need to authenticate in order to use this endpoint
- browser_endpoint - endpoint to be used in browser. Authentication will be handled via the browser
- port - the port exposed by the application
- protocol - the protocol used by the endpoint
- name - the identifier used for this endpoint
"""
Session.verify_feature_set("advanced")
if protocol not in self._external_endpoint_port_map.keys():
raise ValueError("Invalid protocol: {}".format(protocol))
if static_route:
self._validate_static_route(static_route)
self.reload()
runtime_props = self._get_runtime_properties()
suffix_map = self._collect_endpoint_suffixes(protocol, runtime_props)
resolved_suffix = DEFAULT_ENDPOINT_NAME
if endpoint_name is not None:
resolved_suffix = str(endpoint_name)
elif DEFAULT_ENDPOINT_NAME in suffix_map:
index = 1
while str(index) in suffix_map:
index += 1
resolved_suffix = str(index)
external_host_port_mapping = runtime_props.get(
self._external_endpoint_host_tcp_port_mapping["tcp_host_mapping"]
)
if external_host_port_mapping:
out_port = None
# noinspection PyBroadException
try:
for port_range in external_host_port_mapping.split(","):
out_range, in_range = port_range.split(":", 1)
out_range = out_range.split("-")
in_range = in_range.split("-")
if int(in_range[0]) <= port <= int(in_range[-1]):
# we found a match
out_port = int(out_range[0]) + (port - int(in_range[0]))
print(
"INFO: Task.request_external_endpoint(...) changed requested external port to {}, "
"conforming to mapped external host ports [{} -> {}]".format(out_port, port, port_range)
)
break
except Exception:
print(
"WARNING: Task.request_external_endpoint(...) failed matching requested port to "
"mapped external host port [{} to {}], proceeding with original port {}".format(
port, external_host_port_mapping, port
)
)
if out_port:
port = out_port
runtime_key_suffix = None if resolved_suffix == DEFAULT_ENDPOINT_NAME else resolved_suffix
runtime_properties_to_set: Dict[str, Union[str, int]] = {
self._compose_runtime_key("_SERVICE", runtime_key_suffix): self._external_endpoint_service_map[protocol],
self._compose_runtime_key(
self._external_endpoint_address_map[protocol], runtime_key_suffix
): HOST_MACHINE_IP.get() or get_private_ip(),
self._compose_runtime_key(self._external_endpoint_port_map[protocol], runtime_key_suffix): port,
}
internal_port_key = self._external_endpoint_internal_port_map.get(protocol)
if internal_port_key and internal_port_key != self._external_endpoint_port_map[protocol]:
runtime_properties_to_set[
self._compose_runtime_key(internal_port_key, runtime_key_suffix)
] = port
if static_route:
runtime_properties_to_set.update(
{
self._compose_runtime_key("_ROUTER_ENDPOINT_MODE", runtime_key_suffix): "path",
self._compose_runtime_key("_ROUTER_ENDPOINT_MODE_PARAM", runtime_key_suffix): static_route,
}
)
# noinspection PyProtectedMember
self._set_runtime_properties(runtime_properties_to_set)
# required system_tag for the router to catch the routing request
self.set_system_tags(list(set((self.get_system_tags() or []) + ["external_service"])))
if wait:
return self.wait_for_external_endpoint(
wait_interval_seconds=wait_interval_seconds,
wait_timeout_seconds=wait_timeout_seconds,
protocol=protocol,
endpoint_name=None if runtime_key_suffix is None else runtime_key_suffix,
)
return None
def wait_for_external_endpoint(
self,
wait_interval_seconds: float = 3.0,
wait_timeout_seconds: float = 90.0,
protocol: Optional[str] = "http",
endpoint_name: Optional[str] = None,
) -> Union[Optional[Dict], List[Optional[Dict]]]:
"""
Wait for an external endpoint to be assigned
:param wait_interval_seconds: The poll frequency when waiting for the endpoint
:param wait_timeout_seconds: If this timeout is exceeded while waiting for the endpoint,
the method will no longer wait
:param protocol: `http` or `tcp`. Wait for an endpoint to be assigned based on the protocol.
If None, wait for all supported protocols
:param endpoint_name: Optional identifier of the endpoint to wait on.
:return: If no endpoint could be found while waiting, this method returns None.
If a protocol has been specified, it returns a dictionary containing the following values:
- endpoint - raw endpoint. One might need to authenticate in order to use this endpoint
- browser_endpoint - endpoint to be used in browser. Authentication will be handled via the browser
- port - the port exposed by the application
- protocol - the protocol used by the endpoint
- name - the identifier used for this endpoint
If not protocol is specified, it returns a list of dictionaries containing the values above,
for each protocol requested and waited
"""
Session.verify_feature_set("advanced")
if protocol is None and endpoint_name is not None:
raise ValueError("Endpoint name can only be specified when waiting on a specific protocol")
if protocol:
return self._wait_for_external_endpoint(
wait_interval_seconds=wait_interval_seconds,
wait_timeout_seconds=wait_timeout_seconds,
protocol=protocol,
endpoint_name=endpoint_name,
warn=True,
)
results = []
protocols = ["http", "tcp"]
waited_protocols = []
for protocol_ in protocols:
start_time = time.time()
result = self._wait_for_external_endpoint(
wait_interval_seconds=wait_interval_seconds,
wait_timeout_seconds=wait_timeout_seconds,
protocol=protocol_,
endpoint_name=None,
warn=False,
)
elapsed = time.time() - start_time
if result:
results.append(result)
wait_timeout_seconds -= elapsed
if wait_timeout_seconds > 0 or result:
waited_protocols.append(protocol_)
unwaited_protocols = [p for p in protocols if p not in waited_protocols]
if wait_timeout_seconds <= 0 and unwaited_protocols:
LoggerRoot.get_base_logger().warning(
"Timeout exceeded while waiting for {} endpoint(s)".format(",".join(unwaited_protocols))
)
return results
def _wait_for_external_endpoint(
self,
wait_interval_seconds=3.0,
wait_timeout_seconds=90.0,
protocol="http",
endpoint_name: Optional[str] = None,
warn=True,
):
resolved_suffix = DEFAULT_ENDPOINT_NAME if endpoint_name is None else str(endpoint_name)
first_iteration = True
start_time = time.time()
while True:
self.reload()
runtime_props = self._get_runtime_properties()
registry = self._collect_endpoint_suffixes(protocol, runtime_props)
if resolved_suffix not in registry:
if warn and first_iteration:
if resolved_suffix == DEFAULT_ENDPOINT_NAME:
LoggerRoot.get_base_logger().warning(
"No external {} endpoints have been requested".format(protocol)
)
else:
LoggerRoot.get_base_logger().warning(
"No external {} endpoint named '{}' has been requested".format(protocol, resolved_suffix)
)
return None
endpoint, browser_endpoint = None, None
runtime_key_suffix = None if resolved_suffix == DEFAULT_ENDPOINT_NAME else resolved_suffix
if protocol == "http":
endpoint = runtime_props.get(self._compose_runtime_key("endpoint", runtime_key_suffix))
browser_endpoint = runtime_props.get(self._compose_runtime_key("browser_endpoint", runtime_key_suffix))
elif protocol == "tcp":
health_check = runtime_props.get(
self._compose_runtime_key(self._external_endpoint_internal_port_map[protocol], runtime_key_suffix)
)
if health_check:
address_value = runtime_props.get(
self._compose_runtime_key(self._external_endpoint_address_map[protocol], runtime_key_suffix)
)
port_value = runtime_props.get(
self._compose_runtime_key(self._external_endpoint_port_map[protocol], runtime_key_suffix)
)
if address_value and port_value:
endpoint = "{}:{}".format(address_value, port_value)
if endpoint or browser_endpoint:
port_value = registry.get(resolved_suffix)
return {
"endpoint": endpoint,
"browser_endpoint": browser_endpoint,
"port": port_value,
"protocol": protocol,
"name": None if runtime_key_suffix is None else runtime_key_suffix,
}
if time.time() >= start_time + wait_timeout_seconds:
if warn:
warning_message = "Timeout exceeded while waiting for {} endpoint{}".format(
protocol,
"" if runtime_key_suffix is None else " '{}'".format(runtime_key_suffix),
)
LoggerRoot.get_base_logger().warning(warning_message)
return None
time.sleep(wait_interval_seconds)
first_iteration = False
def list_external_endpoints(self, protocol: Optional[str] = None) -> List[Dict]:
"""
List all external endpoints assigned
:param protocol: If None, list all external endpoints. Otherwise, only list endpoints
that use this protocol
:return: A list of dictionaries. Each dictionary contains the following values:
- endpoint - raw endpoint. One might need to authenticate in order to use this endpoint
- browser_endpoint - endpoint to be used in browser. Authentication will be handled via the browser
- port - the port exposed by the application
- protocol - the protocol used by the endpoint
- name - the identifier used for this endpoint
"""
Session.verify_feature_set("advanced")
runtime_props = self._get_runtime_properties()
results = []
protocols = [protocol] if protocol is not None else ["http", "tcp"]
for protocol in protocols:
registry = self._collect_endpoint_suffixes(protocol, runtime_props)
for endpoint_name in sorted(registry.keys(), key=lambda name: (name != DEFAULT_ENDPOINT_NAME, str(name))):
port_value = registry.get(endpoint_name)
endpoint_value, browser_endpoint_value = None, None
runtime_key_suffix = None if endpoint_name == DEFAULT_ENDPOINT_NAME else endpoint_name
if protocol == "http":
endpoint_value = runtime_props.get(self._compose_runtime_key("endpoint", runtime_key_suffix))
browser_endpoint_value = runtime_props.get(
self._compose_runtime_key("browser_endpoint", runtime_key_suffix)
)
elif protocol == "tcp":
health_check = runtime_props.get(
self._compose_runtime_key(
self._external_endpoint_internal_port_map[protocol], runtime_key_suffix
)
)
if health_check:
address_value = runtime_props.get(
self._compose_runtime_key(self._external_endpoint_address_map[protocol], runtime_key_suffix)
)
external_port_value = runtime_props.get(
self._compose_runtime_key(self._external_endpoint_port_map[protocol], runtime_key_suffix)
)
if address_value and external_port_value:
endpoint_value = "{}:{}".format(address_value, external_port_value)
if endpoint_value or browser_endpoint_value:
results.append(
{
"endpoint": endpoint_value,
"browser_endpoint": browser_endpoint_value,
"port": port_value,
"protocol": protocol,
"name": None if endpoint_name == DEFAULT_ENDPOINT_NAME else endpoint_name,
}
)
return results
@classmethod
def create(
cls,
project_name: Optional[str] = None,
task_name: Optional[str] = None,
task_type: Optional[str] = None,
repo: Optional[str] = None,
branch: Optional[str] = None,
commit: Optional[str] = None,
script: Optional[str] = None,
working_directory: Optional[str] = None,
packages: Optional[Union[bool, Sequence[str]]] = None,
requirements_file: Optional[Union[str, Path]] = None,
docker: Optional[str] = None,
docker_args: Optional[str] = None,
docker_bash_setup_script: Optional[str] = None,
argparse_args: Optional[Sequence[Tuple[str, str]]] = None,
base_task_id: Optional[str] = None,
add_task_init_call: bool = True,
force_single_script_file: bool = False,
binary: Optional[str] = None,
module: Optional[str] = None,
detect_repository: bool = True
) -> TaskInstance:
"""
Manually create and populate a new Task (experiment) in the system.
If the code does not already contain a call to ``Task.init``, pass add_task_init_call=True,
and the code will be patched in remote execution (i.e. when executed by `clearml-agent`)
.. note::
This method **always** creates a new Task.
Use :meth:`Task.init` method to automatically create and populate task for the running process.
To reference an existing Task, call the :meth:`Task.get_task` method .
:param project_name: Set the project name for the task. Required if base_task_id is None.
:param task_name: Set the name of the remote task. Required if base_task_id is None.
:param task_type: Optional, The task type to be created. Supported values: 'training', 'testing', 'inference',
'data_processing', 'application', 'monitor', 'controller', 'optimizer', 'service', 'qc', 'custom'
:param repo: Remote URL for the repository to use, or path to local copy of the git repository.
Example: 'https://github.com/allegroai/clearml.git' or '~/project/repo'. If ``repo`` is specified, then
the ``script`` parameter must also be specified
:param branch: Select specific repository branch/tag (implies the latest commit from the branch)
:param commit: Select specific commit ID to use (default: latest commit,
or when used with local repository matching the local commit ID)
:param script: Specify the entry point script for the remote execution. When used in tandem with
remote git repository the script should be a relative path inside the repository,
for example: './source/train.py' . When used with local repository path it supports a
direct path to a file inside the local repository itself, for example: '~/project/source/train.py'
:param working_directory: Working directory to launch the script from. Default: repository root folder.
Relative to repo root or local folder.
:param packages: Manually specify a list of required packages. Example: ``["tqdm>=2.1", "scikit-learn"]``
or `True` to automatically create requirements
based on locally installed packages (repository must be local).
Pass an empty string to not install any packages (not even from the repository)
:param requirements_file: Specify requirements.txt file to install when setting the session.
If not provided, the requirements.txt from the repository will be used.
:param docker: Select the docker image to be executed in by the remote session
:param docker_args: Add docker arguments, pass a single string
:param docker_bash_setup_script: Add bash script to be executed
inside the docker before setting up the Task's environment
:param argparse_args: Arguments to pass to the remote execution, list of string pairs (argument, value)
Notice, only supported if the codebase itself uses argparse.ArgumentParser
:param base_task_id: Use a pre-existing task in the system, instead of a local repo/script.
Essentially clones an existing task and overrides arguments/requirements.
:param add_task_init_call: If True, a 'Task.init()' call is added to the script entry point in remote execution.
:param force_single_script_file: If True, do not auto-detect local repository
:param binary: Binary used to launch the entry point
:param module: If specified instead of executing `script`, a module named `module` is executed.
Implies script is empty. Module can contain multiple argument for execution,
for example: module="my.module arg1 arg2"
:param detect_repository: If True, detect the repository if no repository has been specified.
If False, don't detect repository under any circumstance. Ignored if `repo` is specified
:return: The newly created Task (experiment)
:rtype: Task
"""
if cls.is_offline():
raise UsageError("Creating task in offline mode. Use 'Task.init' instead.")
if not project_name and not base_task_id:
if not cls.__main_task:
raise ValueError(
"Please provide project_name, no global task context found "
"(Task.current_task hasn't been called)"
)
project_name = cls.__main_task.get_project_name()
from .backend_interface.task.populate import CreateAndPopulate
manual_populate = CreateAndPopulate(
project_name=project_name,
task_name=task_name,
task_type=task_type,
repo=repo,
branch=branch,
commit=commit,
script=script,
working_directory=working_directory,
packages=packages,
requirements_file=requirements_file,
docker=docker,
docker_args=docker_args,
docker_bash_setup_script=docker_bash_setup_script,
base_task_id=base_task_id,
add_task_init_call=add_task_init_call,
force_single_script_file=force_single_script_file,
raise_on_missing_entries=False,
module=module,
binary=binary,
detect_repository=detect_repository
)
task = manual_populate.create_task()
if task and argparse_args:
manual_populate.update_task_args(argparse_args)
task.reload()
return task
@classmethod
def get_by_name(cls, task_name: str) -> TaskInstance:
"""
.. note::
This method is deprecated, use :meth:`Task.get_task` instead.
Returns the most recent task with the given name from anywhere in the system as a Task object.
:param str task_name: The name of the task to search for.
:return: Task object of the most recent task with that name.
"""
warnings.warn(
"Warning: 'Task.get_by_name' is deprecated. Use 'Task.get_task' instead",
DeprecationWarning,
)
return cls.get_task(task_name=task_name)
@classmethod
def get_task(
cls,
task_id: Optional[str] = None,
project_name: Optional[str] = None,
task_name: Optional[str] = None,
tags: Optional[Sequence[str]] = None,
allow_archived: bool = True,
task_filter: Optional[dict] = None,
) -> TaskInstance:
"""
Get a Task by ID, or project name / task name combination.
For example:
The following code demonstrates calling ``Task.get_task`` to report a scalar to another Task. The output
of :meth:`.Logger.report_scalar` from testing is associated with the Task named ``training``. It allows
training and testing to run concurrently, because they initialized different Tasks (see :meth:`Task.init`
for information about initializing Tasks).
The training script:
.. code-block:: py
# initialize the training Task
task = Task.init('myProject', 'training')
# do some training
The testing script:
.. code-block:: py
# initialize the testing Task
task = Task.init('myProject', 'testing')
# get the training Task
train_task = Task.get_task(project_name='myProject', task_name='training')
# report metrics in the training Task
for x in range(10):
train_task.get_logger().report_scalar('title', 'series', value=x * 2, iteration=x)
:param str task_id: The ID (system UUID) of the experiment to get.
If specified, ``project_name`` and ``task_name`` are ignored.
:param str project_name: The project name of the Task to get.
:param str task_name: The name of the Task within ``project_name`` to get.
:param list tags: Filter based on the requested list of tags (strings). To exclude a tag add "-" prefix to the
tag. Example: ``["best", "-debug"]``.
The default behaviour is to join all tags with a logical "OR" operator.
To join all tags with a logical "AND" operator instead, use "__$all" as the first string, for example:
.. code-block:: py
["__$all", "best", "experiment", "ever"]
To join all tags with AND, but exclude a tag use "__$not" before the excluded tag, for example:
.. code-block:: py
["__$all", "best", "experiment", "ever", "__$not", "internal", "__$not", "test"]
The "OR" and "AND" operators apply to all tags that follow them until another operator is specified.
The NOT operator applies only to the immediately following tag.
For example:
.. code-block:: py
["__$all", "a", "b", "c", "__$or", "d", "__$not", "e", "__$and", "__$or", "f", "g"]
This example means ("a" AND "b" AND "c" AND ("d" OR NOT "e") AND ("f" OR "g")).
See https://clear.ml/docs/latest/docs/clearml_sdk/task_sdk/#tag-filters for more information.
:param bool allow_archived: Only applicable if *not* using specific ``task_id``,
If True (default), allow to return archived Tasks, if False filter out archived Tasks
:param bool task_filter: Only applicable if *not* using specific ``task_id``,
Pass additional query filters, on top of project/name. See details in Task.get_tasks.
:return: The Task specified by ID, or project name / experiment name combination.
:rtype: Task
"""
return cls.__get_task(
task_id=task_id,
project_name=project_name,
task_name=task_name,
tags=tags,
include_archived=allow_archived,
task_filter=task_filter,
)
@classmethod
def get_tasks(
cls,
task_ids: Optional[Sequence[str]] = None,
project_name: Optional[Union[Sequence[str], str]] = None,
task_name: Optional[str] = None,
tags: Optional[Sequence[str]] = None,
allow_archived: bool = True,
task_filter: Optional[Dict] = None,
) -> List[TaskInstance]:
"""
Get a list of Tasks objects matching the queries/filters:
- A list of specific Task IDs.
- Filter Tasks based on specific fields:
project name (including partial match), task name (including partial match), tags
Apply Additional advanced filtering with `task_filter`
.. note::
This function returns the most recent 500 tasks. If you wish to retrieve older tasks
use ``Task.query_tasks()``
:param list(str) task_ids: The IDs (system UUID) of experiments to get.
If ``task_ids`` specified, then ``project_name`` and ``task_name`` are ignored.
:param str project_name: The project name of the Tasks to get. To get the experiment
in all projects, use the default value of ``None``. (Optional)
Use a list of strings for multiple optional project names.
:param str task_name: The full name or partial name of the Tasks to match within the specified
``project_name`` (or all projects if ``project_name`` is ``None``).
This method supports regular expressions for name matching (if you wish to match special characters and
avoid any regex behaviour, use re.escape()). (Optional)
To match an exact task name (i.e. not partial matching),
add ^/$ at the beginning/end of the string, for example: "^exact_task_name_here$"
:param list tags: Filter based on the requested list of tags (strings). To exclude a tag add "-" prefix to the
tag. Example: ``["best", "-debug"]``.
The default behaviour is to join all tags with a logical "OR" operator.
To join all tags with a logical "AND" operator instead, use "__$all" as the first string, for example:
.. code-block:: py
["__$all", "best", "experiment", "ever"]
To join all tags with AND, but exclude a tag use "__$not" before the excluded tag, for example:
.. code-block:: py
["__$all", "best", "experiment", "ever", "__$not", "internal", "__$not", "test"]
The "OR" and "AND" operators apply to all tags that follow them until another operator is specified.
The NOT operator applies only to the immediately following tag.
For example:
.. code-block:: py
["__$all", "a", "b", "c", "__$or", "d", "__$not", "e", "__$and", "__$or", "f", "g"]
This example means ("a" AND "b" AND "c" AND ("d" OR NOT "e") AND ("f" OR "g")).
See https://clear.ml/docs/latest/docs/clearml_sdk/task_sdk/#tag-filters for more information.
:param bool allow_archived: If True (default), allow to return archived Tasks, if False filter out archived Tasks
:param dict task_filter: filter and order Tasks.
See :class:`.backend_api.service.v?.tasks.GetAllRequest` for details; the ? needs to be replaced by the appropriate version.
- ``parent`` - (str) filter by parent task-id matching
- ``search_text`` - (str) free text search (in task fields comment/name/id)
- ``status`` - List[str] List of valid statuses. Options are: "created", "queued", "in_progress", "stopped", "published", "publishing", "closed", "failed", "completed", "unknown"
- ``type`` - List[str] List of valid task types. Options are: 'training', 'testing', 'inference', 'data_processing', 'application', 'monitor', 'controller', 'optimizer', 'service', 'qc'. 'custom'
- ``user`` - List[str] Filter based on Task's user owner, provide list of valid user IDs.
- ``order_by`` - List[str] List of field names to order by. When ``search_text`` is used. Use '-' prefix to specify descending order. Optional, recommended when using page. Example: ``order_by=['-last_update']``
- ``_all_`` - dict(fields=[], pattern='') Match string `pattern` (regular expression) appearing in All `fields`. Example: dict(fields=['script.repository'], pattern='github.com/user')
- ``_any_`` - dict(fields=[], pattern='') Match string `pattern` (regular expression) appearing in any of the `fields`. Example: dict(fields=['comment', 'name'], pattern='my comment')
- Examples - ``{'status': ['stopped'], 'order_by': ["-last_update"]}`` , ``{'order_by'=['-last_update'], '_all_'=dict(fields=['script.repository'], pattern='github.com/user'))``
:return: The Tasks specified by the parameter combinations (see the parameters).
:rtype: List[Task]
"""
task_filter = task_filter or {}
if not allow_archived:
task_filter["system_tags"] = (task_filter.get("system_tags") or []) + ["-{}".format(cls.archived_tag)]
return cls.__get_tasks(
task_ids=task_ids, project_name=project_name, tags=tags, task_name=task_name, **task_filter
)
@classmethod
def query_tasks(
cls,
project_name: Optional[Union[Sequence[str], str]] = None,
task_name: Optional[str] = None,
tags: Optional[Sequence[str]] = None,
additional_return_fields: Optional[Sequence[str]] = None,
task_filter: Optional[Dict] = None,
) -> Union[List[str], List[Dict[str, str]]]:
"""
Get a list of Tasks ID matching the specific query/filter.
Notice, if `additional_return_fields` is specified, returns a list of
dictionaries with requested fields (dict per Task)
:param str project_name: The project name of the Tasks to get. To get the experiment
in all projects, use the default value of ``None``. (Optional)
Use a list of strings for multiple optional project names.
:param str task_name: The full name or partial name of the Tasks to match within the specified
``project_name`` (or all projects if ``project_name`` is ``None``).
This method supports regular expressions for name matching (if you wish to match special characters and
avoid any regex behaviour, use re.escape()). (Optional)
:param str project_name: project name (str) the task belongs to (use None for all projects)
:param str task_name: task name (str) within the selected project
Return any partial match of task_name, regular expressions matching is also supported.
If None is passed, returns all tasks within the project
:param list tags: Filter based on the requested list of tags (strings).
To exclude a tag add "-" prefix to the tag. Example: ``["best", "-debug"]``.
The default behaviour is to join all tags with a logical "OR" operator.
To join all tags with a logical "AND" operator instead, use "__$all" as the first string, for example:
.. code-block:: py
["__$all", "best", "experiment", "ever"]
To join all tags with AND, but exclude a tag use "__$not" before the excluded tag, for example:
.. code-block:: py
["__$all", "best", "experiment", "ever", "__$not", "internal", "__$not", "test"]
The "OR" and "AND" operators apply to all tags that follow them until another operator is specified.
The NOT operator applies only to the immediately following tag.
For example:
.. code-block:: py
["__$all", "a", "b", "c", "__$or", "d", "__$not", "e", "__$and", "__$or", "f", "g"]
This example means ("a" AND "b" AND "c" AND ("d" OR NOT "e") AND ("f" OR "g")).
See https://clear.ml/docs/latest/docs/clearml_sdk/task_sdk/#tag-filters for more information.
:param list additional_return_fields: Optional, if not provided return a list of Task IDs.
If provided return dict per Task with the additional requested fields.
Example: ``returned_fields=['last_updated', 'user', 'script.repository']`` will return a list of dict:
``[{'id': 'task_id', 'last_update': datetime.datetime(), 'user': 'user_id', 'script.repository': 'https://github.com/user/'}, ]``
:param dict task_filter: filter and order Tasks.
See :class:`.backend_api.service.v?.tasks.GetAllRequest` for details; the ? needs to be replaced by the appropriate version.
- ``parent`` - (str) filter by parent task-id matching
- ``search_text`` - (str) free text search (in task fields comment/name/id)
- ``status`` - List[str] List of valid statuses. Options are: "created", "queued", "in_progress", "stopped", "published", "publishing", "closed", "failed", "completed", "unknown"
- ``type`` - List[Union[str, TaskTypes]] List of valid task types. Options are: 'training', 'testing', 'inference', 'data_processing', 'application', 'monitor', 'controller', 'optimizer', 'service', 'qc'. 'custom'
- ``user`` - List[str] Filter based on Task's user owner, provide list of valid user IDs.
- ``order_by`` - List[str] List of field names to order by. When search_text is used. Use '-' prefix to specify descending order. Optional, recommended when using page. Example: ``order_by=['-last_update']``
- ``_all_`` - dict(fields=[], pattern='') Match string ``pattern`` (regular expression) appearing in All `fields`. ``dict(fields=['script.repository'], pattern='github.com/user')``
- ``_any_`` - dict(fields=[], pattern='') Match string `pattern` (regular expression) appearing in Any of the `fields`. `dict(fields=['comment', 'name'], pattern='my comment')`
- Examples: ``{'status': ['stopped'], 'order_by': ["-last_update"]}``, ``{'order_by'=['-last_update'], '_all_'=dict(fields=['script.repository'], pattern='github.com/user')}``
:return: The Tasks specified by the parameter combinations (see the parameters).
"""
task_filter = task_filter or {}
if tags:
task_filter["tags"] = (task_filter.get("tags") or []) + list(tags)
return_fields = {}
if additional_return_fields:
return_fields = set(list(additional_return_fields) + ["id"])
task_filter["only_fields"] = (task_filter.get("only_fields") or []) + list(return_fields)
if task_filter.get("type"):
task_filter["type"] = [str(task_type) for task_type in task_filter["type"]]
results = cls._query_tasks(project_name=project_name, task_name=task_name, **task_filter)
return (
[t.id for t in results]
if not additional_return_fields
else [
{
k: cls._get_data_property(prop_path=k, data=r, raise_on_error=False, log_on_error=False)
for k in return_fields
}
for r in results
]
)
@property
def output_uri(self) -> str:
"""
The storage / output url for this task. This is the default location for output models and other artifacts.
:return: The url string.
"""
return self.storage_uri
@property
def last_worker(self) -> str:
"""
ID of last worker that handled the task.
:return: The worker ID.
"""
return self._data.last_worker
@output_uri.setter
def output_uri(self, value: Union[str, bool]) -> None:
"""
Set the storage / output url for this task. This is the default location for output models and other artifacts.
:param str/bool value: The value to set for output URI. Can be either a bucket link, True for default server
or False. Check Task.init reference docs for more info (output_uri is a parameter).
"""
# check if this is boolean
if value is False:
value = None
elif value is True:
value = str(self.__default_output_uri or self._get_default_report_storage_uri())
# check if we have the correct packages / configuration
if value and value != self.storage_uri:
from .storage.helper import StorageHelper
helper = StorageHelper.get(value)
if not helper:
raise ValueError(
"Could not get access credentials for '{}' "
", check configuration file ~/clearml.conf".format(value)
)
helper.check_write_permissions(value)
self.storage_uri = value
@property
def artifacts(self) -> Dict[str, Artifact]:
"""
A read-only dictionary of Task artifacts (name, artifact).
:return: The artifacts.
"""
if not Session.check_min_api_version("2.3"):
return ReadOnlyDict()
artifacts_pairs = []
if self.data.execution and self.data.execution.artifacts:
artifacts_pairs = [(a.key, Artifact(a)) for a in self.data.execution.artifacts]
if self._artifacts_manager:
artifacts_pairs += list(self._artifacts_manager.registered_artifacts.items())
return ReadOnlyDict(artifacts_pairs)
@property
def models(self) -> Mapping[str, Sequence[Model]]:
"""
Read-only dictionary of the Task's loaded/stored models.
:return: A dictionary-like object with "input"/"output" keys and input/output properties, pointing to a
list-like object containing Model objects. Each list-like object also acts as a dictionary, mapping
model name to an appropriate model instance.
Get input/output models:
.. code-block:: py
task.models.input
task.models["input"]
task.models.output
task.models["output"]
Get the last output model:
.. code-block:: py
task.models.output[-1]
Get a model by name:
.. code-block:: py
task.models.output["model name"]
"""
return self.get_models()
@property
def logger(self) -> Logger:
"""
Get a Logger object for reporting, for this task context. You can view all Logger report output associated with
the Task for which this method is called, including metrics, plots, text, tables, and images, in the
**ClearML Web-App (UI)**.
:return: The Logger object for the current Task (experiment).
"""
return self.get_logger()
@classmethod
def clone(
cls,
source_task: Optional[Union["Task", str]] = None,
name: Optional[str] = None,
comment: Optional[str] = None,
parent: Optional[str] = None,
project: Optional[str] = None,
) -> TaskInstance:
"""
Create a duplicate (a clone) of a Task (experiment). The status of the cloned Task is ``Draft``
and modifiable.
Use this method to manage experiments and for autoML.
:param str source_task: The Task to clone. Specify a Task object or a Task ID. (Optional)
:param str name: The name of the new cloned Task. (Optional)
:param str comment: A comment / description for the new cloned Task. (Optional)
:param str parent: The ID of the parent Task of the new Task.
- If ``parent`` is not specified, then ``parent`` is set to ``source_task.parent``.
- If ``parent`` is not specified and ``source_task.parent`` is not available, then ``parent`` set to ``source_task``.
:param str project: The ID of the project in which to create the new Task.
If ``None``, the new task inherits the original Task's project. (Optional)
:return: The new cloned Task (experiment).
:rtype: Task
"""
assert isinstance(source_task, (six.string_types, Task))
if not Session.check_min_api_version("2.4"):
raise ValueError(
"ClearML-server does not support DevOps features, upgrade clearml-server to 0.12.0 or above"
)
task_id = source_task if isinstance(source_task, six.string_types) else source_task.id
if not parent:
if isinstance(source_task, six.string_types):
source_task = cls.get_task(task_id=source_task)
parent = source_task.id if not source_task.parent else source_task.parent
elif isinstance(parent, Task):
parent = parent.id
cloned_task_id = cls._clone_task(
cloned_task_id=task_id,
name=name,
comment=comment,
parent=parent,
project=project,
)
cloned_task = cls.get_task(task_id=cloned_task_id)
return cloned_task
@classmethod
def enqueue(
cls,
task: Union["Task", str],
queue_name: Optional[str] = None,
queue_id: Optional[str] = None,
force: bool = False,
) -> Any:
"""
Enqueue a Task for execution, by adding it to an execution queue.
.. note::
A worker daemon must be listening at the queue for the worker to fetch the Task and execute it,
see "ClearML Agent" in the ClearML Documentation.
:param Task/str task: The Task to enqueue. Specify a Task object or Task ID.
:param str queue_name: The name of the queue. If not specified, then ``queue_id`` must be specified.
:param str queue_id: The ID of the queue. If not specified, then ``queue_name`` must be specified.
:param bool force: If True, reset the Task if necessary before enqueuing it
:return: An enqueue JSON response.
.. code-block:: javascript
{
"queued": 1,
"updated": 1,
"fields": {
"status": "queued",
"status_reason": "",
"status_message": "",
"status_changed": "2020-02-24T15:05:35.426770+00:00",
"last_update": "2020-02-24T15:05:35.426770+00:00",
"execution.queue": "2bd96ab2d9e54b578cc2fb195e52c7cf"
}
}
- ``queued`` - The number of Tasks enqueued (an integer or ``null``).
- ``updated`` - The number of Tasks updated (an integer or ``null``).
- ``fields``
- ``status`` - The status of the experiment.
- ``status_reason`` - The reason for the last status change.
- ``status_message`` - Information about the status.
- ``status_changed`` - The last status change date and time (ISO 8601 format).
- ``last_update`` - The last Task update time, including Task creation, update, change, or events for this task (ISO 8601 format).
- ``execution.queue`` - The ID of the queue where the Task is enqueued. ``null`` indicates not enqueued.
"""
assert isinstance(task, (six.string_types, Task))
if not Session.check_min_api_version("2.4"):
raise ValueError(
"ClearML-server does not support DevOps features, upgrade clearml-server to 0.12.0 or above"
)
# make sure we have wither name ot id
mutually_exclusive(queue_name=queue_name, queue_id=queue_id)
task_id = task if isinstance(task, six.string_types) else task.id
session = cls._get_default_session()
if not queue_id:
queue_id = get_queue_id(session, queue_name)
if not queue_id:
raise ValueError('Could not find queue named "{}"'.format(queue_name))
req = tasks.EnqueueRequest(task=task_id, queue=queue_id)
exception = None
res = None
try:
res = cls._send(session=session, req=req)
ok = res.ok()
except Exception as e:
exception = e
ok = False
if not ok:
if not force:
if res:
raise ValueError(res.response)
raise exception
task = cls.get_task(task_id=task) if isinstance(task, str) else task
task.reset(set_started_on_success=False, force=True)
req = tasks.EnqueueRequest(task=task_id, queue=queue_id)
res = cls._send(session=session, req=req)
if not res.ok():
raise ValueError(res.response)
resp = res.response
return resp
@classmethod
def get_num_enqueued_tasks(cls, queue_name: Optional[str] = None, queue_id: Optional[str] = None) -> int:
"""
Get the number of tasks enqueued in a given queue.
:param queue_name: The name of the queue. If not specified, then ``queue_id`` must be specified
:param queue_id: The ID of the queue. If not specified, then ``queue_name`` must be specified
:return: The number of tasks enqueued in the given queue
"""
if not Session.check_min_api_server_version("2.20", raise_error=True):
raise ValueError("You version of clearml-server does not support the 'queues.get_num_entries' endpoint")
mutually_exclusive(queue_name=queue_name, queue_id=queue_id)
session = cls._get_default_session()
if not queue_id:
queue_id = get_queue_id(session, queue_name)
if not queue_id:
raise ValueError('Could not find queue named "{}"'.format(queue_name))
result = get_num_enqueued_tasks(session, queue_id)
if result is None:
raise ValueError("Could not query the number of enqueued tasks in queue with ID {}".format(queue_id))
return result
@classmethod
def dequeue(cls, task: Union["Task", str]) -> Any:
"""
Dequeue (remove) a Task from an execution queue.
:param Task/str task: The Task to dequeue. Specify a Task object or Task ID.
:return: A dequeue JSON response.
.. code-block:: javascript
{
"dequeued": 1,
"updated": 1,
"fields": {
"status": "created",
"status_reason": "",
"status_message": "",
"status_changed": "2020-02-24T16:43:43.057320+00:00",
"last_update": "2020-02-24T16:43:43.057320+00:00",
"execution.queue": null
}
}
- ``dequeued`` - The number of Tasks enqueued (an integer or ``null``).
- ``fields``
- ``status`` - The status of the experiment.
- ``status_reason`` - The reason for the last status change.
- ``status_message`` - Information about the status.
- ``status_changed`` - The last status change date and time in ISO 8601 format.
- ``last_update`` - The last time the Task was created, updated,
changed, or events for this task were reported.
- ``execution.queue`` - The ID of the queue where the Task is enqueued. ``null`` indicates not enqueued.
- ``updated`` - The number of Tasks updated (an integer or ``null``).
"""
assert isinstance(task, (six.string_types, Task))
if not Session.check_min_api_version("2.4"):
raise ValueError(
"ClearML-server does not support DevOps features, upgrade clearml-server to 0.12.0 or above"
)
task_id = task if isinstance(task, six.string_types) else task.id
session = cls._get_default_session()
req = tasks.DequeueRequest(task=task_id)
res = cls._send(session=session, req=req)
resp = res.response
return resp
def set_progress(self, progress: int) -> ():
"""
Sets Task's progress (0 - 100)
Progress is a field computed and reported by the user.
:param progress: numeric value (0 - 100)
"""
if not isinstance(progress, int) or progress < 0 or progress > 100:
self.log.warning("Can't set progress {} as it is not and int between 0 and 100".format(progress))
return
self._set_runtime_properties({"progress": str(progress)})
def get_progress(self) -> Optional[int]:
"""
Gets Task's progress (0 - 100)
:return: Task's progress as an int.
In case the progress doesn't exist, None will be returned
"""
progress = self._get_runtime_properties().get("progress")
if progress is None or not progress.isnumeric():
return None
return int(progress)
def add_tags(self, tags: Union[Sequence[str], str]) -> None:
"""
Add Tags to this task. Old tags are not deleted. When executing a Task (experiment) remotely,
this method has no effect.
:param tags: A list of tags which describe the Task to add.
"""
if isinstance(tags, six.string_types):
tags = tags.split(" ")
self.data.tags = list(
set(
itertools.chain(self.data.tags or [], tags)
)
)
self._edit(tags=self.data.tags)
def connect(
self,
mutable: Any,
name: Optional[str] = None,
ignore_remote_overrides: bool = False,
) -> Any:
"""
Connect an object to a Task object. This connects an experiment component (part of an experiment) to the
experiment. For example, an experiment component can be a valid object containing some hyperparameters, or a :class:`Model`.
When running remotely, the value of the connected object is overridden by the corresponding value found
under the experiment's UI/backend (unless `ignore_remote_overrides` is True).
:param object mutable: The experiment component to connect. The object must be one of the following types:
- argparse - An argparse object for parameters.
- dict - A dictionary for parameters. Note: only keys of type `str` are supported.
- TaskParameters - A TaskParameters object.
- :class:`Model` - A model object for initial model warmup, or for model update/snapshot uploading. In practice the model should be either :class:`InputModel` or :class:`OutputModel`.
- type - A Class type, storing all class properties (excluding '_' prefixed properties).
- object - A class instance, storing all instance properties (excluding '_' prefixed properties).
:param str name: A section name associated with the connected object, if 'name' is None defaults to 'General'
Currently, `name` is only supported for `dict` and `TaskParameter` objects, and should be omitted for the other supported types. (Optional)
For example, by setting `name='General'` the connected dictionary will be under the General section in the hyperparameters section.
While by setting `name='Train'` the connected dictionary will be under the Train section in the hyperparameters section.
:param ignore_remote_overrides: If True, ignore UI/backend overrides when running remotely.
Default is False, meaning that any changes made in the UI/backend will be applied in remote execution.
:return: It will return the same object that was passed as the `mutable` argument to the method, except if the type of the object is dict.
For dicts the :meth:`Task.connect` will return the dict decorated as a `ProxyDictPostWrite`.
This is done to allow propagating the updates from the connected object.
:raise: Raises an exception if passed an unsupported object.
"""
# input model connect and task parameters will handle this instead
if not isinstance(mutable, (InputModel, TaskParameters)):
ignore_remote_overrides = self._handle_ignore_remote_overrides(
(name or "General") + "/_ignore_remote_overrides_",
ignore_remote_overrides,
)
# dispatching by match order
dispatch = (
(OutputModel, self._connect_output_model),
(InputModel, self._connect_input_model),
(ArgumentParser, self._connect_argparse),
(dict, self._connect_dictionary),
(TaskParameters, self._connect_task_parameters),
(type, self._connect_object),
(object, self._connect_object),
)
multi_config_support = Session.check_min_api_version("2.9")
if multi_config_support and not name and not isinstance(mutable, (OutputModel, InputModel)):
name = self._default_configuration_section_name
if not multi_config_support and name and name != self._default_configuration_section_name:
raise ValueError(
"Multiple configurations is not supported with the current 'clearml-server', "
"please upgrade to the latest version"
)
for mutable_type, method in dispatch:
if isinstance(mutable, mutable_type):
return method(mutable, name=name, ignore_remote_overrides=ignore_remote_overrides)
raise Exception("Unsupported mutable type %s: no connect function found" % type(mutable).__name__)
def set_packages(self, packages: Union[str, Path, Sequence[str]]) -> ():
"""
Manually specify a list of required packages or a local requirements.txt file. Note that this will
overwrite all existing packages.
When running remotely this call is ignored
:param packages: The list of packages or the path to the requirements.txt file.
Example: ``["tqdm>=2.1", "scikit-learn"]`` or ``"./requirements.txt"`` or ``""``
Use an empty string (packages="") to clear the requirements section (remote execution will use
requirements.txt from the git repository if the file exists)
"""
if running_remotely() or packages is None:
return
self._wait_for_repo_detection(timeout=300.0)
if packages and isinstance(packages, (str, Path)) and Path(packages).is_file():
with open(Path(packages).as_posix(), "rt") as f:
# noinspection PyProtectedMember
self._update_requirements([line.strip() for line in f.readlines()])
return
# noinspection PyProtectedMember
self._update_requirements(packages or "")
def set_repo(
self,
repo: Optional[str] = None,
branch: Optional[str] = None,
commit: Optional[str] = None,
) -> ():
"""
Specify a repository to attach to the function.
Allow users to execute the task inside the specified repository, enabling them to load modules/script
from the repository. Notice the execution work directory will be the repository root folder.
Supports both git repo url link, and local repository path (automatically converted into the remote
git/commit as is currently checkout).
Example remote url: "https://github.com/user/repo.git".
Example local repo copy: "./repo" - will automatically store the remote
repo url and commit ID based on the locally cloned copy.
When executing remotely, this call will not override the repository data (it is ignored)
:param repo: Optional, remote URL for the repository to use, OR path to local copy of the git repository.
Use an empty string to clear the repo.
Example: "https://github.com/allegroai/clearml.git" or "~/project/repo" or ""
:param branch: Optional, specify the remote repository branch (Ignored, if local repo path is used).
Use an empty string to clear the branch.
:param commit: Optional, specify the repository commit ID (Ignored, if local repo path is used).
Use an empty string to clear the commit.
"""
if running_remotely():
return
self._wait_for_repo_detection(timeout=300.0)
with self._edit_lock:
self.reload()
if repo is not None:
# we cannot have None on the value itself
self.data.script.repository = repo or ""
if branch is not None:
# we cannot have None on the value itself
self.data.script.branch = branch or ""
if commit is not None:
# we cannot have None on the value itself
self.data.script.version_num = commit or ""
self._edit(script=self.data.script)
def get_requirements(self) -> RequirementsDict:
"""
Get the task's requirements
:return: A `RequirementsDict` object that holds the `pip`, `conda`, `orig_pip` requirements.
"""
if not running_remotely() and self.is_main_task():
self._wait_for_repo_detection(timeout=300.0)
requirements_dict = RequirementsDict()
requirements_dict.update(self.data.script.requirements)
return requirements_dict
def connect_configuration(
self,
configuration: Union[Mapping, list, Path, str],
name: Optional[str] = None,
description: Optional[str] = None,
ignore_remote_overrides: bool = False,
) -> Union[dict, Path, str]:
"""
Connect a configuration dictionary or configuration file (pathlib.Path / str) to a Task object.
This method should be called before reading the configuration file.
For example, a local file:
.. code-block:: py
config_file = task.connect_configuration(config_file)
my_params = json.load(open(config_file,'rt'))
A parameter dictionary/list:
.. code-block:: py
my_params = task.connect_configuration(my_params)
When running remotely, the value of the connected configuration is overridden by the corresponding value found
under the experiment's UI/backend (unless `ignore_remote_overrides` is True).
:param configuration: The configuration. This is usually the configuration used in the model training process.
Specify one of the following:
- A dictionary/list - A dictionary containing the configuration. ClearML stores the configuration in
the **ClearML Server** (backend), in a HOCON format (JSON-like format) which is editable.
- A ``pathlib2.Path`` string - A path to the configuration file. ClearML stores the content of the file.
A local path must be relative path. When executing a Task remotely in a worker, the contents brought
from the **ClearML Server** (backend) overwrites the contents of the file.
:param str name: Configuration section name. default: 'General'
Allowing users to store multiple configuration dicts/files
:param str description: Configuration section description (text). default: None
:param bool ignore_remote_overrides: If True, ignore UI/backend overrides when running remotely.
Default is False, meaning that any changes made in the UI/backend will be applied in remote execution.
:return: If a dictionary is specified, then a dictionary is returned. If pathlib2.Path / string is
specified, then a path to a local configuration file is returned. Configuration object.
"""
ignore_remote_overrides = self._handle_ignore_remote_overrides(
(name or "General") + "/_ignore_remote_overrides_config_",
ignore_remote_overrides,
)
pathlib_Path = None # noqa
cast_Path = Path
if not isinstance(configuration, (dict, list, Path, six.string_types)):
try:
from pathlib import Path as pathlib_Path # noqa
except ImportError:
pass
if not pathlib_Path or not isinstance(configuration, pathlib_Path):
raise ValueError(
"connect_configuration supports `dict`, `str` and 'Path' types, "
"{} is not supported".format(type(configuration))
)
if pathlib_Path and isinstance(configuration, pathlib_Path):
cast_Path = pathlib_Path
multi_config_support = Session.check_min_api_version("2.9")
if multi_config_support and not name:
name = self._default_configuration_section_name
if not multi_config_support and name and name != self._default_configuration_section_name:
raise ValueError(
"Multiple configurations is not supported with the current 'clearml-server', "
"please upgrade to the latest version"
)
# parameter dictionary
if isinstance(
configuration,
(
dict,
list,
),
):
def _update_config_dict(task, config_dict):
if multi_config_support:
# noinspection PyProtectedMember
task._set_configuration(
name=name,
description=description,
config_type="dictionary",
config_dict=config_dict,
)
else:
# noinspection PyProtectedMember
task._set_model_config(config_dict=config_dict)
def get_dev_config(configuration_: Union[dict, list, Path, str]) -> Union[dict, ProxyDictPostWrite]:
if multi_config_support:
self._set_configuration(
name=name,
description=description,
config_type="dictionary",
config_dict=configuration_,
)
else:
self._set_model_config(config_dict=configuration)
if isinstance(configuration_, dict):
configuration_ = ProxyDictPostWrite(self, _update_config_dict, configuration_)
return configuration_
if (
not running_remotely()
or not (self.is_main_task() or self._is_remote_main_task())
or ignore_remote_overrides
):
configuration = get_dev_config(configuration)
else:
# noinspection PyBroadException
try:
remote_configuration = (
self._get_configuration_dict(name=name)
if multi_config_support
else self._get_model_config_dict()
)
except Exception:
remote_configuration = None
if remote_configuration is None:
LoggerRoot.get_base_logger().warning(
"Could not retrieve remote configuration named '{}'\n"
"Using default configuration: {}".format(name, str(configuration))
)
# update back configuration section
if multi_config_support:
self._set_configuration(
name=name,
description=description,
config_type="dictionary",
config_dict=configuration,
)
return configuration
if not remote_configuration:
configuration = get_dev_config(configuration)
elif isinstance(configuration, dict):
configuration.clear()
configuration.update(remote_configuration)
configuration = ProxyDictPreWrite(False, False, **configuration)
elif isinstance(configuration, list):
configuration.clear()
configuration.extend(remote_configuration)
return configuration
# it is a path to a local file
if (
not running_remotely()
or not (self.is_main_task() or self._is_remote_main_task())
or ignore_remote_overrides
):
# check if not absolute path
configuration_path = cast_Path(configuration)
if not configuration_path.is_file():
ValueError("Configuration file does not exist")
try:
with open(configuration_path.as_posix(), "rt") as f:
configuration_text = f.read()
except Exception:
raise ValueError(
"Could not connect configuration file {}, file could not be read".format(
configuration_path.as_posix()
)
)
if multi_config_support:
self._set_configuration(
name=name,
description=description,
config_type=(
configuration_path.suffixes[-1].lstrip(".")
if configuration_path.suffixes and configuration_path.suffixes[-1]
else "file"
),
config_text=configuration_text,
)
else:
self._set_model_config(config_text=configuration_text)
return configuration
else:
configuration_text = (
self._get_configuration_text(name=name) if multi_config_support else self._get_model_config_text()
)
if configuration_text is None:
LoggerRoot.get_base_logger().warning(
"Could not retrieve remote configuration named '{}'\n"
"Using default configuration: {}".format(name, str(configuration))
)
# update back configuration section
if multi_config_support:
configuration_path = cast_Path(configuration)
if configuration_path.is_file():
with open(configuration_path.as_posix(), "rt") as f:
configuration_text = f.read()
self._set_configuration(
name=name,
description=description,
config_type=(
configuration_path.suffixes[-1].lstrip(".")
if configuration_path.suffixes and configuration_path.suffixes[-1]
else "file"
),
config_text=configuration_text,
)
return configuration
configuration_path = cast_Path(configuration)
fd, local_filename = mkstemp(
prefix="clearml_task_config_",
suffix=(configuration_path.suffixes[-1] if configuration_path.suffixes else ".txt"),
)
with open(fd, "w") as f:
f.write(configuration_text)
return cast_Path(local_filename) if isinstance(configuration, cast_Path) else local_filename
def connect_label_enumeration(
self, enumeration: Dict[str, int], ignore_remote_overrides: bool = False
) -> Dict[str, int]:
"""
Connect a label enumeration dictionary to a Task (experiment) object.
Later, when creating an output model, the model will include the label enumeration dictionary.
:param dict enumeration: A label enumeration dictionary of string (label) to integer (value) pairs.
For example:
.. code-block:: javascript
{
"background": 0,
"person": 1
}
:param ignore_remote_overrides: If True, ignore UI/backend overrides when running remotely.
Default is False, meaning that any changes made in the UI/backend will be applied in remote execution.
:return: The label enumeration dictionary (JSON).
"""
ignore_remote_overrides = self._handle_ignore_remote_overrides(
"General/_ignore_remote_overrides_label_enumeration_",
ignore_remote_overrides,
)
if not isinstance(enumeration, dict):
raise ValueError(
"connect_label_enumeration supports only `dict` type, {} is not supported".format(type(enumeration))
)
if (
not running_remotely()
or not (self.is_main_task() or self._is_remote_main_task())
or ignore_remote_overrides
):
self.set_model_label_enumeration(enumeration)
else:
# pop everything
enumeration.clear()
enumeration.update(self.get_labels_enumeration())
return enumeration
def get_logger(self) -> Logger:
"""
Get a Logger object for reporting, for this task context. You can view all Logger report output associated with
the Task for which this method is called, including metrics, plots, text, tables, and images, in the
**ClearML Web-App (UI)**.
:return: The Logger for the Task (experiment).
"""
return self._get_logger(auto_connect_streams=self._log_to_backend)
def launch_multi_node(
self,
total_num_nodes: int,
port: Optional[int] = 29500,
queue: Optional[str] = None,
wait: bool = False,
addr: Optional[str] = None,
devices: Optional[Union[int, Sequence[int]]] = None,
hide_children=False, # bool
):
"""
Enqueue multiple clones of the current task to a queue, allowing the task
to be ran by multiple workers in parallel. Each task running this way is called a node.
Each node has a rank The node that initialized the execution of the other nodes
is called the `master node` and it has a rank equal to 0.
A dictionary named `multi_node_instance` will be connected to the tasks.
One can use this dictionary to modify the behaviour of this function when running remotely.
The contents of this dictionary correspond to the parameters of this function, and they are:
- `total_num_nodes` - the total number of nodes, including the master node
- `queue` - the queue to enqueue the nodes to
The following environment variables, will be set:
- `MASTER_ADDR` - the address of the machine that the master node is running on
- `MASTER_PORT` - the open port of the machine that the master node is running on
- `WORLD_SIZE` - the total number of nodes, including the master
- `RANK` - the rank of the current node (master has rank 0)
One may use this function in conjuction with PyTorch's distributed communication package.
Note that `Task.launch_multi_node` should be called before `torch.distributed.init_process_group`.
For example:
.. code-block:: py
from clearml import Task
import torch
import torch.distributed as dist
def run(rank, size):
print('World size is ', size)
tensor = torch.zeros(1)
if rank == 0:
for i in range(1, size):
tensor += 1
dist.send(tensor=tensor, dst=i)
print('Sending from rank ', rank, ' to rank ', i, ' data: ', tensor[0])
else:
dist.recv(tensor=tensor, src=0)
print('Rank ', rank, ' received data: ', tensor[0])
if __name__ == '__main__':
task = Task.init('some_name', 'some_name')
task.execute_remotely(queue_name='queue')
config = task.launch_multi_node(4)
dist.init_process_group('gloo')
run(config.get('node_rank'), config.get('total_num_nodes'))
When using the ClearML cloud autoscaler apps, one needs to make sure the nodes can reach eachother.
The machines need to be in the same security group, the `MASTER_PORT` needs to be exposed and the
`MASTER_ADDR` needs to be the right private ip of the instance the master is running on.
For example, to achieve this, one can set the following Docker arguments in the `Additional ClearML Configuration` section:
.. code-block:: py
agent.extra_docker_arguments=["--ipc=host", "--network=host", "-p", "29500:29500", "--env", "CLEARML_MULTI_NODE_MASTER_DEF_ADDR=`hostname -I | awk '{print $1}'`"]`
:param total_num_nodes: The total number of nodes to be enqueued, including the master node,
which should already be enqueued when running remotely
:param port: Port opened by the master node. If the environment variable ``CLEARML_MULTI_NODE_MASTER_DEF_PORT``
is set, the value of this parameter will be set to the one defined in ``CLEARML_MULTI_NODE_MASTER_DEF_PORT``.
If ``CLEARML_MULTI_NODE_MASTER_DEF_PORT`` doesn't exist, but ``MASTER_PORT`` does, then the value of this
parameter will be set to the one defined in ``MASTER_PORT``. If neither environment variables exist,
the value passed to the parameter will be used
:param queue: The queue to enqueue the nodes to. Can be different from the queue the master
node is enqueued to. If None, the nodes will be enqueued to the same queue as the master node
:param wait: If True, the master node will wait for the other nodes to start
:param addr: The address of the master node's worker. If the environment variable
``CLEARML_MULTI_NODE_MASTER_DEF_ADDR`` is set, the value of this parameter will be set to
the one defined in ``CLEARML_MULTI_NODE_MASTER_DEF_ADDR``.
If ``CLEARML_MULTI_NODE_MASTER_DEF_ADDR`` doesn't exist, but ``MASTER_ADDR`` does, then the value of this
parameter will be set to the one defined in ``MASTER_ADDR``. If neither environment variables exist,
the value passed to the parameter will be used. If this value is None (default), the private IP of
the machine the master node is running on will be used.
:param devices: The devices to use. This can be a positive number indicating the number of devices to use,
a sequence of indices or the value ``-1`` to indicate all available devices should be used.
:param hide_children: If True, the children tasks will be hidden. Otherwise, they will be visible in the UI
:return: A dictionary containing relevant information regarding the multi node run. This dictionary has the following entries:
- `master_addr` - the address of the machine that the master node is running on
- `master_port` - the open port of the machine that the master node is running on
- `total_num_nodes` - the total number of nodes, including the master
- `queue` - the queue the nodes are enqueued to, excluding the master
- `node_rank` - the rank of the current node (master has rank 0)
- `wait` - if True, the master node will wait for the other nodes to start
"""
def set_launch_multi_node_runtime_props(task: Task, conf: Dict[str, Any]) -> None:
# noinspection PyProtectedMember
task._set_runtime_properties(
{"{}/{}".format(self._launch_multi_node_section, k): v for k, v in conf.items()}
)
if total_num_nodes < 1:
raise UsageError("total_num_nodes needs to be at least 1")
if running_remotely() and not (self.data.execution and self.data.execution.queue) and not queue:
raise UsageError("Master task is not enqueued to any queue and the queue parameter is None")
master_conf = {
"master_addr": os.environ.get(
"CLEARML_MULTI_NODE_MASTER_DEF_ADDR",
os.environ.get("MASTER_ADDR", addr or get_private_ip()),
),
"master_port": int(
os.environ.get(
"CLEARML_MULTI_NODE_MASTER_DEF_PORT",
os.environ.get("MASTER_PORT", port),
)
),
"node_rank": 0,
"wait": wait,
"devices": devices,
}
editable_conf = {"total_num_nodes": total_num_nodes, "queue": queue}
editable_conf = self.connect(editable_conf, name=self._launch_multi_node_section)
if not running_remotely():
return master_conf
master_conf.update(editable_conf)
runtime_properties = self._get_runtime_properties()
remote_node_rank = runtime_properties.get("{}/node_rank".format(self._launch_multi_node_section))
current_conf = master_conf
if remote_node_rank:
# self is a child node, build the conf from the runtime proprerties
current_conf = {
entry: runtime_properties.get("{}/{}".format(self._launch_multi_node_section, entry))
for entry in master_conf.keys()
}
elif os.environ.get("CLEARML_MULTI_NODE_MASTER") is None:
nodes_to_wait = []
# self is the master node, enqueue the other nodes
set_launch_multi_node_runtime_props(self, master_conf)
for node_rank in range(1, master_conf.get("total_num_nodes", total_num_nodes)):
node = self.clone(source_task=self, parent=self.id)
node_conf = copy.deepcopy(master_conf)
node_conf["node_rank"] = node_rank
set_launch_multi_node_runtime_props(node, node_conf)
node.set_system_tags(
node.get_system_tags()
+ [self._launch_multi_node_instance_tag]
+ ([self.__hidden_tag] if hide_children else [])
)
if master_conf.get("queue"):
Task.enqueue(node, queue_name=master_conf["queue"])
else:
Task.enqueue(node, queue_id=self.data.execution.queue)
if master_conf.get("wait"):
nodes_to_wait.append(node)
for node_to_wait, rank in zip(
nodes_to_wait,
range(1, master_conf.get("total_num_nodes", total_num_nodes)),
):
self.log.info("Waiting for node with task ID {} and rank {}".format(node_to_wait.id, rank))
node_to_wait.wait_for_status(
status=(
Task.TaskStatusEnum.completed,
Task.TaskStatusEnum.stopped,
Task.TaskStatusEnum.closed,
Task.TaskStatusEnum.failed,
Task.TaskStatusEnum.in_progress,
),
check_interval_sec=10,
)
self.log.info("Node with task ID {} and rank {} detected".format(node_to_wait.id, rank))
os.environ["CLEARML_MULTI_NODE_MASTER"] = "1"
num_devices = 1
if devices is not None:
try:
num_devices = int(devices)
except TypeError:
try:
num_devices = len(devices)
except Exception as ex:
raise ValueError("Failed parsing number of devices: {}".format(ex))
except ValueError as ex:
raise ValueError("Failed parsing number of devices: {}".format(ex))
if num_devices < 0:
try:
import torch
num_devices = torch.cuda.device_count()
except ImportError:
raise ImportError(
"Could not import `torch` while finding the number of devices. "
"Please install it or set `devices` to a value different than -1"
)
os.environ["MASTER_ADDR"] = current_conf.get("master_addr", "")
os.environ["MASTER_PORT"] = str(current_conf.get("master_port", ""))
os.environ["RANK"] = str(
current_conf.get("node_rank", 0) * num_devices + int(os.environ.get("LOCAL_RANK", "0"))
)
os.environ["NODE_RANK"] = str(current_conf.get("node_rank", ""))
os.environ["WORLD_SIZE"] = str(current_conf.get("total_num_nodes", total_num_nodes) * num_devices)
return current_conf
def mark_started(self, force: bool = False) -> ():
"""
Manually mark a Task as started (happens automatically)
:param bool force: If True, the task status will be changed to `started` regardless of the current Task state.
"""
# UI won't let us see metrics if we're not started
self.started(force=force)
self.reload()
def mark_stopped(self, force: bool = False, status_message: Optional[str] = None) -> ():
"""
Manually mark a Task as stopped (also used in :meth:`_at_exit`)
:param bool force: If True, the task status will be changed to `stopped` regardless of the current Task state.
:param str status_message: Optional, add status change message to the stop request.
This message will be stored as status_message on the Task's info panel
"""
# flush any outstanding logs
self.flush(wait_for_uploads=True)
# mark task as stopped
self.stopped(force=force, status_message=str(status_message) if status_message else None)
def mark_stop_request(self, force: bool = False, status_message: Optional[str] = None) -> ():
"""
Request a task to stop. this will not change the task status
but mark a request for an agent or SDK to actually stop the Task.
This will trigger the Task's abort callback, and at the end will
change the task status to stopped and kill the Task's processes
Notice: calling this on your own Task, will cause
the watchdog to call the on_abort callback and kill the process
:param bool force: If not True, call fails if the task status is not 'in_progress'
:param str status_message: Optional, add status change message to the stop request.
This message will be stored as status_message on the Task's info panel
"""
# flush any outstanding logs
self.flush(wait_for_uploads=True)
# request task stop
return self.stop_request(self, force=force, status_message=status_message)
def flush(self, wait_for_uploads: bool = False) -> bool:
"""
Flush any outstanding reports or console logs.
:param bool wait_for_uploads: Wait for all outstanding uploads to complete
- ``True`` - Wait
- ``False`` - Do not wait (default)
"""
# make sure model upload is done
if BackendModel.get_num_results() > 0 and wait_for_uploads:
BackendModel.wait_for_results()
# flush any outstanding logs
if self._logger:
# noinspection PyProtectedMember
self._logger._flush_stdout_handler()
if self.__reporter:
self.__reporter.flush()
if wait_for_uploads:
self.__reporter.wait_for_events()
LoggerRoot.flush()
return True
def reset(self, set_started_on_success: bool = False, force: bool = False) -> None:
"""
Reset a Task. ClearML reloads a Task after a successful reset.
When a worker executes a Task remotely, the Task does not reset unless
the ``force`` parameter is set to ``True`` (this avoids accidentally clearing logs and metrics).
:param bool set_started_on_success: If successful, automatically set the Task to `started`
- ``True`` - If successful, set to started.
- ``False`` - If successful, do not set to started. (default)
:param bool force: Force a Task reset, even when executing the Task (experiment) remotely in a worker
- ``True`` - Force
- ``False`` - Do not force (default)
"""
if not running_remotely() or not self.is_main_task() or force:
super(Task, self).reset(set_started_on_success=set_started_on_success, force=force)
def close(self) -> None:
"""
Closes the current Task and changes its status to "Completed".
Enables you to manually shut down the task from the process which opened the task.
This method does not terminate the (current) Python process, in contrast to :meth:`Task.mark_completed`.
After having :meth:`Task.close` -d a task, the respective object cannot be used anymore and
methods like :meth:`Task.connect` or :meth:`Task.connect_configuration` will throw a `ValueError`.
In order to obtain an object representing the task again, use methods like :meth:`Task.get_task`.
.. warning::
Only call :meth:`Task.close` if you are certain the Task is not needed.
"""
if self._at_exit_called:
return
# store is main before we call at_exit, because will will Null it
is_main = self.is_main_task()
is_sub_process = self.__is_subprocess()
# wait for repository detection (5 minutes should be reasonable time to detect all packages)
if self._logger and not self.__is_subprocess():
self._wait_for_repo_detection(timeout=300.0)
self.__shutdown()
# unregister atexit callbacks and signal hooks, if we are the main task
if is_main:
self.__register_at_exit(None)
self._remove_signal_hooks()
self._remove_exception_hooks()
if not is_sub_process:
# make sure we enable multiple Task.init callas with reporting sub-processes
BackgroundMonitor.clear_main_process(self)
# noinspection PyProtectedMember
Logger._remove_std_logger()
# unbind everything
PatchHydra.update_current_task(None)
PatchedJoblib.update_current_task(None)
PatchedMatplotlib.update_current_task(None)
PatchAbsl.update_current_task(None)
TensorflowBinding.update_current_task(None)
PatchPyTorchModelIO.update_current_task(None)
PatchMegEngineModelIO.update_current_task(None)
PatchXGBoostModelIO.update_current_task(None)
PatchCatBoostModelIO.update_current_task(None)
PatchFastai.update_current_task(None)
PatchLIGHTgbmModelIO.update_current_task(None)
EnvironmentBind.update_current_task(None)
PatchJsonArgParse.update_current_task(None)
PatchOsFork.patch_fork(None)
def delete(
self,
delete_artifacts_and_models: bool = True,
skip_models_used_by_other_tasks: bool = True,
raise_on_error: bool = False,
callback: Callable[[str, str], bool] = None,
) -> bool:
"""
Delete the task as well as its output models and artifacts.
Models and artifacts are deleted from their storage locations, each using its URI.
Note: in order to delete models and artifacts using their URI, make sure the proper storage credentials are
configured in your configuration file (e.g. if an artifact is stored in S3, make sure sdk.aws.s3.credentials
are properly configured and that you have delete permission in the related buckets).
:param delete_artifacts_and_models: If True, artifacts and models would also be deleted (default True).
If callback is provided, this argument is ignored.
:param skip_models_used_by_other_tasks: If True, models used by other tasks would not be deleted (default True)
:param raise_on_error: If True, an exception will be raised when encountering an error.
If False an error would be printed and no exception will be raised.
:param callback: An optional callback accepting a uri type (string) and a uri (string) that will be called
for each artifact and model. If provided, the delete_artifacts_and_models is ignored.
Return True to indicate the artifact/model should be deleted or False otherwise.
:return: True if the task was deleted successfully.
"""
if not running_remotely() or not self.is_main_task():
return super(Task, self)._delete(
delete_artifacts_and_models=delete_artifacts_and_models,
skip_models_used_by_other_tasks=skip_models_used_by_other_tasks,
raise_on_error=raise_on_error,
callback=callback,
)
return False
def register_artifact(
self,
name: str,
artifact: "pandas.DataFrame",
metadata: Dict = None,
uniqueness_columns: Union[bool, Sequence[str]] = True,
) -> None:
"""
Register (add) an artifact for the current Task. Registered artifacts are dynamically synchronized with the
**ClearML Server** (backend). If a registered artifact is updated, the update is stored in the
**ClearML Server** (backend). Registered artifacts are primarily used for Data Auditing.
The currently supported registered artifact object type is a pandas.DataFrame.
See also :meth:`Task.unregister_artifact` and :meth:`Task.get_registered_artifacts`.
.. note::
ClearML also supports uploaded artifacts which are one-time uploads of static artifacts that are not
dynamically synchronized with the **ClearML Server** (backend). These static artifacts include
additional object types. For more information, see :meth:`Task.upload_artifact`.
:param str name: The name of the artifact.
.. warning::
If an artifact with the same name was previously registered, it is overwritten.
:param object artifact: The artifact object.
:param dict metadata: A dictionary of key-value pairs for any metadata. This dictionary appears with the
experiment in the **ClearML Web-App (UI)**, **ARTIFACTS** tab.
:param uniqueness_columns: A Sequence of columns for artifact uniqueness comparison criteria, or the default
value of ``True``. If ``True``, the artifact uniqueness comparison criteria is all the columns,
which is the same as ``artifact.columns``.
"""
if not isinstance(uniqueness_columns, CollectionsSequence) and uniqueness_columns is not True:
raise ValueError("uniqueness_columns should be a List (sequence) or True")
if isinstance(uniqueness_columns, str):
uniqueness_columns = [uniqueness_columns]
self._artifacts_manager.register_artifact(
name=name,
artifact=artifact,
metadata=metadata,
uniqueness_columns=uniqueness_columns,
)
def unregister_artifact(self, name: str) -> None:
"""
Unregister (remove) a registered artifact. This removes the artifact from the watch list that ClearML uses
to synchronize artifacts with the **ClearML Server** (backend).
.. important::
- Calling this method does not remove the artifact from a Task. It only stops ClearML from
monitoring the artifact.
- When this method is called, ClearML immediately takes the last snapshot of the artifact.
"""
self._artifacts_manager.unregister_artifact(name=name)
def get_registered_artifacts(self) -> Dict[str, Artifact]:
"""
Get a dictionary containing the Task's registered (dynamically synchronized) artifacts (name, artifact object).
.. note::
After calling ``get_registered_artifacts``, you can still modify the registered artifacts.
:return: The registered (dynamically synchronized) artifacts.
"""
return self._artifacts_manager.registered_artifacts
def upload_artifact(
self,
name: str,
artifact_object: Union[str, Mapping, "pandas.DataFrame", numpy.ndarray, "Image.Image", Any],
metadata: Optional[Mapping] = None,
delete_after_upload: bool = False,
auto_pickle: Optional[bool] = None,
preview: Any = None,
wait_on_upload: bool = False,
extension_name: Optional[str] = None,
serialization_function: Optional[Callable[[Any], Union[bytes, bytearray]]] = None,
retries: int = 0,
sort_keys: bool = True,
) -> bool:
"""
Upload (add) a static artifact to a Task object. The artifact is uploaded in the background.
The currently supported upload (static) artifact types include:
- string / pathlib2.Path - A path to artifact file. If a wildcard or a folder is specified, then ClearML
creates and uploads a ZIP file.
- dict - ClearML stores a dictionary as ``.json`` (or see ``extension_name``) file and uploads it.
- pandas.DataFrame - ClearML stores a pandas.DataFrame as ``.csv.gz`` (compressed CSV)
(or see ``extension_name``) file and uploads it.
- numpy.ndarray - ClearML stores a numpy.ndarray as ``.npz`` (or see ``extension_name``) file and uploads it.
- PIL.Image - ClearML stores a PIL.Image as ``.png`` (or see ``extension_name``) file and uploads it.
- Any - If called with auto_pickle=True, the object will be pickled and uploaded.
:param name: The artifact name.
.. warning::
If an artifact with the same name was previously uploaded, then it is overwritten.
:param artifact_object: The artifact object.
:param metadata: A dictionary of key-value pairs for any metadata. This dictionary appears with the
experiment in the **ClearML Web-App (UI)**, **ARTIFACTS** tab.
:param bool delete_after_upload: After the upload, delete the local copy of the artifact
- ``True`` - Delete the local copy of the artifact.
- ``False`` - Do not delete. (default)
:param auto_pickle: If True and the artifact_object is not one of the following types:
pathlib2.Path, dict, pandas.DataFrame, numpy.ndarray, PIL.Image, url (string), local_file (string),
the artifact_object will be pickled and uploaded as pickle file artifact (with file extension .pkl).
If set to None (default) the sdk.development.artifacts.auto_pickle configuration value will be used.
:param preview: The artifact preview
:param wait_on_upload: Whether the upload should be synchronous, forcing the upload to complete
before continuing.
:param extension_name: File extension which indicates the format the artifact should be stored as.
The following are supported, depending on the artifact type (default value applies when extension_name is None):
- Any - ``.pkl`` if passed supersedes any other serialization type, and always pickles the object
- dict - ``.json``, ``.yaml`` (default ``.json``)
- pandas.DataFrame - ``.csv.gz``, ``.parquet``, ``.feather``, ``.pickle`` (default ``.csv.gz``)
- numpy.ndarray - ``.npz``, ``.csv.gz`` (default ``.npz``)
- PIL.Image - whatever extensions PIL supports (default ``.png``)
- In case the ``serialization_function`` argument is set - any extension is supported
:param serialization_function: A serialization function that takes one
parameter of any type which is the object to be serialized. The function should return
a `bytes` or `bytearray` object, which represents the serialized object. Note that the object will be
immediately serialized using this function, thus other serialization methods will not be used
(e.g. `pandas.DataFrame.to_csv`), even if possible. To deserialize this artifact when getting
it using the `Artifact.get` method, use its `deserialization_function` argument.
:param retries: Number of retries before failing to upload artifact. If 0, the upload is not retried
:param sort_keys: If True (default), sort the keys of the artifact if it is yaml/json serializable.
Otherwise, don't sort the keys. Ignored if the artifact is not yaml/json serializable.
:return: The status of the upload.
- ``True`` - Upload succeeded.
- ``False`` - Upload failed.
:raise: If the artifact object type is not supported, raise a ``ValueError``.
"""
exception_to_raise = None
for retry in range(retries + 1):
# noinspection PyBroadException
try:
if self._artifacts_manager.upload_artifact(
name=name,
artifact_object=artifact_object,
metadata=metadata,
delete_after_upload=delete_after_upload,
auto_pickle=auto_pickle,
preview=preview,
wait_on_upload=wait_on_upload,
extension_name=extension_name,
serialization_function=serialization_function,
sort_keys=sort_keys,
):
return True
except Exception as e:
exception_to_raise = e
if retry < retries:
getLogger().warning(
"Failed uploading artifact '{}'. Retrying... ({}/{})".format(name, retry + 1, retries)
)
if exception_to_raise:
raise exception_to_raise
return False
def get_debug_samples(self, title: str, series: str, n_last_iterations: Optional[int] = None) -> List[dict]:
"""
:param str title: Debug sample's title, also called metric in the UI
:param str series: Debug sample's series,
corresponding to debug sample's file name in the UI, also known as variant
:param int n_last_iterations: How many debug sample iterations to fetch in reverse chronological order.
Leave empty to get all debug samples.
:raise: TypeError if `n_last_iterations` is explicitly set to anything other than a positive integer value
:return: A list of `dict`s, each dictionary containing the debug sample's URL and other metadata.
The URLs can be passed to StorageManager.get_local_copy to fetch local copies of debug samples.
"""
from .config.defs import MAX_SERIES_PER_METRIC
if not n_last_iterations:
n_last_iterations = MAX_SERIES_PER_METRIC.get()
if isinstance(n_last_iterations, int) and n_last_iterations >= 0:
samples = self._get_debug_samples(title=title, series=series, n_last_iterations=n_last_iterations)
else:
raise TypeError(
"Parameter n_last_iterations is expected to be a positive integer value,"
" but instead got n_last_iterations={}".format(n_last_iterations)
)
return samples
def _send_debug_image_request(self, title, series, n_last_iterations, scroll_id=None):
return Task._send(
Task._get_default_session(),
events.DebugImagesRequest(
[{"task": self.id, "metric": title, "variants": [series]}],
iters=n_last_iterations,
scroll_id=scroll_id,
),
)
def _get_debug_samples(self, title: str, series: str, n_last_iterations: Optional[int] = None) -> List[dict]:
response = self._send_debug_image_request(title, series, n_last_iterations)
debug_samples = []
while True:
scroll_id = response.response_data.get("scroll_id", None)
for metric_resp in response.response_data.get("metrics", []):
iterations_events: List[List[dict]] = [
iteration["events"] for iteration in metric_resp.get("iterations", [])
]
flattened_events = (event for single_iter_events in iterations_events for event in single_iter_events)
debug_samples.extend(flattened_events)
response = self._send_debug_image_request(title, series, n_last_iterations, scroll_id=scroll_id)
if len(debug_samples) == n_last_iterations or all(
len(metric_resp.get("iterations", [])) == 0 for metric_resp in response.response_data.get("metrics", [])
):
break
return debug_samples
def get_models(self) -> Mapping[str, Sequence[Model]]:
"""
Return a dictionary with ``{'input': [], 'output': []}`` loaded/stored models of the current Task
Input models are files loaded in the task, either manually or automatically logged
Output models are files stored in the task, either manually or automatically logged.
Automatically logged frameworks are for example: TensorFlow, Keras, PyTorch, ScikitLearn(joblib) etc.
:return: A dictionary-like object with "input"/"output" keys and input/output properties, pointing to a
list-like object containing Model objects. Each list-like object also acts as a dictionary, mapping
model name to an appropriate model instance.
Example:
.. code-block:: py
{'input': [clearml.Model()], 'output': [clearml.Model()]}
"""
return TaskModels(self)
def is_current_task(self) -> bool:
"""
.. deprecated:: 0.13.0
This method is deprecated. Use :meth:`Task.is_main_task` instead.
Is this Task object the main execution Task (initially returned by :meth:`Task.init`)
:return: Is this Task object the main execution Task
- ``True`` - Is the main execution Task.
- ``False`` - Is not the main execution Task.
"""
return self.is_main_task()
def is_main_task(self) -> bool:
"""
Is this Task object the main execution Task (initially returned by :meth:`Task.init`)
.. note::
If :meth:`Task.init` was never called, this method will *not* create
it, making this test more efficient than:
.. code-block:: py
Task.init() == task
:return: Is this Task object the main execution Task
- ``True`` - Is the main execution Task.
- ``False`` - Is not the main execution Task.
"""
return self is self.__main_task
def set_model_config(
self,
config_text: Optional[str] = None,
config_dict: Optional[Mapping] = None,
) -> None:
"""
.. deprecated:: 0.14.1
Use :meth:`Task.connect_configuration` instead.
"""
self._set_model_config(config_text=config_text, config_dict=config_dict)
def get_model_config_text(self) -> str:
"""
.. deprecated:: 0.14.1
Use :meth:`Task.connect_configuration` instead.
"""
return self._get_model_config_text()
def get_model_config_dict(self) -> Dict:
"""
.. deprecated:: 0.14.1
Use :meth:`Task.connect_configuration` instead.
"""
return self._get_model_config_dict()
def set_model_label_enumeration(self, enumeration: Optional[Mapping[str, int]] = None) -> ():
"""
Set the label enumeration for the Task object before creating an output model.
Later, when creating an output model, the model will inherit these properties.
:param dict enumeration: A label enumeration dictionary of string (label) to integer (value) pairs.
For example:
.. code-block:: javascript
{
"background": 0,
"person": 1
}
"""
super(Task, self).set_model_label_enumeration(enumeration=enumeration)
def get_last_iteration(self) -> int:
"""
Get the last reported iteration, which is the last iteration for which the Task reported a metric.
.. note::
The maximum reported iteration is not in the local cache. This method
sends a request to the **ClearML Server** (backend).
:return: The last reported iteration number.
"""
self._reload_last_iteration()
return max(
self.data.last_iteration or 0,
self.__reporter.max_iteration if self.__reporter else 0,
)
def set_initial_iteration(self, offset: int = 0) -> int:
"""
Set initial iteration, instead of zero. Useful when continuing training from previous checkpoints
:param int offset: Initial iteration (at starting point)
:return: Newly set initial offset.
"""
return super(Task, self).set_initial_iteration(offset=offset)
def get_initial_iteration(self) -> int:
"""
Return the initial iteration offset, default is 0
Useful when continuing training from previous checkpoints
:return: Initial iteration offset.
"""
return super(Task, self).get_initial_iteration()
def get_last_scalar_metrics(self) -> Dict[str, Dict[str, Dict[str, float]]]:
"""
Get the last scalar metrics which the Task reported. This is a nested dictionary, ordered by title and series.
For example:
.. code-block:: javascript
{
"title": {
"series": {
"last": 0.5,
"min": 0.1,
"max": 0.9
}
}
}
:return: The last scalar metrics.
"""
self.reload()
metrics = self.data.last_metrics
scalar_metrics = dict()
for i in metrics.values():
for j in i.values():
scalar_metrics.setdefault(j["metric"], {}).setdefault(
j["variant"],
{"last": j["value"], "min": j["min_value"], "max": j["max_value"]},
)
return scalar_metrics
def get_parameters_as_dict(self, cast: bool = False) -> Dict:
"""
Get the Task parameters as a raw nested dictionary.
.. note::
If `cast` is False (default) The values are not parsed. They are returned as is.
:param cast: If True, cast the parameter to the original type. Default False,
values are returned in their string representation
"""
return naive_nested_from_flat_dictionary(self.get_parameters(cast=cast))
def set_parameters_as_dict(self, dictionary: Dict) -> None:
"""
Set the parameters for the Task object from a dictionary. The dictionary can be nested.
This does not link the dictionary to the Task object. It does a one-time update. This
is the same behavior as the :meth:`Task.connect` method.
"""
self._arguments.copy_from_dict(flatten_dictionary(dictionary))
def get_user_properties(self, value_only: bool = False) -> Dict[str, Union[str, dict]]:
"""
Get user properties for this task.
Returns a dictionary mapping user property name to user property details dict.
:param value_only: If True, returned user property details will be a string representing the property value.
"""
if not Session.check_min_api_version("2.9"):
self.log.info("User properties are not supported by the server")
return {}
section = "properties"
params = self._hyper_params_manager.get_hyper_params(
sections=[section],
projector=(lambda x: x.get("value")) if value_only else None,
)
return dict(params.get(section, {}))
def set_user_properties(
self,
*iterables: Union[Mapping[str, Union[str, dict, None]], Iterable[dict]],
**properties: Union[str, dict, int, float, None],
) -> bool:
"""
Set user properties for this task.
A user property can contain the following fields (all of type string):
name / value / description / type
Examples:
.. code-block:: py
task.set_user_properties(backbone='great', stable=True)
task.set_user_properties(backbone={"type": int, "description": "network type", "value": "great"}, )
task.set_user_properties(
{"name": "backbone", "description": "network type", "value": "great"},
{"name": "stable", "description": "is stable", "value": True},
)
:param iterables: Properties iterables, each can be:
* A dictionary of string key (name) to either a string value (value) a dict (property details). If the value
is a dict, it must contain a "value" field. For example:
.. code-block:: javascript
{
"property_name": {"description": "This is a user property", "value": "property value"},
"another_property_name": {"description": "This is user property", "value": "another value"},
"yet_another_property_name": "some value"
}
* An iterable of dicts (each representing property details). Each dict must contain a "name" field and a
"value" field. For example:
.. code-block:: javascript
[
{
"name": "property_name",
"description": "This is a user property",
"value": "property value"
},
{
"name": "another_property_name",
"description": "This is another user property",
"value": "another value"
}
]
:param properties: Additional properties keyword arguments. Key is the property name, and value can be
a string (property value) or a dict (property details). If the value is a dict, it must contain a "value"
field. For example:
.. code-block:: javascript
{
"property_name": "string as property value",
"another_property_name": {
"type": "string",
"description": "This is user property",
"value": "another value"
}
}
"""
if not Session.check_min_api_version("2.9"):
self.log.info("User properties are not supported by the server")
return False
return self._hyper_params_manager.edit_hyper_params(
iterables=list(properties.items())
+ (list(iterables.items()) if isinstance(iterables, dict) else list(iterables)),
replace="none",
force_section="properties",
)
def get_script(self) -> Mapping[str, Optional[str]]:
"""
Get task's script details.
Returns a dictionary containing the script details.
:return: Dictionary with script properties e.g.
.. code-block:: javascript
{
'working_dir': 'examples/reporting',
'entry_point': 'artifacts.py',
'branch': 'master',
'repository': 'https://github.com/allegroai/clearml.git'
}
"""
script = self.data.script
return {
"working_dir": script.working_dir,
"entry_point": script.entry_point,
"branch": script.branch,
"repository": script.repository,
}
def set_script(
self,
repository: Optional[str] = None,
branch: Optional[str] = None,
commit: Optional[str] = None,
diff: Optional[str] = None,
working_dir: Optional[str] = None,
entry_point: Optional[str] = None,
) -> None:
"""
Set task's script.
Examples:
.. code-block:: py
task.set_script(
repository='https://github.com/allegroai/clearml.git,
branch='main',
working_dir='examples/reporting',
entry_point='artifacts.py'
)
:param repository: Optional, URL of remote repository. use empty string ("") to clear repository entry.
:param branch: Optional, Select specific repository branch / tag. use empty string ("") to clear branch entry.
:param commit: Optional, set specific git commit id. use empty string ("") to clear commit ID entry.
:param diff: Optional, set "git diff" section. use empty string ("") to clear git-diff entry.
:param working_dir: Optional, Working directory to launch the script from.
:param entry_point: Optional, Path to execute within the repository.
"""
self.reload()
script = self.data.script
if repository is not None:
script.repository = str(repository)
if branch is not None:
script.branch = str(branch)
if script.tag:
script.tag = None
if commit is not None:
script.version_num = str(commit)
if diff is not None:
script.diff = str(diff)
if working_dir is not None:
script.working_dir = str(working_dir)
if entry_point is not None:
script.entry_point = str(entry_point)
# noinspection PyProtectedMember
self._update_script(script=script)
def delete_user_properties(self, *iterables: Iterable[Union[dict, Iterable[str]]]) -> bool:
"""
Delete hyperparameters for this task.
:param iterables: Hyperparameter key iterables. Each an iterable whose possible values each represent
a hyperparameter entry to delete, value formats are:
* A dictionary containing a 'section' and 'name' fields
* An iterable (e.g. tuple, list etc.) whose first two items denote 'section' and 'name'
"""
if not Session.check_min_api_version("2.9"):
self.log.info("User properties are not supported by the server")
return False
return self._hyper_params_manager.delete_hyper_params(*iterables)
def set_base_docker(
self,
docker_cmd: Optional[str] = None,
docker_image: Optional[str] = None,
docker_arguments: Optional[Union[str, Sequence[str]]] = None,
docker_setup_bash_script: Optional[Union[str, Sequence[str]]] = None,
) -> ():
"""
Set the base docker image for this experiment
If provided, this value will be used by clearml-agent to execute this experiment
inside the provided docker image.
When running remotely the call is ignored
:param docker_cmd: Deprecated! compound docker container image + arguments
(example: 'nvidia/cuda:11.1 -e test=1') Deprecated, use specific arguments.
:param docker_image: docker container image (example: 'nvidia/cuda:11.1')
:param docker_arguments: docker execution parameters (example: '-e ENV=1')
:param docker_setup_bash_script: bash script to run at the
beginning of the docker before launching the Task itself. example: ['apt update', 'apt-get install -y gcc']
"""
if not self.running_locally() and self.is_main_task():
return
super(Task, self).set_base_docker(
docker_cmd=docker_cmd or docker_image,
docker_arguments=docker_arguments,
docker_setup_bash_script=docker_setup_bash_script,
)
@classmethod
def set_resource_monitor_iteration_timeout(
cls,
seconds_from_start: float = 30.0,
wait_for_first_iteration_to_start_sec: float = 180.0,
max_wait_for_first_iteration_to_start_sec: float = 1800.0,
) -> bool:
"""
Set the ResourceMonitor maximum duration (in seconds) to wait until first scalar/plot is reported.
If timeout is reached without any reporting, the ResourceMonitor will start reporting machine statistics based
on seconds from Task start time (instead of based on iteration).
Notice! Should be called before `Task.init`.
:param seconds_from_start: Maximum number of seconds to wait for scalar/plot reporting before defaulting
to machine statistics reporting based on seconds from experiment start time
:param wait_for_first_iteration_to_start_sec: Set the initial time (seconds) to wait for iteration reporting
to be used as x-axis for the resource monitoring, if timeout exceeds then reverts to `seconds_from_start`
:param max_wait_for_first_iteration_to_start_sec: Set the maximum time (seconds) to allow the resource
monitoring to revert back to iteration reporting x-axis after starting to report `seconds_from_start`
:return: True if success
"""
if ResourceMonitor._resource_monitor_instances:
getLogger().warning(
"Task.set_resource_monitor_iteration_timeout called after Task.init."
" This might not work since the values might not be used in forked processes"
)
# noinspection PyProtectedMember
for instance in ResourceMonitor._resource_monitor_instances:
# noinspection PyProtectedMember
instance._first_report_sec = seconds_from_start
instance.wait_for_first_iteration = wait_for_first_iteration_to_start_sec
instance.max_check_first_iteration = max_wait_for_first_iteration_to_start_sec
# noinspection PyProtectedMember
ResourceMonitor._first_report_sec_default = seconds_from_start
# noinspection PyProtectedMember
ResourceMonitor._wait_for_first_iteration_to_start_sec_default = wait_for_first_iteration_to_start_sec
# noinspection PyProtectedMember
ResourceMonitor._max_wait_for_first_iteration_to_start_sec_default = max_wait_for_first_iteration_to_start_sec
return True
def execute_remotely(
self,
queue_name: Optional[str] = None,
clone: bool = False,
exit_process: bool = True,
) -> Optional["Task"]:
"""
If task is running locally (i.e., not by ``clearml-agent``), then clone the Task and enqueue it for remote
execution; or, stop the execution of the current Task, reset its state, and enqueue it. If ``exit==True``,
*exit* this process.
.. note::
If the task is running remotely (i.e., ``clearml-agent`` is executing it), this call is a no-op
(i.e., does nothing).
:param queue_name: The queue name used for enqueueing the task. If ``None``, this call exits the process
without enqueuing the task.
:param clone: Clone the Task and execute the newly cloned Task
The values are:
- ``True`` - A cloned copy of the Task will be created, and enqueued, instead of this Task.
- ``False`` - The Task will be enqueued.
:param exit_process: The function call will leave the calling process at the end.
- ``True`` - Exit the process (exit(0)). Note: if ``clone==False``, then ``exit_process`` must be ``True``.
- ``False`` - Do not exit the process.
:return Task: return the task object of the newly generated remotely executing task
"""
# do nothing, we are running remotely
if running_remotely() and self.is_main_task():
return None
if not self.is_main_task():
LoggerRoot.get_base_logger().warning(
"Calling task.execute_remotely is only supported on main Task (created with Task.init)\n"
"Defaulting to self.enqueue(queue_name={})".format(queue_name)
)
if not queue_name:
raise ValueError("queue_name must be provided")
enqueue_task = Task.clone(source_task=self) if clone else self
Task.enqueue(task=enqueue_task, queue_name=queue_name)
return
if not clone and not exit_process:
raise ValueError(
"clone==False and exit_process==False is not supported. "
"Task enqueuing itself must exit the process afterwards."
)
# make sure we analyze the process
if self.status in (Task.TaskStatusEnum.in_progress,):
if clone:
# wait for repository detection (5 minutes should be reasonable time to detect all packages)
self.flush(wait_for_uploads=True)
if self._logger and not self.__is_subprocess():
self._wait_for_repo_detection(timeout=300.0)
else:
# close ourselves (it will make sure the repo is updated)
self.close()
# clone / reset Task
if clone:
task = Task.clone(self)
else:
task = self
# check if the server supports enqueueing aborted/stopped Tasks
if Session.check_min_api_server_version("2.13"):
self.mark_stopped(force=True)
else:
self.reset()
# enqueue ourselves
if queue_name:
Task.enqueue(task, queue_name=queue_name)
LoggerRoot.get_base_logger().warning(
"Switching to remote execution, output log page {}".format(task.get_output_log_web_page())
)
else:
# Remove the development system tag
system_tags = [t for t in task.get_system_tags() if t != self._development_tag]
self.set_system_tags(system_tags)
# if we leave the Task out there, it makes sense to make it editable.
self.reset(force=True)
# leave this process.
if exit_process:
LoggerRoot.get_base_logger().warning(
"ClearML Terminating local execution process - continuing execution remotely"
)
leave_process(0)
return task
def create_function_task(
self,
func: Callable,
func_name: Optional[str] = None,
task_name: Optional[str] = None,
**kwargs: Optional[Any],
) -> Optional["Task"]:
"""
Create a new task, and call ``func`` with the specified kwargs.
One can think of this call as remote forking, where the newly created instance is the new Task
calling the specified func with the appropriate kwargs and leaving once the func terminates.
Notice that a remote executed function cannot create another child remote executed function.
.. note::
- Must be called from the main Task, i.e. the one created by Task.init(...)
- The remote Tasks inherits the environment from the creating Task
- In the remote Task, the entrypoint is the same as the creating Task
- In the remote Task, the execution is the same until reaching this function call
:param func: A function to execute remotely as a single Task.
On the remote executed Task the entry-point and the environment are copied from this
calling process, only this function call redirect the execution flow to the called func,
alongside the passed arguments
:param func_name: A unique identifier of the function. Default the function name without the namespace.
For example Class.foo() becomes 'foo'
:param task_name: The newly created Task name. Default: the calling Task name + function name
:param kwargs: name specific arguments for the target function.
These arguments will appear under the configuration, "Function" section
:return Task: Return the newly created Task or None if running remotely and execution is skipped
"""
if not self.is_main_task():
raise ValueError("Only the main Task object can call create_function_task()")
if not callable(func):
raise ValueError("func must be callable")
if not Session.check_min_api_version("2.9"):
raise ValueError("Remote function execution is not supported, please upgrade to the latest server version")
func_name = str(func_name or func.__name__).strip()
if func_name in self._remote_functions_generated:
raise ValueError(
"Function name must be unique, a function by the name '{}' "
"was already created by this Task.".format(func_name)
)
section_name = "Function"
tag_name = "func"
func_marker = "__func_readonly__"
# sanitize the dict, leave only basic types that we might want to override later in the UI
func_params = {k: v for k, v in kwargs.items() if verify_basic_value(v)}
func_params[func_marker] = func_name
# do not query if we are running locally, there is no need.
task_func_marker = self.running_locally() or self.get_parameter("{}/{}".format(section_name, func_marker))
# if we are running locally or if we are running remotely but we are not a forked tasks
# condition explained:
# (1) running in development mode creates all the forked tasks
# (2) running remotely but this is not one of the forked tasks (i.e. it is missing the fork tag attribute)
if self.running_locally() or not task_func_marker:
self._wait_for_repo_detection(300)
task = self.clone(
self,
name=task_name or "{} <{}>".format(self.name, func_name),
parent=self.id,
)
task.set_system_tags((task.get_system_tags() or []) + [tag_name])
task.connect(func_params, name=section_name)
self._remote_functions_generated[func_name] = task.id
return task
# check if we are one of the generated functions and if this is us,
# if we are not the correct function, not do nothing and leave
if task_func_marker != func_name:
self._remote_functions_generated[func_name] = len(self._remote_functions_generated) + 1
return
# mark this is us:
self._remote_functions_generated[func_name] = self.id
# this is us for sure, let's update the arguments and call the function
self.connect(func_params, name=section_name)
func_params.pop(func_marker, None)
kwargs.update(func_params)
func(**kwargs)
# This is it, leave the process
leave_process(0)
def wait_for_status(
self,
status: Iterable["Task.TaskStatusEnum"] = (
_Task.TaskStatusEnum.completed,
_Task.TaskStatusEnum.stopped,
_Task.TaskStatusEnum.closed,
),
raise_on_status: Optional[Iterable["Task.TaskStatusEnum"]] = (_Task.TaskStatusEnum.failed,),
check_interval_sec: float = 60.0,
) -> ():
"""
Wait for a task to reach a defined status.
:param status: Status to wait for. Defaults to ('completed', 'stopped', 'closed', )
:param raise_on_status: Raise RuntimeError if the status of the tasks matches one of these values.
Defaults to ('failed').
:param check_interval_sec: Interval in seconds between two checks. Defaults to 60 seconds.
:raise: RuntimeError if the status is one of ``{raise_on_status}``.
"""
stopped_status = list(status) + (list(raise_on_status) if raise_on_status else [])
while self.status not in stopped_status:
time.sleep(check_interval_sec)
if raise_on_status and self.status in raise_on_status:
raise RuntimeError("Task {} has status: {}.".format(self.task_id, self.status))
# make sure we have the Task object
self.reload()
def export_task(self) -> dict:
"""
Export Task's configuration into a dictionary (for serialization purposes).
A Task can be copied/modified by calling Task.import_task()
Notice: Export task does not include the tasks outputs, such as results
(scalar/plots etc.) or Task artifacts/models
:return: dictionary of the Task's configuration.
"""
self.reload()
export_data = self.data.to_dict()
export_data.pop("last_metrics", None)
export_data.pop("last_iteration", None)
export_data.pop("status_changed", None)
export_data.pop("status_reason", None)
export_data.pop("status_message", None)
export_data.get("execution", {}).pop("artifacts", None)
export_data.get("execution", {}).pop("model", None)
export_data["project_name"] = self.get_project_name()
export_data["session_api_version"] = self.session.api_version
return export_data
def update_task(self, task_data: dict) -> bool:
"""
Update current task with configuration found on the task_data dictionary.
See also export_task() for retrieving Task configuration.
:param task_data: dictionary with full Task configuration
:return: return True if Task update was successful
"""
return bool(self.import_task(task_data=task_data, target_task=self, update=True))
def rename(self, new_name: str) -> bool:
"""
Rename this task
:param new_name: The new name of this task
:return: True if the rename was successful and False otherwise
"""
result = bool(self._edit(name=new_name))
self.reload()
return result
def move_to_project(
self,
new_project_id: Optional[str] = None,
new_project_name: Optional[str] = None,
system_tags: Optional[Sequence[str]] = None,
) -> bool:
"""
Move this task to another project
:param new_project_id: The ID of the project the task should be moved to.
Not required if `new_project_name` is passed.
:param new_project_name: Name of the new project the task should be moved to.
Not required if `new_project_id` is passed.
:param system_tags: System tags for the project the task should be moved to.
:return: True if the move was successful and False otherwise
"""
new_project_id = get_or_create_project(
self.session,
project_name=new_project_name,
project_id=new_project_id,
system_tags=system_tags,
)
result = bool(self._edit(project=new_project_id))
self.reload()
return result
def register_abort_callback(
self,
callback_function: Optional[Callable],
callback_execution_timeout: float = 30.0,
): # type (...) -> None
"""
Register a Task abort callback (single callback function support only).
Pass a function to be called from a background thread when the Task is **externally** being aborted.
Users must specify a timeout for the callback function execution (default 30 seconds)
if the callback execution function exceeds the timeout, the Task's process will be terminated
Call this register function from the main process only.
Note: Ctrl-C is Not considered external, only backend induced abort is covered here
:param callback_function: Callback function to be called via external thread (from the main process).
pass None to remove existing callback
:param callback_execution_timeout: Maximum callback execution time in seconds, after which the process
will be terminated even if the callback did not return
"""
if self.__is_subprocess():
raise ValueError("Register abort callback must be called from the main process, this is a subprocess.")
if callback_function is None:
if self._dev_worker:
self._dev_worker.register_abort_callback(callback_function=None, execution_timeout=0, poll_freq=0)
return
if float(callback_execution_timeout) <= 0:
raise ValueError(
"function_timeout_sec must be positive timeout in seconds, got {}".format(callback_execution_timeout)
)
# if we are running remotely we might not have a DevWorker monitoring us, so let's create one
if not self._dev_worker:
self._dev_worker = DevWorker()
self._dev_worker.register(self, stop_signal_support=True)
poll_freq = 15.0
self._dev_worker.register_abort_callback(
callback_function=callback_function,
execution_timeout=callback_execution_timeout,
poll_freq=poll_freq,
)
@classmethod
def import_task(
cls,
task_data: dict,
target_task: Optional[Union[str, "Task"]] = None,
update: bool = False,
) -> Optional["Task"]:
"""
Import (create) Task from previously exported Task configuration (see Task.export_task)
Can also be used to edit/update an existing Task (by passing `target_task` and `update=True`).
:param task_data: dictionary of a Task's configuration
:param target_task: Import task_data into an existing Task. Can be either task_id (str) or Task object.
:param update: If True, merge task_data with current Task configuration.
:return: return True if Task was imported/updated
"""
# restore original API version (otherwise, we might not be able to restore the data correctly)
force_api_version = task_data.get("session_api_version") or None
original_api_version = Session.api_version
original_force_max_api_version = Session.force_max_api_version
if force_api_version:
Session.force_max_api_version = str(force_api_version)
if not target_task:
project_name = task_data.get("project_name") or Task._get_project_name(task_data.get("project", ""))
target_task = Task.create(project_name=project_name, task_name=task_data.get("name", None))
elif isinstance(target_task, six.string_types):
target_task: Optional[Task] = Task.get_task(task_id=target_task)
elif not isinstance(target_task, Task):
raise ValueError(
"`target_task` must be either Task id (str) or Task object, "
"received `target_task` type {}".format(type(target_task))
)
target_task.reload()
cur_data = target_task.data.to_dict()
cur_data = merge_dicts(cur_data, task_data) if update else dict(**task_data)
cur_data.pop("id", None)
cur_data.pop("project", None)
# noinspection PyProtectedMember
valid_fields = list(tasks.EditRequest._get_data_props().keys())
cur_data = dict((k, cur_data[k]) for k in valid_fields if k in cur_data)
res = target_task._edit(**cur_data)
if res and res.ok():
target_task.reload()
else:
target_task = None
# restore current api version, and return a new instance if Task with the current version
if force_api_version:
Session.force_max_api_version = original_force_max_api_version
Session.api_version = original_api_version
if target_task:
target_task = Task.get_task(task_id=target_task.id)
return target_task
@classmethod
def set_offline(cls, offline_mode: bool = False) -> None:
"""
Set offline mode, where all data and logs are stored into local folder, for later transmission
.. note::
`Task.set_offline` can't move the same task from offline to online, nor can it be applied before `Task.create`.
See below an example of **incorrect** usage of `Task.set_offline`:
```
from clearml import Task
Task.set_offline(True)
task = Task.create(project_name='DEBUG', task_name="offline")
# ^^^ an error or warning is raised, saying that Task.set_offline(True)
# is supported only for `Task.init`
Task.set_offline(False)
# ^^^ an error or warning is raised, saying that running Task.set_offline(False)
# while the current task is not closed is not supported
data = task.export_task()
imported_task = Task.import_task(task_data=data)
```
The correct way to use `Task.set_offline` can be seen in the following example:
```
from clearml import Task
Task.set_offline(True)
task = Task.init(project_name='DEBUG', task_name="offline")
task.upload_artifact("large_artifact", "test_string")
task.close()
Task.set_offline(False)
imported_task = Task.import_offline_session(task.get_offline_mode_folder())
```
:param offline_mode: If True, offline-mode is turned on, and no communication to the backend is enabled.
:return:
"""
if running_remotely() or bool(offline_mode) == InterfaceBase._offline_mode:
return
if cls.current_task() and cls.current_task().status != cls.TaskStatusEnum.closed and not offline_mode:
raise UsageError(
"Switching from offline mode to online mode, but the current task has not been closed. Use `Task.close` to close it."
)
ENV_OFFLINE_MODE.set(offline_mode)
InterfaceBase._offline_mode = bool(offline_mode)
Session._offline_mode = bool(offline_mode)
if not offline_mode:
# noinspection PyProtectedMember
Session._make_all_sessions_go_online()
@classmethod
def is_offline(cls) -> bool:
"""
Return offline-mode state, If in offline-mode, no communication to the backend is enabled.
:return: boolean offline-mode state
"""
return cls._offline_mode
@classmethod
def import_offline_session(
cls, session_folder_zip: str, previous_task_id: Optional[str] = None, iteration_offset: Optional[int] = 0
) -> Optional[str]:
"""
Upload an offline session (execution) of a Task.
Full Task execution includes repository details, installed packages, artifacts, logs, metric and debug samples.
This function may also be used to continue a previously executed task with a task executed offline.
:param session_folder_zip: Path to a folder containing the session, or zip-file of the session folder.
:param previous_task_id: Task ID of the task you wish to continue with this offline session.
:param iteration_offset: Reporting of the offline session will be offset with the
number specified by this parameter. Useful for avoiding overwriting metrics.
:return: Newly created task ID or the ID of the continued task (previous_task_id)
"""
print("ClearML: Importing offline session from {}".format(session_folder_zip))
temp_folder = None
if Path(session_folder_zip).is_file():
# unzip the file:
temp_folder = mkdtemp(prefix="clearml-offline-")
ZipFile(session_folder_zip).extractall(path=temp_folder)
session_folder_zip = temp_folder
session_folder = Path(session_folder_zip)
if not session_folder.is_dir():
raise ValueError("Could not find the session folder / zip-file {}".format(session_folder))
try:
with open((session_folder / cls._offline_filename).as_posix(), "rt") as f:
export_data = json.load(f)
except Exception as ex:
raise ValueError(
"Could not read Task object {}: Exception {}".format(session_folder / cls._offline_filename, ex)
)
current_task = cls.import_task(export_data)
if previous_task_id:
task_holding_reports = cls.get_task(task_id=previous_task_id)
task_holding_reports.mark_started(force=True)
task_holding_reports = cls.import_task(export_data, target_task=task_holding_reports, update=True)
else:
task_holding_reports = current_task
task_holding_reports.mark_started(force=True)
# fix artifacts
if current_task.data.execution.artifacts:
from . import StorageManager
# noinspection PyProtectedMember
offline_folder = os.path.join(export_data.get("offline_folder", ""), "data/")
# noinspection PyProtectedMember
remote_url = current_task._get_default_report_storage_uri()
if remote_url and remote_url.endswith("/"):
remote_url = remote_url[:-1]
for artifact in current_task.data.execution.artifacts:
local_path = artifact.uri.replace(offline_folder, "", 1)
local_file = session_folder / "data" / local_path
if local_file.is_file():
remote_path = local_path.replace(
".{}{}".format(export_data["id"], os.sep),
".{}{}".format(current_task.id, os.sep),
1,
)
artifact.uri = "{}/{}".format(remote_url, remote_path)
StorageManager.upload_file(local_file=local_file.as_posix(), remote_url=artifact.uri)
# noinspection PyProtectedMember
task_holding_reports._edit(execution=current_task.data.execution)
for output_model in export_data.get("offline_output_models", []):
model = OutputModel(task=current_task, **output_model["init"])
if output_model.get("output_uri"):
model.set_upload_destination(output_model.get("output_uri"))
model.update_weights(auto_delete_file=False, **output_model["weights"])
Metrics.report_offline_session(
model,
session_folder,
iteration_offset=iteration_offset,
remote_url=task_holding_reports._get_default_report_storage_uri(),
only_with_id=output_model["id"],
session=task_holding_reports.session,
)
# logs
TaskHandler.report_offline_session(task_holding_reports, session_folder, iteration_offset=iteration_offset)
# metrics
Metrics.report_offline_session(
task_holding_reports,
session_folder,
iteration_offset=iteration_offset,
only_with_id=export_data["id"],
session=task_holding_reports.session,
)
# print imported results page
print("ClearML results page: {}".format(task_holding_reports.get_output_log_web_page()))
task_holding_reports.mark_completed()
# close task
task_holding_reports.close()
# cleanup
if temp_folder:
# noinspection PyBroadException
try:
shutil.rmtree(temp_folder)
except Exception:
pass
return task_holding_reports.id
@classmethod
def set_credentials(
cls,
api_host: Optional[str] = None,
web_host: Optional[str] = None,
files_host: Optional[str] = None,
key: Optional[str] = None,
secret: Optional[str] = None,
store_conf_file: bool = False,
) -> None:
"""
Set new default **ClearML Server** (backend) host and credentials.
These credentials will be overridden by either OS environment variables, or the ClearML configuration
file, ``clearml.conf``.
.. warning::
Credentials must be set before initializing a Task object.
For example, to set credentials for a remote computer:
.. code-block:: py
Task.set_credentials(
api_host='http://localhost:8008', web_host='http://localhost:8080', files_host='http://localhost:8081',
key='optional_credentials', secret='optional_credentials'
)
task = Task.init('project name', 'experiment name')
:param str api_host: The API server url. For example, ``host='http://localhost:8008'``
:param str web_host: The Web server url. For example, ``host='http://localhost:8080'``
:param str files_host: The file server url. For example, ``host='http://localhost:8081'``
:param str key: The user key (in the key/secret pair). For example, ``key='thisisakey123'``
:param str secret: The user secret (in the key/secret pair). For example, ``secret='thisisseceret123'``
:param bool store_conf_file: If True, store the current configuration into the ~/clearml.conf file.
If the configuration file exists, no change will be made (outputs a warning).
Not applicable when running remotely (i.e. clearml-agent).
"""
if api_host:
Session.default_host = api_host
if not running_remotely() and not ENV_HOST.get():
ENV_HOST.set(api_host)
if web_host:
Session.default_web = web_host
if not running_remotely() and not ENV_WEB_HOST.get():
ENV_WEB_HOST.set(web_host)
if files_host:
Session.default_files = files_host
if not running_remotely() and not ENV_FILES_HOST.get():
ENV_FILES_HOST.set(files_host)
if key:
Session.default_key = key
if not running_remotely():
ENV_ACCESS_KEY.set(key)
if secret:
Session.default_secret = secret
if not running_remotely():
ENV_SECRET_KEY.set(secret)
if store_conf_file and not running_remotely():
active_conf_file = get_active_config_file()
if active_conf_file:
getLogger().warning(
"Could not store credentials in configuration file, '{}' already exists".format(active_conf_file)
)
else:
conf = {
"api": dict(
api_server=Session.default_host,
web_server=Session.default_web,
files_server=Session.default_files,
credentials=dict(
access_key=Session.default_key,
secret_key=Session.default_secret,
),
)
}
with open(get_config_file(), "wt") as f:
lines = json.dumps(conf, indent=4).split("\n")
f.write("\n".join(lines[1:-1]))
@classmethod
def debug_simulate_remote_task(cls, task_id: str, reset_task: bool = False) -> ():
"""
Simulate remote execution of a specified Task.
This call will simulate the behaviour of your Task as if executed by the ClearML-Agent
This means configurations will be coming from the backend server into the code
(the opposite from manual execution, where the backend logs the code arguments)
Use with care.
:param task_id: Task ID to simulate, notice that all configuration will be taken from the specified
Task, regardless of the code initial values, just like it as if executed by ClearML agent
:param reset_task: If True, target Task, is automatically cleared / reset.
"""
# if we are already running remotely, do nothing
if running_remotely():
return
# verify Task ID exists
task = Task.get_task(task_id=task_id)
if not task:
raise ValueError("Task ID '{}' could not be found".format(task_id))
if reset_task:
task.reset(set_started_on_success=False, force=True)
from .config.remote import override_current_task_id
from .config.defs import LOG_TO_BACKEND_ENV_VAR
override_current_task_id(task_id)
LOG_TO_BACKEND_ENV_VAR.set(True)
DEBUG_SIMULATE_REMOTE_TASK.set(True)
def get_executed_queue(self, return_name: bool = False) -> Optional[str]:
"""
Get the queue the task was executed on.
:param return_name: If True, return the name of the queue. Otherwise, return its ID
:return: Return the ID or name of the queue the task was executed on.
If no queue was found, return None
"""
queue_id = self.data.execution.queue
if not return_name or not queue_id:
return queue_id
try:
queue_name_result = Task._send(Task._get_default_session(), queues.GetByIdRequest(queue_id))
return queue_name_result.response.queue.name
except Exception as e:
getLogger().warning("Could not get name of queue with ID '{}': {}".format(queue_id, e))
return None
@classmethod
def _create(
cls,
project_name: Optional[str] = None,
task_name: Optional[str] = None,
task_type: "Task.TaskTypes" = TaskTypes.training,
) -> TaskInstance:
"""
Create a new unpopulated Task (experiment).
:param str project_name: The name of the project in which the experiment will be created.
If ``project_name`` is ``None``, and the main execution Task is initialized (see :meth:`Task.init`),
then the main execution Task's project is used. Otherwise, if the project does
not exist, it is created. (Optional)
:param str task_name: The name of Task (experiment).
:param TaskTypes task_type: The task type.
:return: The newly created task created.
:rtype: Task
"""
if not project_name:
if not cls.__main_task:
raise ValueError(
"Please provide project_name, no global task context found "
"(Task.current_task hasn't been called)"
)
project_name = cls.__main_task.get_project_name()
try:
task = cls(
private=cls.__create_protection,
project_name=project_name,
task_name=task_name,
task_type=task_type,
log_to_backend=False,
force_create=True,
)
except Exception:
raise
return task
def _set_model_config(
self,
config_text: Optional[str] = None,
config_dict: Optional[Mapping] = None,
) -> None:
"""
Set Task model configuration text/dict
:param config_text: model configuration (unconstrained text string). usually the content
of a configuration file. If `config_text` is not None, `config_dict` must not be provided.
:param config_dict: model configuration parameters dictionary.
If `config_dict` is not None, `config_text` must not be provided.
"""
# noinspection PyProtectedMember
design = OutputModel._resolve_config(config_text=config_text, config_dict=config_dict)
super(Task, self)._set_model_design(design=design)
def _get_model_config_text(self) -> str:
"""
Get Task model configuration text (before creating an output model)
When an output model is created it will inherit these properties
:return: The model config_text (unconstrained text string).
"""
return super(Task, self).get_model_design()
def _get_model_config_dict(self) -> Dict:
"""
Get Task model configuration dictionary (before creating an output model)
When an output model is created it will inherit these properties
:return: config_dict: model configuration parameters dictionary.
"""
config_text = self._get_model_config_text()
# noinspection PyProtectedMember
return OutputModel._text_to_config_dict(config_text)
def _set_startup_info(self) -> ():
self._set_runtime_properties(
runtime_properties={
"CLEARML VERSION": self.session.client,
"CLI": sys.argv[0],
"progress": "0",
}
)
@classmethod
def _reset_current_task_obj(cls) -> None:
if not cls.__main_task:
return
task = cls.__main_task
cls.__main_task = None
cls.__forked_proc_main_pid = None
if task._dev_worker:
task._dev_worker.unregister()
task._dev_worker = None
@classmethod
def _has_current_task_obj(cls) -> bool:
return bool(cls.__main_task)
@classmethod
def _create_dev_task(
cls,
default_project_name,
default_task_name,
default_task_type,
tags,
reuse_last_task_id,
continue_last_task=False,
detect_repo=True,
auto_connect_streams=True,
):
if not default_project_name or not default_task_name:
# get project name and task name from repository name and entry_point
result, _ = ScriptInfo.get(create_requirements=False, check_uncommitted=False)
if not default_project_name:
# noinspection PyBroadException
try:
parts = result.script["repository"].split("/")
default_project_name = (parts[-1] or parts[-2]).replace(".git", "") or "Untitled"
except Exception:
default_project_name = "Untitled"
if not default_task_name:
# noinspection PyBroadException
try:
default_task_name = os.path.splitext(os.path.basename(result.script["entry_point"]))[0]
except Exception:
pass
# conform reuse_last_task_id and continue_last_task
if continue_last_task and isinstance(continue_last_task, str):
reuse_last_task_id = continue_last_task
continue_last_task = True
elif isinstance(continue_last_task, int) and continue_last_task is not True:
# allow initial offset environment override
continue_last_task = continue_last_task
if TASK_SET_ITERATION_OFFSET.get() is not None:
continue_last_task = TASK_SET_ITERATION_OFFSET.get()
# if we force no task reuse from os environment
if DEV_TASK_NO_REUSE.get() or not reuse_last_task_id or isinstance(reuse_last_task_id, str):
default_task = None
else:
# if we have a previous session to use, get the task id from it
default_task = cls.__get_last_used_task_id(
default_project_name,
default_task_name,
default_task_type.value,
)
closed_old_task = False
default_task_id = None
task = None
in_dev_mode = not running_remotely()
if in_dev_mode:
if isinstance(reuse_last_task_id, str) and reuse_last_task_id:
default_task_id = reuse_last_task_id
elif not reuse_last_task_id or not cls.__task_is_relevant(default_task):
default_task_id = None
else:
default_task_id = default_task.get("id") if default_task else None
if default_task_id:
try:
task = cls(
private=cls.__create_protection,
task_id=default_task_id,
log_to_backend=True,
)
# instead of resting the previously used task we are continuing the training with it.
if task and (
continue_last_task
or (isinstance(continue_last_task, int) and not isinstance(continue_last_task, bool))
):
task.reload()
task.mark_started(force=True)
# allow to disable the
if continue_last_task is True:
task.set_initial_iteration(task.get_last_iteration() + 1)
else:
task.set_initial_iteration(continue_last_task)
else:
task_tags = task.data.system_tags if hasattr(task.data, "system_tags") else task.data.tags
task_artifacts = (
task.data.execution.artifacts if hasattr(task.data.execution, "artifacts") else None
)
if (
(
task._status
in (
cls.TaskStatusEnum.published,
cls.TaskStatusEnum.closed,
)
)
or task.output_models_id
or (cls.archived_tag in task_tags)
or (cls._development_tag not in task_tags)
or task_artifacts
):
# If the task is published or closed, we shouldn't reset it so we can't use it in dev mode
# If the task is archived, or already has an output model,
# we shouldn't use it in development mode either
default_task_id = None
task = None
else:
with task._edit_lock:
# from now on, there is no need to reload, we just clear stuff,
# this flag will be cleared off once we actually refresh at the end of the function
task._reload_skip_flag = True
# reset the task, so we can update it
task.reset(set_started_on_success=False, force=False)
# clear the heaviest stuff first
task._clear_task(
system_tags=[cls._development_tag],
comment=make_message("Auto-generated at %(time)s by %(user)s@%(host)s"),
)
except (Exception, ValueError):
# we failed reusing task, create a new one
default_task_id = None
# create a new task
if not default_task_id:
task = cls(
private=cls.__create_protection,
project_name=default_project_name,
task_name=default_task_name,
task_type=default_task_type,
log_to_backend=True,
)
# no need to reload yet, we clear this before the end of the function
task._reload_skip_flag = True
if in_dev_mode:
# update this session, for later use
cls.__update_last_used_task_id(
default_project_name,
default_task_name,
default_task_type.value,
task.id,
)
# set default docker image from env.
task._set_default_docker_image()
# mark us as the main Task, there should only be one dev Task at a time.
if not Task.__main_task:
Task.__forked_proc_main_pid = os.getpid()
Task.__main_task = task
# mark the task as started
task.started()
# reload, making sure we are synced
task._reload_skip_flag = False
task.reload()
# add Task tags
if tags:
task.add_tags([tags] if isinstance(tags, str) else tags)
# force update of base logger to this current task (this is the main logger task)
logger = task._get_logger(auto_connect_streams=auto_connect_streams)
if closed_old_task:
logger.report_text("ClearML Task: Closing old development task id={}".format(default_task.get("id")))
# print warning, reusing/creating a task
if default_task_id and not continue_last_task:
logger.report_text("ClearML Task: overwriting (reusing) task id=%s" % task.id)
elif default_task_id and continue_last_task:
logger.report_text(
"ClearML Task: continuing previous task id=%s Notice this run will not be reproducible!" % task.id
)
else:
logger.report_text("ClearML Task: created new task id=%s" % task.id)
# update current repository and put warning into logs
if detect_repo:
# noinspection PyBroadException
try:
import traceback
stack = traceback.extract_stack(limit=10)
# NOTICE WE ARE ALWAYS 3 down from caller in stack!
for i in range(len(stack) - 1, 0, -1):
# look for the Task.init call, then the one above it is the callee module
if stack[i].name == "init":
task._calling_filename = os.path.abspath(stack[i - 1].filename)
break
except Exception:
pass
if in_dev_mode and cls.__detect_repo_async:
task._detect_repo_async_thread = threading.Thread(target=task._update_repository)
task._detect_repo_async_thread.daemon = True
task._detect_repo_async_thread.start()
else:
task._update_repository()
# make sure we see something in the UI
thread = threading.Thread(target=LoggerRoot.flush)
thread.daemon = True
thread.start()
return task
def _get_logger(
self,
flush_period: Optional[float] = NotSet,
auto_connect_streams: Union[bool, dict] = False,
) -> Logger:
"""
get a logger object for reporting based on the task
:param flush_period: The period of the logger flush.
If None of any other False value, will not flush periodically.
If a logger was created before, this will be the new period and
the old one will be discarded.
:return: Logger object
"""
if not self._logger:
# do not recreate logger after task was closed/quit
if self._at_exit_called and self._at_exit_called in (
True,
get_current_thread_id(),
):
raise ValueError("Cannot use Task Logger after task was closed")
# Get a logger object
self._logger = Logger(
private_task=self,
connect_stdout=(auto_connect_streams is True)
or (isinstance(auto_connect_streams, dict) and auto_connect_streams.get("stdout", False)),
connect_stderr=(auto_connect_streams is True)
or (isinstance(auto_connect_streams, dict) and auto_connect_streams.get("stderr", False)),
connect_logging=isinstance(auto_connect_streams, dict) and auto_connect_streams.get("logging", False),
)
# make sure we set our reported to async mode
# we make sure we flush it in self._at_exit
self._reporter.async_enable = True
# if we just created the logger, set default flush period
if not flush_period or flush_period is self.NotSet:
flush_period = float(DevWorker.report_period)
if isinstance(flush_period, (int, float)):
flush_period = int(abs(flush_period))
if flush_period is None or isinstance(flush_period, int):
self._logger.set_flush_period(flush_period)
return self._logger
def _connect_output_model(self, model: OutputModel, name: Optional[str] = None, **kwargs: Any) -> OutputModel:
assert isinstance(model, OutputModel)
model.connect(self, name=name, ignore_remote_overrides=False)
return model
def _save_output_model(self, model: OutputModel) -> None:
"""
Deprecated: Save a reference to the connected output model.
:param model: The connected output model
"""
# deprecated
self._connected_output_model = model
def _handle_ignore_remote_overrides(self, overrides_name: str, ignore_remote_overrides: bool) -> bool:
if self.running_locally() and ignore_remote_overrides:
self.set_parameter(
overrides_name,
True,
description="If True, ignore UI/backend overrides when running remotely."
" Set it to False if you would like the overrides to be applied",
value_type=bool,
)
elif not self.running_locally():
ignore_remote_overrides = self.get_parameter(overrides_name, default=ignore_remote_overrides, cast=True)
return ignore_remote_overrides
def _reconnect_output_model(self) -> None:
"""
Deprecated: If there is a saved connected output model, connect it again.
This is needed if the input model is connected after the output model
is connected, an then we will have to get the model design from the
input model by reconnecting.
"""
# Deprecated:
if self._connected_output_model:
self.connect(self._connected_output_model)
def _connect_input_model(
self,
model: InputModel,
name: Optional[str] = None,
ignore_remote_overrides: bool = False,
) -> InputModel:
assert isinstance(model, InputModel)
# we only allow for an input model to be connected once
# at least until we support multiple input models
# notice that we do not check the task's input model because we allow task reuse and overwrite
# add into comment that we are using this model
# refresh comment
comment = self._reload_field("comment") or self.comment or ""
if not comment.endswith("\n"):
comment += "\n"
comment += "Using model id: {}".format(model.id)
self.set_comment(comment)
model.connect(self, name, ignore_remote_overrides=ignore_remote_overrides)
return model
def _connect_argparse(
self,
parser,
args=None,
namespace=None,
parsed_args=None,
name=None,
ignore_remote_overrides=False,
):
# do not allow argparser to connect to jupyter notebook
# noinspection PyBroadException
try:
if "IPython" in sys.modules:
# noinspection PyPackageRequirements
from IPython import get_ipython # noqa
ip = get_ipython()
if ip is not None and "IPKernelApp" in ip.config:
return parser
except Exception:
pass
if self.is_main_task():
argparser_update_currenttask(self)
if (parser is None or parsed_args is None) and argparser_parseargs_called():
# if we have a parser but nor parsed_args, we need to find the parser
if parser and not parsed_args:
for _parser, _parsed_args in get_argparser_last_args():
if _parser == parser:
parsed_args = _parsed_args
break
else:
# prefer the first argparser (hopefully it is more relevant?!
for _parser, _parsed_args in get_argparser_last_args():
if parser is None:
parser = _parser
if parsed_args is None and parser == _parser:
parsed_args = _parsed_args
if running_remotely() and (self.is_main_task() or self._is_remote_main_task()) and not ignore_remote_overrides:
self._arguments.copy_to_parser(parser, parsed_args)
else:
self._arguments.copy_defaults_from_argparse(parser, args=args, namespace=namespace, parsed_args=parsed_args)
return parser
def _connect_dictionary(
self,
dictionary: dict,
name: Optional[str] = None,
ignore_remote_overrides: bool = False,
) -> dict:
def _update_args_dict(task: Task, config_dict: Dict) -> None:
# noinspection PyProtectedMember
task._arguments.copy_from_dict(flatten_dictionary(config_dict), prefix=name)
def _refresh_args_dict(task: Task, config_proxy_dict: ProxyDictPostWrite) -> None:
# reread from task including newly added keys
# noinspection PyProtectedMember
a_flat_dict = task._arguments.copy_to_dict(flatten_dictionary(config_proxy_dict), prefix=name)
# noinspection PyProtectedMember
nested_dict = config_proxy_dict._to_dict()
config_proxy_dict.clear()
config_proxy_dict._do_update(nested_from_flat_dictionary(nested_dict, a_flat_dict))
def _check_keys(dict_: dict, warning_sent: bool = False) -> None:
if warning_sent:
return
for k, v in dict_.items():
if warning_sent:
return
if not isinstance(k, str):
getLogger().warning(
"Unsupported key of type '{}' found when connecting dictionary. It will be converted to str".format(
type(k)
)
)
warning_sent = True
if isinstance(v, dict):
_check_keys(v, warning_sent)
if (
not running_remotely()
or not (self.is_main_task() or self._is_remote_main_task())
or ignore_remote_overrides
):
_check_keys(dictionary)
flat_dict = {str(k): v for k, v in flatten_dictionary(dictionary).items()}
self._arguments.copy_from_dict(flat_dict, prefix=name)
dictionary = ProxyDictPostWrite(self, _update_args_dict, **dictionary)
else:
flat_dict = flatten_dictionary(dictionary)
flat_dict = self._arguments.copy_to_dict(flat_dict, prefix=name)
dictionary = nested_from_flat_dictionary(dictionary, flat_dict)
dictionary = ProxyDictPostWrite(self, _refresh_args_dict, **dictionary)
return dictionary
def _connect_task_parameters(self, attr_class, name=None, ignore_remote_overrides=False):
ignore_remote_overrides_section = "_ignore_remote_overrides_"
if running_remotely():
ignore_remote_overrides = self.get_parameter(
(name or "General") + "/" + ignore_remote_overrides_section,
default=ignore_remote_overrides,
cast=True,
)
if running_remotely() and (self.is_main_task() or self._is_remote_main_task()) and not ignore_remote_overrides:
parameters = self.get_parameters(cast=True)
if name:
parameters = dict(
(k[len(name) + 1 :], v) for k, v in parameters.items() if k.startswith("{}/".format(name))
)
parameters.pop(ignore_remote_overrides_section, None)
attr_class.update_from_dict(parameters)
else:
parameters_dict = attr_class.to_dict()
if ignore_remote_overrides:
parameters_dict[ignore_remote_overrides_section] = True
self.set_parameters(parameters_dict, __parameters_prefix=name)
return attr_class
def _connect_object(self, an_object, name=None, ignore_remote_overrides=False):
def verify_type(key, value):
if str(key).startswith("_") or not isinstance(value, self._parameters_allowed_types):
return False
# verify everything is json able (i.e. basic types)
try:
json.dumps(value)
return True
except TypeError:
return False
a_dict = {
k: v
for cls_ in getattr(an_object, "__mro__", [an_object])
for k, v in cls_.__dict__.items()
if verify_type(k, v)
}
if running_remotely() and (self.is_main_task() or self._is_remote_main_task()) and not ignore_remote_overrides:
a_dict = self._connect_dictionary(a_dict, name, ignore_remote_overrides=ignore_remote_overrides)
for k, v in a_dict.items():
if getattr(an_object, k, None) != a_dict[k]:
setattr(an_object, k, v)
return an_object
else:
self._connect_dictionary(a_dict, name, ignore_remote_overrides=ignore_remote_overrides)
return an_object
def _dev_mode_stop_task(self, stop_reason: str, pid: Optional[int] = None) -> None:
# make sure we do not get called (by a daemon thread) after at_exit
if self._at_exit_called:
return
self.log.warning("### TASK STOPPED - USER ABORTED - {} ###".format(stop_reason.upper().replace("_", " ")))
self.flush(wait_for_uploads=True)
# if running remotely, we want the daemon to kill us
if self.running_locally():
self.stopped(status_reason="USER ABORTED")
if self._dev_worker:
self._dev_worker.unregister()
# NOTICE! This will end the entire execution tree!
if self.__exit_hook:
self.__exit_hook.remote_user_aborted = True
self._kill_all_child_processes(send_kill=False, pid=pid, allow_kill_calling_pid=False)
time.sleep(2.0)
self._kill_all_child_processes(send_kill=True, pid=pid, allow_kill_calling_pid=True)
os._exit(1) # noqa
@staticmethod
def _kill_all_child_processes(send_kill=False, pid=None, allow_kill_calling_pid=True):
# get current process if pid not provided
current_pid = os.getpid()
kill_ourselves = None
pid = pid or current_pid
try:
parent = psutil.Process(pid)
except psutil.Error:
# could not find parent process id
return
for child in parent.children(recursive=True):
# kill ourselves last (if we need to)
if child.pid == current_pid:
kill_ourselves = child
continue
if send_kill:
child.kill()
else:
child.terminate()
# parent ourselves
if allow_kill_calling_pid or parent.pid != current_pid:
if send_kill:
parent.kill()
else:
parent.terminate()
# kill ourselves if we need to:
if allow_kill_calling_pid and kill_ourselves:
if send_kill:
kill_ourselves.kill()
else:
kill_ourselves.terminate()
def _dev_mode_setup_worker(self):
if (
(running_remotely() and not DEBUG_SIMULATE_REMOTE_TASK.get())
or not self.is_main_task()
or self._at_exit_called
or self._offline_mode
):
return
if self._dev_worker:
return self._dev_worker
self._dev_worker = DevWorker()
self._dev_worker.register(self)
logger = self.get_logger()
flush_period = logger.get_flush_period()
if not flush_period or flush_period > self._dev_worker.report_period:
logger.set_flush_period(self._dev_worker.report_period)
def _wait_for_repo_detection(self, timeout: Optional[float] = None) -> None:
# wait for detection repo sync
if not self._detect_repo_async_thread:
return
with self._repo_detect_lock:
if not self._detect_repo_async_thread:
return
# noinspection PyBroadException
try:
if self._detect_repo_async_thread.is_alive():
# if negative timeout, just kill the thread:
if timeout is not None and timeout < 0:
from .utilities.lowlevel.threads import kill_thread
kill_thread(self._detect_repo_async_thread)
else:
self.log.info("Waiting for repository detection and full package requirement analysis")
self._detect_repo_async_thread.join(timeout=timeout)
# because join has no return value
if self._detect_repo_async_thread.is_alive():
self.log.info(
"Repository and package analysis timed out ({} sec), giving up".format(timeout)
)
# done waiting, kill the thread
from .utilities.lowlevel.threads import kill_thread
kill_thread(self._detect_repo_async_thread)
else:
self.log.info("Finished repository detection and package analysis")
self._detect_repo_async_thread = None
except Exception:
pass
def _summary_artifacts(self) -> None:
# signal artifacts upload, and stop daemon
self._artifacts_manager.stop(wait=True)
# print artifacts summary (if not empty)
if self._artifacts_manager.summary:
self.get_logger().report_text(self._artifacts_manager.summary)
def _at_exit(self) -> None:
# protect sub-process at_exit (should never happen)
if self._at_exit_called and self._at_exit_called != get_current_thread_id():
return
# make sure we do not try to use events, because Python might deadlock itself.
# https://bugs.python.org/issue41606
if self.__is_subprocess():
BackgroundMonitor.set_at_exit_state(True)
# shutdown will clear the main, so we have to store it before.
# is_main = self.is_main_task()
# fix debugger signal in the middle, catch everything
try:
self.__shutdown()
except: # noqa
pass
# In rare cases we might need to forcefully shutdown the process, currently we should avoid it.
# if is_main:
# # we have to forcefully shutdown if we have forked processes, sometimes they will get stuck
# os._exit(self.__exit_hook.exit_code if self.__exit_hook and self.__exit_hook.exit_code else 0)
def __shutdown(self) -> None:
"""
Will happen automatically once we exit code, i.e. atexit
:return:
"""
# protect sub-process at_exit
if self._at_exit_called:
is_sub_process = self.__is_subprocess()
# if we are called twice (signal in the middle of the shutdown),
_nested_shutdown_call = bool(self._at_exit_called == get_current_thread_id())
if _nested_shutdown_call and not is_sub_process:
# if we were called again in the main thread on the main process, let's try again
# make sure we only do this once
self._at_exit_called = True
else:
# make sure we flush stdout, this is the best we can do.
if _nested_shutdown_call and self._logger and is_sub_process:
# noinspection PyProtectedMember
self._logger._close_stdout_handler(wait=True)
self._at_exit_called = True
# if we get here, we should do nothing and leave
return
else:
# from here only a single thread can re-enter
self._at_exit_called = get_current_thread_id()
LoggerRoot.clear_logger_handlers()
# disable lock on signal callbacks, to avoid deadlocks.
if self.__exit_hook and self.__exit_hook.signal is not None:
self.__edit_lock = False
is_sub_process = self.__is_subprocess()
task_status = None
# noinspection PyBroadException
try:
wait_for_uploads = True
# first thing mark task as stopped, so we will not end up with "running" on lost tasks
# if we are running remotely, the daemon will take care of it
wait_for_std_log = True
if (
(not running_remotely() or DEBUG_SIMULATE_REMOTE_TASK.get())
and self.is_main_task()
and not is_sub_process
):
# check if we crashed, ot the signal is not interrupt (manual break)
task_status = ("stopped",)
if self.__exit_hook:
is_exception = self.__exit_hook.exception
# check if we are running inside a debugger
if not is_exception and sys.modules.get("pydevd"):
# noinspection PyBroadException
try:
is_exception = sys.last_type
except Exception:
pass
# check if this is Jupyter interactive session, do not mark as exception
if "IPython" in sys.modules:
is_exception = None
# only if we have an exception (and not ctrl-break) or signal is not SIGTERM / SIGINT
if (
is_exception
and not isinstance(is_exception, KeyboardInterrupt)
and is_exception != KeyboardInterrupt
) or (
not self.__exit_hook.remote_user_aborted
and (self.__exit_hook.signal not in (None, 2, 15) or self.__exit_hook.exit_code)
):
task_status = (
"failed",
(
"Exception {}".format(is_exception)
if is_exception
else "Signal {}".format(self.__exit_hook.signal)
),
)
wait_for_uploads = False
else:
wait_for_uploads = self.__exit_hook.remote_user_aborted or self.__exit_hook.signal is None
if (
not self.__exit_hook.remote_user_aborted
and self.__exit_hook.signal is None
and not is_exception
):
task_status = ("completed",)
else:
task_status = ("stopped",)
# user aborted. do not bother flushing the stdout logs
wait_for_std_log = self.__exit_hook.signal is not None
# wait for repository detection (if we didn't crash)
if wait_for_uploads and self._logger:
# we should print summary here
self._summary_artifacts()
# make sure that if we crashed the thread we are not waiting forever
if not is_sub_process:
self._wait_for_repo_detection(timeout=10.0)
# kill the repo thread (negative timeout, do not wait), if it hasn't finished yet.
if not is_sub_process:
self._wait_for_repo_detection(timeout=-1)
# wait for uploads
print_done_waiting = False
if wait_for_uploads and (
BackendModel.get_num_results() > 0 or (self.__reporter and self.__reporter.events_waiting())
):
self.log.info("Waiting to finish uploads")
print_done_waiting = True
# from here, do not send log in background thread
if wait_for_uploads:
self.flush(wait_for_uploads=True)
# wait until the reporter flush everything
if self.__reporter:
self.__reporter.stop()
if self.is_main_task():
# notice: this will close the reporting for all the Tasks in the system
Metrics.close_async_threads()
# notice: this will close the jupyter monitoring
ScriptInfo.close()
if self.is_main_task():
# noinspection PyBroadException
try:
from .storage.helper import StorageHelper
StorageHelper.close_async_threads()
except Exception:
pass
if print_done_waiting:
self.log.info("Finished uploading")
# elif self._logger:
# # noinspection PyProtectedMember
# self._logger._flush_stdout_handler()
# from here, do not check worker status
if self._dev_worker:
self._dev_worker.unregister()
self._dev_worker = None
# stop resource monitoring
if self._resource_monitor:
self._resource_monitor.stop()
self._resource_monitor = None
if self._logger:
self._logger.set_flush_period(None)
# noinspection PyProtectedMember
self._logger._close_stdout_handler(wait=wait_for_uploads or wait_for_std_log)
if not is_sub_process:
# change task status
if not task_status:
pass
elif task_status[0] == "failed":
self.mark_failed(status_reason=task_status[1])
elif task_status[0] == "completed":
self.set_progress(100)
self.mark_completed()
elif task_status[0] == "stopped":
self.stopped()
# this is so in theory we can close a main task and start a new one
if self.is_main_task():
Task.__main_task = None
Task.__forked_proc_main_pid = None
Task.__update_master_pid_task(task=None)
except Exception:
# make sure we do not interrupt the exit process
pass
# make sure we store last task state
if self._offline_mode and not is_sub_process:
# noinspection PyBroadException
try:
# make sure the state of the offline data is saved
self._edit()
# create zip file
offline_folder = self.get_offline_mode_folder()
zip_file = offline_folder.as_posix() + ".zip"
with ZipFile(zip_file, "w", allowZip64=True, compression=ZIP_DEFLATED) as zf:
for filename in offline_folder.rglob("*"):
if filename.is_file():
relative_file_name = filename.relative_to(offline_folder).as_posix()
zf.write(filename.as_posix(), arcname=relative_file_name)
print("ClearML Task: Offline session stored in {}".format(zip_file))
except Exception:
pass
# delete locking object (lock file)
if self._edit_lock:
# noinspection PyBroadException
try:
del self.__edit_lock
except Exception:
pass
self._edit_lock = None
# make sure no one will re-enter the shutdown method
self._at_exit_called = True
if not is_sub_process and BackgroundMonitor.is_subprocess_enabled():
BackgroundMonitor.wait_for_sub_process(self)
# we are done
return
@classmethod
def _remove_exception_hooks(cls) -> None:
if cls.__exit_hook:
cls.__exit_hook.remove_exception_hooks()
@classmethod
def _remove_signal_hooks(cls) -> None:
if cls.__exit_hook:
cls.__exit_hook.remove_signal_hooks()
@classmethod
def __register_at_exit(cls, exit_callback: Callable) -> None:
if cls.__exit_hook is None:
# noinspection PyBroadException
try:
cls.__exit_hook = ExitHooks(exit_callback)
cls.__exit_hook.hook()
except Exception:
cls.__exit_hook = None
else:
cls.__exit_hook.update_callback(exit_callback)
@classmethod
def __get_task(
cls,
task_id: Optional[str] = None,
project_name: Optional[str] = None,
task_name: Optional[str] = None,
include_archived: bool = True,
tags: Optional[Sequence[str]] = None,
task_filter: Optional[dict] = None,
) -> TaskInstance:
if task_id:
return cls(private=cls.__create_protection, task_id=task_id, log_to_backend=False)
if project_name:
res = cls._send(
cls._get_default_session(),
projects.GetAllRequest(name=exact_match_regex(project_name)),
)
project = get_single_result(entity="project", query=project_name, results=res.response.projects)
else:
project = None
# get default session, before trying to access tasks.Task so that we do not create two sessions.
session = cls._get_default_session()
system_tags = "system_tags" if hasattr(tasks.Task, "system_tags") else "tags"
task_filter = task_filter or {}
if not include_archived:
task_filter["system_tags"] = (task_filter.get("system_tags") or []) + ["-{}".format(cls.archived_tag)]
if tags:
task_filter["tags"] = (task_filter.get("tags") or []) + list(tags)
res = cls._send(
session,
tasks.GetAllRequest(
project=[project.id] if project else None,
name=exact_match_regex(task_name) if task_name else None,
only_fields=["id", "name", "last_update", system_tags],
**task_filter,
),
)
res_tasks = res.response.tasks
# if we have more than one result, filter out the 'archived' results
# notice that if we only have one result we do get the archived one as well.
if len(res_tasks) > 1:
filtered_tasks = [
t
for t in res_tasks
if not getattr(t, system_tags, None) or cls.archived_tag not in getattr(t, system_tags, None)
]
# if we did not filter everything (otherwise we have only archived tasks, so we return them)
if filtered_tasks:
res_tasks = filtered_tasks
task = get_single_result(
entity="task",
query={
k: v
for k, v in dict(
project_name=project_name,
task_name=task_name,
tags=tags,
include_archived=include_archived,
task_filter=task_filter,
).items()
if v
},
results=res_tasks,
raise_on_error=False,
)
if not task:
# should never happen
return None # noqa
return cls(
private=cls.__create_protection,
task_id=task.id,
log_to_backend=False,
)
@classmethod
def __get_tasks(
cls,
task_ids: Optional[Sequence[str]] = None,
project_name: Optional[Union[Sequence[str], str]] = None,
task_name: Optional[str] = None,
**kwargs: Any,
) -> List["Task"]:
if task_ids:
if isinstance(task_ids, six.string_types):
task_ids = [task_ids]
return [
cls(
private=cls.__create_protection,
task_id=task_id,
log_to_backend=False,
)
for task_id in task_ids
]
queried_tasks = cls._query_tasks(
project_name=project_name, task_name=task_name, fetch_only_first_page=True, **kwargs
)
if len(queried_tasks) == 500:
LoggerRoot.get_base_logger().warning(
"Too many requests when calling Task.get_tasks()."
" Returning only the first 500 results."
" Use Task.query_tasks() to fetch all task IDs"
)
return [cls(private=cls.__create_protection, task_id=task.id, log_to_backend=False) for task in queried_tasks]
@classmethod
def _query_tasks(
cls,
task_ids: Optional[Union[Sequence[str], str]] = None,
project_name: Optional[Union[Sequence[str], str]] = None,
task_name: Optional[str] = None,
fetch_only_first_page: bool = False,
exact_match_regex_flag: bool = True,
**kwargs: Any,
) -> List["Task"]:
res = None
if not task_ids:
task_ids = None
elif isinstance(task_ids, six.string_types):
task_ids = [task_ids]
if project_name and isinstance(project_name, str):
project_names = [project_name]
else:
project_names = project_name
project_ids = []
projects_not_found = []
if project_names:
for name in project_names:
aux_kwargs = {}
if kwargs.get("_allow_extra_fields_"):
aux_kwargs["_allow_extra_fields_"] = True
aux_kwargs["search_hidden"] = kwargs.get("search_hidden", False)
res = cls._send(
cls._get_default_session(),
projects.GetAllRequest(
name=(exact_match_regex(name) if exact_match_regex_flag else name), **aux_kwargs
),
)
if res.response and res.response.projects:
project_ids.extend([project.id for project in res.response.projects])
else:
projects_not_found.append(name)
if projects_not_found:
# If any of the given project names does not exist, fire off a warning
LoggerRoot.get_base_logger().warning(
"No projects were found with name(s): {}".format(", ".join(projects_not_found))
)
if not project_ids:
# If not a single project exists or was found, return empty right away
return []
session = cls._get_default_session()
system_tags = "system_tags" if hasattr(tasks.Task, "system_tags") else "tags"
only_fields = ["id", "name", "last_update", system_tags]
if kwargs and kwargs.get("only_fields"):
only_fields = list(set(kwargs.pop("only_fields")) | set(only_fields))
# if we have specific page to look for, we should only get the requested one
if not fetch_only_first_page and kwargs and "page" in kwargs:
fetch_only_first_page = True
ret_tasks = []
page = -1
page_size = 500
while page == -1 or (not fetch_only_first_page and res and len(res.response.tasks) == page_size):
page += 1
# work on a copy and make sure we override all fields with ours
request_kwargs = dict(
id=task_ids,
project=project_ids if project_ids else kwargs.pop("project", None),
name=task_name if task_name else kwargs.pop("name", None),
only_fields=only_fields,
page=page,
page_size=page_size,
)
# make sure we always override with the kwargs (specifically page selection / page_size)
request_kwargs.update(kwargs or {})
res = cls._send(
session,
tasks.GetAllRequest(**request_kwargs),
)
ret_tasks.extend(res.response.tasks)
return ret_tasks
@classmethod
def _wait_for_deferred(cls, task: Optional["Task"]) -> None:
"""
Make sure the task object deferred `Task.init` is completed.
Accessing any of the `task` object's property will ensure the Task.init call was also complete
This is an internal utility function
:param task: Optional deferred Task object as returned form Task.init
"""
if not task:
return
# force deferred init to complete
task.id # noqa
@classmethod
def __get_hash_key(cls, *args: Any) -> str:
def normalize(x: Any) -> str:
return "<{}>".format(x) if x is not None else ""
return ":".join(map(normalize, args))
@classmethod
def __get_last_used_task_id(cls, default_project_name, default_task_name, default_task_type):
hash_key = cls.__get_hash_key(
cls._get_api_server(),
default_project_name,
default_task_name,
default_task_type,
)
# check if we have a cached task_id we can reuse
# it must be from within the last 24h and with the same project/name/type
task_sessions = SessionCache.load_dict(str(cls))
task_data = task_sessions.get(hash_key)
if task_data is None:
return None
try:
task_data["type"] = cls.TaskTypes(task_data["type"])
except (ValueError, KeyError):
LoggerRoot.get_base_logger().warning(
"Corrupted session cache entry: {}. "
"Unsupported task type: {}"
"Creating a new task.".format(hash_key, task_data["type"]),
)
return None
return task_data
@classmethod
def __update_last_used_task_id(cls, default_project_name, default_task_name, default_task_type, task_id):
hash_key = cls.__get_hash_key(
cls._get_api_server(),
default_project_name,
default_task_name,
default_task_type,
)
task_id = str(task_id)
# update task session cache
task_sessions = SessionCache.load_dict(str(cls))
last_task_session = {
"time": time.time(),
"project": default_project_name,
"name": default_task_name,
"type": default_task_type,
"id": task_id,
}
# remove stale sessions
for k in list(task_sessions.keys()):
if (time.time() - task_sessions[k].get("time", 0)) > 60 * 60 * cls.__task_id_reuse_time_window_in_hours:
task_sessions.pop(k)
# update current session
task_sessions[hash_key] = last_task_session
# store
SessionCache.store_dict(str(cls), task_sessions)
@classmethod
def __task_timed_out(cls, task_data):
return (
task_data
and task_data.get("id")
and task_data.get("time")
and (time.time() - task_data.get("time")) > (60 * 60 * cls.__task_id_reuse_time_window_in_hours)
)
@classmethod
def __get_task_api_obj(cls, task_id: str, only_fields: Optional[List[str]] = None) -> Optional["tasks.Task"]:
if not task_id or cls._offline_mode:
return None
all_tasks = cls._send(
cls._get_default_session(),
tasks.GetAllRequest(id=[task_id], only_fields=only_fields),
).response.tasks
# The task may not exist in environment changes
if not all_tasks:
return None
return all_tasks[0]
@classmethod
def __task_is_relevant(cls, task_data: Mapping[str, Any]) -> bool:
"""
Check that a cached task is relevant for reuse.
A task is relevant for reuse if:
1. It is not timed out i.e it was last use in the previous 24 hours.
2. It's name, project and type match the data in the server, so not
to override user changes made by using the UI.
:param task_data: A mapping from 'id', 'name', 'project', 'type' keys
to the task's values, as saved in the cache.
:return: True, if the task is relevant for reuse. False, if not.
"""
if not task_data:
return False
if cls.__task_timed_out(task_data):
return False
task_id = task_data.get("id")
if not task_id:
return False
# noinspection PyBroadException
try:
task = cls.__get_task_api_obj(task_id, ("id", "name", "project", "type"))
except Exception:
task = None
if task is None:
return False
project_name = None
if task.project:
# noinspection PyBroadException
try:
project = cls._send(
cls._get_default_session(),
projects.GetByIdRequest(project=task.project),
).response.project
if project:
project_name = project.name
except Exception:
pass
if (
task_data.get("type")
and task_data.get("type") not in (cls.TaskTypes.training, cls.TaskTypes.testing)
and not Session.check_min_api_version(2.8)
):
print(
'WARNING: Changing task type to "{}" : '
'clearml-server does not support task type "{}", '
"please upgrade clearml-server.".format(cls.TaskTypes.training, task_data["type"].value)
)
task_data["type"] = cls.TaskTypes.training
compares = (
(task.name, "name"),
(project_name, "project"),
(task.type, "type"),
)
# compare after casting to string to avoid enum instance issues
# remember we might have replaced the api version by now, so enums are different
return all(
six.text_type(server_data) == six.text_type(task_data.get(task_data_key))
for server_data, task_data_key in compares
)
@classmethod
def __close_timed_out_task(cls, task_data: Optional[Dict[str, Any]]) -> bool:
if not task_data:
return False
task = cls.__get_task_api_obj(task_data.get("id"), ("id", "status"))
if task is None:
return False
stopped_statuses = (
cls.TaskStatusEnum.stopped,
cls.TaskStatusEnum.published,
cls.TaskStatusEnum.publishing,
cls.TaskStatusEnum.closed,
cls.TaskStatusEnum.failed,
cls.TaskStatusEnum.completed,
)
if task.status not in stopped_statuses:
cls._send(
cls._get_default_session(),
tasks.StoppedRequest(
task=task.id,
force=True,
status_message="Stopped timed out development task",
),
)
return True
return False
@classmethod
def __add_model_wildcards(
cls,
auto_connect_frameworks: Union[Dict[str, Union[str, List[str], Tuple[str]]], Any],
) -> None:
if isinstance(auto_connect_frameworks, dict):
for k, v in auto_connect_frameworks.items():
if isinstance(v, str):
v = [v]
if isinstance(v, (list, tuple)):
WeightsFileHandler.model_wildcards[k] = [str(i) for i in v]
def callback(_: Any, model_info: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]:
if not model_info:
return None
parents = Framework.get_framework_parents(model_info.framework)
wildcards = []
for parent in parents:
if WeightsFileHandler.model_wildcards.get(parent):
wildcards.extend(WeightsFileHandler.model_wildcards[parent])
if not wildcards:
return model_info
if not matches_any_wildcard(model_info.local_model_path, wildcards):
return None
return model_info
WeightsFileHandler.add_pre_callback(callback)
def __getstate__(self) -> dict:
return {
"main": self.is_main_task(),
"id": self.id,
"offline": self.is_offline(),
}
def __setstate__(self, state):
if state["main"] and not self.__main_task:
Task.__forked_proc_main_pid = None
Task.__update_master_pid_task(task=state["id"])
if state["offline"]:
Task.set_offline(offline_mode=state["offline"])
task = (
Task.init(
continue_last_task=state["id"],
auto_connect_frameworks={"detect_repository": False},
)
if state["main"]
else Task.get_task(task_id=state["id"])
)
self.__dict__ = task.__dict__
@property
def resource_monitor(self) -> None:
return self._resource_monitor
| Task |
python | allegroai__clearml | clearml/backend_api/services/v2_9/tasks.py | {
"start": 322670,
"end": 324298
} | class ____(Response):
"""
Response of tasks.validate endpoint.
"""
_service = "tasks"
_action = "validate"
_version = "2.9"
_schema = {"additionalProperties": False, "definitions": {}, "type": "object"}
response_mapping = {
GetByIdRequest: GetByIdResponse,
GetAllRequest: GetAllResponse,
GetTypesRequest: GetTypesResponse,
CloneRequest: CloneResponse,
CreateRequest: CreateResponse,
ValidateRequest: ValidateResponse,
UpdateRequest: UpdateResponse,
UpdateBatchRequest: UpdateBatchResponse,
EditRequest: EditResponse,
ResetRequest: ResetResponse,
DeleteRequest: DeleteResponse,
StartedRequest: StartedResponse,
StopRequest: StopResponse,
StoppedRequest: StoppedResponse,
FailedRequest: FailedResponse,
CloseRequest: CloseResponse,
PublishRequest: PublishResponse,
EnqueueRequest: EnqueueResponse,
DequeueRequest: DequeueResponse,
SetRequirementsRequest: SetRequirementsResponse,
CompletedRequest: CompletedResponse,
PingRequest: PingResponse,
AddOrUpdateArtifactsRequest: AddOrUpdateArtifactsResponse,
MakePublicRequest: MakePublicResponse,
MakePrivateRequest: MakePrivateResponse,
GetHyperParamsRequest: GetHyperParamsResponse,
EditHyperParamsRequest: EditHyperParamsResponse,
DeleteHyperParamsRequest: DeleteHyperParamsResponse,
GetConfigurationsRequest: GetConfigurationsResponse,
GetConfigurationNamesRequest: GetConfigurationNamesResponse,
EditConfigurationRequest: EditConfigurationResponse,
DeleteConfigurationRequest: DeleteConfigurationResponse,
}
| ValidateResponse |
python | scipy__scipy | scipy/stats/tests/test_stats.py | {
"start": 288089,
"end": 293095
} | class ____:
def pmean_reference(a, p):
return (np.sum(a**p) / a.size)**(1/p)
def wpmean_reference(a, p, weights):
return (np.sum(weights * a**p) / np.sum(weights))**(1/p)
def test_bad_exponent(self, xp):
with pytest.raises(ValueError, match='Power mean only defined for'):
stats.pmean(xp.asarray([1, 2, 3]), xp.asarray([0]))
def test_1d(self, xp):
a, p = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100], 3.5
desired = TestPMean.pmean_reference(np.array(a), p)
check_equal_pmean(a, p, desired, xp=xp)
a, p = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100], -2.5
desired = TestPMean.pmean_reference(np.array(a), p)
check_equal_pmean(a, p, desired, xp=xp)
a, p = [1, 2, 3, 4], 2
desired = np.sqrt((1**2 + 2**2 + 3**2 + 4**2) / 4)
check_equal_pmean(a, p, desired, xp=xp)
@pytest.mark.filterwarnings("ignore:invalid value encountered:RuntimeWarning:dask")
@pytest.mark.filterwarnings("ignore:divide by zero encountered:RuntimeWarning:dask")
def test_1d_with_zero(self, xp):
a, p = np.array([1, 0]), -1
desired = 0.0
check_equal_pmean(a, p, desired, rtol=0.0, xp=xp)
def test_1d_with_negative_value(self, xp):
a, p = np.array([1, 0, -1]), 1.23
message = "The power mean is only defined..."
with pytest.warns(RuntimeWarning, match=message):
check_equal_pmean(a, p, xp.nan, xp=xp)
@pytest.mark.parametrize(
("a", "p"),
[([[10, 20], [50, 60], [90, 100]], -0.5),
(np.array([[10, 20], [50, 60], [90, 100]]), 0.5)]
)
def test_2d_axisnone(self, a, p, xp):
desired = TestPMean.pmean_reference(np.array(a), p)
check_equal_pmean(a, p, desired, xp=xp)
@pytest.mark.parametrize(
("a", "p"),
[([[10, 20, 30, 40], [50, 60, 70, 80], [90, 100, 110, 120]], -0.5),
([[10, 0, 30, 40], [50, 60, 70, 80], [90, 100, 110, 120]], 0.5)]
)
def test_2d_axis0(self, a, p, xp):
desired = [
TestPMean.pmean_reference(
np.array([a[i][j] for i in range(len(a))]), p
)
for j in range(len(a[0]))
]
check_equal_pmean(a, p, desired, axis=0, xp=xp)
@pytest.mark.parametrize(
("a", "p"),
[([[10, 20, 30, 40], [50, 60, 70, 80], [90, 100, 110, 120]], -0.5),
([[10, 0, 30, 40], [50, 60, 70, 80], [90, 100, 110, 120]], 0.5)]
)
def test_2d_axis1(self, a, p, xp):
desired = [TestPMean.pmean_reference(np.array(a_), p) for a_ in a]
check_equal_pmean(a, p, desired, axis=1, xp=xp)
def test_weights_1d(self, xp):
a, p = [2, 10, 6], -1.23456789
weights = [10, 5, 3]
desired = TestPMean.wpmean_reference(np.array(a), p, weights)
check_equal_pmean(a, p, desired, weights=weights, rtol=1e-5, xp=xp)
@skip_xp_backends(
np_only=True,
reason='array-likes only supported for NumPy backend',
)
def test_weights_1d_list(self, xp):
a, p = [2, 10, 6], -1.23456789
weights = [10, 5, 3]
desired = TestPMean.wpmean_reference(np.array(a), p, weights)
# all the other tests use `check_equal_pmean`, which now converts
# the input to an xp-array before calling `pmean`. This time, check
# that the function still accepts the lists of ints.
res = stats.pmean(a, p, weights=weights)
xp_assert_close(res, np.asarray(desired), rtol=1e-5)
@skip_xp_invalid_arg
def test_weights_masked_1d_array(self, xp):
a, p = np.array([2, 10, 6, 42]), 1
weights = np.ma.array([10, 5, 3, 42], mask=[0, 0, 0, 1])
desired = np.average(a, weights=weights)
xp = np.ma # check_equal_pmean uses xp.asarray; this will preserve the mask
check_equal_pmean(a, p, desired, weights=weights, rtol=1e-5,
dtype=np.float64, xp=xp)
@pytest.mark.parametrize(
("axis", "fun_name", "p"),
[(None, "wpmean_reference", 9.87654321),
(0, "gmean", 0),
(1, "hmean", -1)]
)
def test_weights_2d(self, axis, fun_name, p, xp):
if fun_name == 'wpmean_reference':
def fun(a, axis, weights):
return TestPMean.wpmean_reference(a, p, weights)
else:
fun = getattr(stats, fun_name)
a = np.array([[2, 5], [10, 5], [6, 5]])
weights = np.array([[10, 1], [5, 1], [3, 1]])
desired = fun(a, axis=axis, weights=weights)
check_equal_pmean(a, p, desired, axis=axis, weights=weights, rtol=1e-5, xp=xp)
def test_infinite_p_gh23111(self):
# gh-23111 reported that `pmean` didn't work properly with infinite `p`;
# check that this raises an appropriate error message
message = "Power mean only implemented for finite `p`"
with pytest.raises(NotImplementedError, match=message):
stats.pmean([2], np.inf)
@make_xp_test_case(stats.gstd)
| TestPMean |
python | huggingface__transformers | src/transformers/models/time_series_transformer/modeling_time_series_transformer.py | {
"start": 2973,
"end": 4729
} | class ____(nn.Module):
"""
Standardize features by calculating the mean and scaling along the first dimension, and then normalizes it by
subtracting from the mean and dividing by the standard deviation.
"""
def __init__(self, config: TimeSeriesTransformerConfig):
super().__init__()
self.dim = config.scaling_dim if hasattr(config, "scaling_dim") else 1
self.keepdim = config.keepdim if hasattr(config, "keepdim") else True
self.minimum_scale = config.minimum_scale if hasattr(config, "minimum_scale") else 1e-5
def forward(
self, data: torch.Tensor, observed_indicator: torch.Tensor
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""
Parameters:
data (`torch.Tensor` of shape `(batch_size, sequence_length, num_input_channels)`):
input for Batch norm calculation
observed_indicator (`torch.BoolTensor` of shape `(batch_size, sequence_length, num_input_channels)`):
Calculating the scale on the observed indicator.
Returns:
tuple of `torch.Tensor` of shapes
(`(batch_size, sequence_length, num_input_channels)`,`(batch_size, 1, num_input_channels)`,
`(batch_size, 1, num_input_channels)`)
"""
denominator = observed_indicator.sum(self.dim, keepdim=self.keepdim)
denominator = denominator.clamp_min(1.0)
loc = (data * observed_indicator).sum(self.dim, keepdim=self.keepdim) / denominator
variance = (((data - loc) * observed_indicator) ** 2).sum(self.dim, keepdim=self.keepdim) / denominator
scale = torch.sqrt(variance + self.minimum_scale)
return (data - loc) / scale, loc, scale
| TimeSeriesStdScaler |
python | airbytehq__airbyte | airbyte-ci/connectors/metadata_service/orchestrator/orchestrator/logging/publish_connector_lifecycle.py | {
"start": 1082,
"end": 3360
} | class ____:
"""
This class is used to log the lifecycle of a publishing a connector to the registries.
It is used to log to the logger and slack (if enabled).
This is nessesary as this lifecycle is not a single job, asset, resource, schedule, or sensor.
"""
@staticmethod
def stage_to_log_level(stage_status: StageStatus) -> str:
if stage_status == StageStatus.FAILED:
return "error"
else:
return "info"
def _commit_link(commit_sha: str) -> str:
"""Create a markdown link to a commit."""
commit_url = f"{REPO_URL}/commit/{commit_sha}"
return f"\ncommit: <{commit_url}|{commit_sha}>"
def _user_mention(user_identifier: str) -> str:
"""Create a markdown link to a user."""
return f"\nauthor: {user_identifier}"
@staticmethod
def create_log_message(
lifecycle_stage: PublishConnectorLifecycleStage,
stage_status: StageStatus,
message: str,
commit_sha: str = None,
user_identifier: str = None,
) -> str:
emoji = stage_status.to_emoji()
final_message = f"*{emoji} _{lifecycle_stage}_ {stage_status}*:\n{message}"
if user_identifier:
final_message += PublishConnectorLifecycle._user_mention(user_identifier)
if commit_sha:
final_message += PublishConnectorLifecycle._commit_link(commit_sha)
return final_message
@staticmethod
def log(
context: OpExecutionContext,
lifecycle_stage: PublishConnectorLifecycleStage,
stage_status: StageStatus,
message: str,
commit_sha: str = None,
user_identifier: str = None,
):
"""Publish a connector notification log to logger and slack (if enabled)."""
message = PublishConnectorLifecycle.create_log_message(lifecycle_stage, stage_status, message, commit_sha, user_identifier)
level = PublishConnectorLifecycle.stage_to_log_level(stage_status)
log_method = getattr(context.log, level)
log_method(message)
channel = os.getenv("PUBLISH_UPDATE_CHANNEL")
if channel:
slack_message = f"🤖 {message}"
send_slack_message(context, channel, slack_message)
| PublishConnectorLifecycle |
python | HypothesisWorks__hypothesis | hypothesis-python/src/hypothesis/internal/conjecture/data.py | {
"start": 3340,
"end": 3536
} | class ____(IntEnum):
OVERRUN = 0
INVALID = 1
VALID = 2
INTERESTING = 3
def __repr__(self) -> str:
return f"Status.{self.name}"
@dataclass(slots=True, frozen=True)
| Status |
python | numba__numba | numba/cuda/vectorizers.py | {
"start": 7246,
"end": 8177
} | class ____(deviceufunc.DeviceVectorize):
def _compile_core(self, sig):
cudevfn = cuda.jit(sig, device=True, inline=True)(self.pyfunc)
return cudevfn, cudevfn.overloads[sig.args].signature.return_type
def _get_globals(self, corefn):
glbl = self.pyfunc.__globals__.copy()
glbl.update({'__cuda__': cuda,
'__core__': corefn})
return glbl
def _compile_kernel(self, fnobj, sig):
return cuda.jit(fnobj)
def build_ufunc(self):
return CUDAUFuncDispatcher(self.kernelmap, self.pyfunc)
@property
def _kernel_template(self):
return vectorizer_stager_source
# ------------------------------------------------------------------------------
# Generalized CUDA ufuncs
_gufunc_stager_source = '''
def __gufunc_{name}({args}):
__tid__ = __cuda__.grid(1)
if __tid__ < {checkedarg}:
__core__({argitems})
'''
| CUDAVectorize |
python | walkccc__LeetCode | solutions/275. H-Index II/275.py | {
"start": 0,
"end": 201
} | class ____:
def hIndex(self, citations: list[int]) -> int:
n = len(citations)
return n - bisect.bisect_left(range(n), n,
key=lambda m: citations[m] + m)
| Solution |
python | spyder-ide__spyder | spyder/plugins/findinfiles/plugin.py | {
"start": 940,
"end": 7146
} | class ____(SpyderDockablePlugin):
"""
Find in files DockWidget.
"""
NAME = 'find_in_files'
REQUIRES = []
OPTIONAL = [
Plugins.Editor,
Plugins.Projects,
Plugins.MainMenu,
Plugins.WorkingDirectory,
]
TABIFY = [Plugins.VariableExplorer]
WIDGET_CLASS = FindInFilesWidget
CONF_SECTION = NAME
CONF_FILE = False
RAISE_AND_FOCUS = True
# --- SpyderDocakblePlugin API
# ------------------------------------------------------------------------
@staticmethod
def get_name():
return _("Find")
@staticmethod
def get_description():
return _("Search for text patterns in files.")
@classmethod
def get_icon(cls):
return cls.create_icon('findf')
def on_initialize(self):
self.create_action(
FindInFilesActions.FindInFiles,
text=_("Search text in files..."),
tip=_("Search text in multiple files with the Find pane"),
triggered=self.find,
register_shortcut=True,
context=Qt.WindowShortcut
)
self.refresh_search_directory()
@on_plugin_available(plugin=Plugins.Editor)
def on_editor_available(self):
widget = self.get_widget()
editor = self.get_plugin(Plugins.Editor)
widget.sig_edit_goto_requested.connect(
lambda filename, lineno, search_text, colno, colend: editor.load(
filename, lineno, start_column=colno, end_column=colend))
editor.sig_file_opened_closed_or_updated.connect(
self.set_current_opened_file)
@on_plugin_available(plugin=Plugins.Projects)
def on_projects_available(self):
projects = self.get_plugin(Plugins.Projects)
projects.sig_project_loaded.connect(self.set_project_path)
projects.sig_project_closed.connect(self.unset_project_path)
@on_plugin_available(plugin=Plugins.MainMenu)
def on_main_menu_available(self):
mainmenu = self.get_plugin(Plugins.MainMenu)
findinfiles_action = self.get_action(FindInFilesActions.FindInFiles)
mainmenu.add_item_to_application_menu(
findinfiles_action,
menu_id=ApplicationMenus.Search,
section=SearchMenuSections.FindInFiles
)
@on_plugin_available(plugin=Plugins.WorkingDirectory)
def on_working_directory_available(self):
working_directory = self.get_plugin(Plugins.WorkingDirectory)
working_directory.sig_current_directory_changed.connect(
self.refresh_search_directory
)
@on_plugin_teardown(plugin=Plugins.Editor)
def on_editor_teardown(self):
widget = self.get_widget()
editor = self.get_plugin(Plugins.Editor)
widget.sig_edit_goto_requested.disconnect()
editor.sig_file_opened_closed_or_updated.disconnect(
self.set_current_opened_file)
@on_plugin_teardown(plugin=Plugins.Projects)
def on_projects_teardon_plugin_teardown(self):
projects = self.get_plugin(Plugins.Projects)
projects.sig_project_loaded.disconnect(self.set_project_path)
projects.sig_project_closed.disconnect(self.unset_project_path)
@on_plugin_teardown(plugin=Plugins.MainMenu)
def on_main_menu_teardown(self):
mainmenu = self.get_plugin(Plugins.MainMenu)
mainmenu.remove_item_from_application_menu(
FindInFilesActions.FindInFiles,
menu_id=ApplicationMenus.Search,
)
@on_plugin_teardown(plugin=Plugins.WorkingDirectory)
def on_working_directory_teardown(self):
working_directory = self.get_plugin(Plugins.WorkingDirectory)
working_directory.sig_current_directory_changed.disconnect(
self.refresh_search_directory
)
def on_close(self, cancelable=False):
self.get_widget()._update_options()
if self.get_widget().running:
self.get_widget()._stop_and_reset_thread(ignore_results=True)
return True
# --- Public API
# ------------------------------------------------------------------------
def refresh_search_directory(self):
"""
Refresh search directory.
"""
self.get_widget().set_directory(getcwd_or_home())
def set_current_opened_file(self, path, _language):
"""
Set path of current opened file in editor.
Parameters
----------
path: str
Path of editor file.
"""
self.get_widget().set_file_path(path)
def set_project_path(self, path):
"""
Set and refresh current project path.
Parameters
----------
path: str
Opened project path.
"""
self.get_widget().set_project_path(path)
def set_max_results(self, value=None):
"""
Set maximum amount of results to add to the result browser.
Parameters
----------
value: int, optional
Number of results. If None an input dialog will be used.
Default is None.
"""
self.get_widget().set_max_results(value)
def unset_project_path(self):
"""
Unset current project path.
"""
self.get_widget().disable_project_search()
def find(self):
"""
Search text in multiple files.
Notes
-----
Find in files using the currently selected text of the focused widget.
"""
focus_widget = QApplication.focusWidget()
text = ''
try:
if focus_widget.has_selected_text():
text = focus_widget.get_selected_text()
except AttributeError:
# This is not a text widget deriving from TextEditBaseWidget
pass
self.switch_to_plugin()
widget = self.get_widget()
if text:
widget.set_search_text(text)
widget.find()
def test():
import sys
from spyder.config.manager import CONF
from spyder.utils.qthelpers import qapplication
app = qapplication()
widget = FindInFiles(None, CONF)
widget.show()
sys.exit(app.exec_())
if __name__ == '__main__':
test()
| FindInFiles |
python | google__flatbuffers | grpc/examples/python/greeter/greeter_grpc.fb.py | {
"start": 179,
"end": 529
} | class ____(object):
"""Interface exported by the server."""
def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Channel.
"""
self.SayHello = channel.unary_unary(method='/models.Greeter/SayHello')
self.SayManyHellos = channel.unary_stream(
method='/models.Greeter/SayManyHellos'
)
| GreeterStub |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/exc.py | {
"start": 12848,
"end": 12976
} | class ____(InvalidRequestError):
"""SQL was attempted without a database connection to execute it on."""
| UnboundExecutionError |
python | kamyu104__LeetCode-Solutions | Python/binary-tree-level-order-traversal.py | {
"start": 154,
"end": 747
} | class ____(object):
# @param root, a tree node
# @return a list of lists of integers
def levelOrder(self, root):
if root is None:
return []
result, current = [], [root]
while current:
next_level, vals = [], []
for node in current:
vals.append(node.val)
if node.left:
next_level.append(node.left)
if node.right:
next_level.append(node.right)
current = next_level
result.append(vals)
return result
| Solution |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/syntax_errors/return_outside_function.py | {
"start": 134,
"end": 215
} | class ____:
return 1 # error
def f():
class C:
return 1 # error
| C |
python | imageio__imageio | imageio/plugins/_swf.py | {
"start": 9461,
"end": 9666
} | class ____(ControlTag):
def __init__(self):
ControlTag.__init__(self)
self.tagtype = 69
def process_tag(self):
self.bytes = "\x00".encode("ascii") * (1 + 3)
| FileAttributesTag |
python | pandas-dev__pandas | pandas/tests/frame/methods/test_set_index.py | {
"start": 1469,
"end": 19586
} | class ____:
def test_set_index_multiindex(self):
# segfault in GH#3308
d = {"t1": [2, 2.5, 3], "t2": [4, 5, 6]}
df = DataFrame(d)
tuples = [(0, 1), (0, 2), (1, 2)]
df["tuples"] = tuples
index = MultiIndex.from_tuples(df["tuples"])
# it works!
df.set_index(index)
def test_set_index_empty_column(self):
# GH#1971
df = DataFrame(
[
{"a": 1, "p": 0},
{"a": 2, "m": 10},
{"a": 3, "m": 11, "p": 20},
{"a": 4, "m": 12, "p": 21},
],
columns=["a", "m", "p", "x"],
)
result = df.set_index(["a", "x"])
expected = df[["m", "p"]]
expected.index = MultiIndex.from_arrays([df["a"], df["x"]], names=["a", "x"])
tm.assert_frame_equal(result, expected)
def test_set_index_empty_dataframe(self):
# GH#38419
df1 = DataFrame(
{"a": Series(dtype="datetime64[ns]"), "b": Series(dtype="int64"), "c": []}
)
df2 = df1.set_index(["a", "b"])
result = df2.index.to_frame().dtypes
expected = df1[["a", "b"]].dtypes
tm.assert_series_equal(result, expected)
def test_set_index_multiindexcolumns(self):
columns = MultiIndex.from_tuples([("foo", 1), ("foo", 2), ("bar", 1)])
df = DataFrame(
np.random.default_rng(2).standard_normal((3, 3)), columns=columns
)
result = df.set_index(df.columns[0])
expected = df.iloc[:, 1:]
expected.index = df.iloc[:, 0].values
expected.index.names = [df.columns[0]]
tm.assert_frame_equal(result, expected)
def test_set_index_timezone(self):
# GH#12358
# tz-aware Series should retain the tz
idx = DatetimeIndex(["2014-01-01 10:10:10"], tz="UTC").tz_convert("Europe/Rome")
df = DataFrame({"A": idx})
assert df.set_index(idx).index[0].hour == 11
assert DatetimeIndex(Series(df.A))[0].hour == 11
assert df.set_index(df.A).index[0].hour == 11
def test_set_index_cast_datetimeindex(self):
df = DataFrame(
{
"A": [datetime(2000, 1, 1) + timedelta(i) for i in range(1000)],
"B": np.random.default_rng(2).standard_normal(1000),
}
)
idf = df.set_index("A")
assert isinstance(idf.index, DatetimeIndex)
def test_set_index_dst(self):
di = date_range("2006-10-29 00:00:00", periods=3, freq="h", tz="US/Pacific")
df = DataFrame(data={"a": [0, 1, 2], "b": [3, 4, 5]}, index=di).reset_index()
# single level
res = df.set_index("index")
exp = DataFrame(
data={"a": [0, 1, 2], "b": [3, 4, 5]},
index=Index(di, name="index"),
)
exp.index = exp.index._with_freq(None)
tm.assert_frame_equal(res, exp)
# GH#12920
res = df.set_index(["index", "a"])
exp_index = MultiIndex.from_arrays([di, [0, 1, 2]], names=["index", "a"])
exp = DataFrame({"b": [3, 4, 5]}, index=exp_index)
tm.assert_frame_equal(res, exp)
def test_set_index(self, float_string_frame):
df = float_string_frame
idx = Index(np.arange(len(df) - 1, -1, -1, dtype=np.int64))
df = df.set_index(idx)
tm.assert_index_equal(df.index, idx)
with pytest.raises(ValueError, match="Length mismatch"):
df.set_index(idx[::2])
def test_set_index_names(self):
df = DataFrame(
np.ones((10, 4)),
columns=Index(list("ABCD"), dtype=object),
index=Index([f"i-{i}" for i in range(10)], dtype=object),
)
df.index.name = "name"
assert df.set_index(df.index).index.names == ["name"]
mi = MultiIndex.from_arrays(df[["A", "B"]].T.values, names=["A", "B"])
mi2 = MultiIndex.from_arrays(
df[["A", "B", "A", "B"]].T.values, names=["A", "B", "C", "D"]
)
df = df.set_index(["A", "B"])
assert df.set_index(df.index).index.names == ["A", "B"]
# Check that set_index isn't converting a MultiIndex into an Index
assert isinstance(df.set_index(df.index).index, MultiIndex)
# Check actual equality
tm.assert_index_equal(df.set_index(df.index).index, mi)
idx2 = df.index.rename(["C", "D"])
# Check that [MultiIndex, MultiIndex] yields a MultiIndex rather
# than a pair of tuples
assert isinstance(df.set_index([df.index, idx2]).index, MultiIndex)
# Check equality
tm.assert_index_equal(df.set_index([df.index, idx2]).index, mi2)
# A has duplicate values, C does not
@pytest.mark.parametrize("keys", ["A", "C", ["A", "B"], ("tuple", "as", "label")])
@pytest.mark.parametrize("inplace", [True, False])
@pytest.mark.parametrize("drop", [True, False])
def test_set_index_drop_inplace(self, frame_of_index_cols, drop, inplace, keys):
df = frame_of_index_cols
if isinstance(keys, list):
idx = MultiIndex.from_arrays([df[x] for x in keys], names=keys)
else:
idx = Index(df[keys], name=keys)
expected = df.drop(keys, axis=1) if drop else df
expected.index = idx
if inplace:
result = df.copy()
return_value = result.set_index(keys, drop=drop, inplace=True)
assert return_value is None
else:
result = df.set_index(keys, drop=drop)
tm.assert_frame_equal(result, expected)
# A has duplicate values, C does not
@pytest.mark.parametrize("keys", ["A", "C", ["A", "B"], ("tuple", "as", "label")])
@pytest.mark.parametrize("drop", [True, False])
def test_set_index_append(self, frame_of_index_cols, drop, keys):
df = frame_of_index_cols
keys = keys if isinstance(keys, list) else [keys]
idx = MultiIndex.from_arrays(
[df.index] + [df[x] for x in keys], names=[None] + keys
)
expected = df.drop(keys, axis=1) if drop else df.copy()
expected.index = idx
result = df.set_index(keys, drop=drop, append=True)
tm.assert_frame_equal(result, expected)
# A has duplicate values, C does not
@pytest.mark.parametrize("keys", ["A", "C", ["A", "B"], ("tuple", "as", "label")])
@pytest.mark.parametrize("drop", [True, False])
def test_set_index_append_to_multiindex(self, frame_of_index_cols, drop, keys):
# append to existing multiindex
df = frame_of_index_cols.set_index(["D"], drop=drop, append=True)
keys = keys if isinstance(keys, list) else [keys]
expected = frame_of_index_cols.set_index(["D"] + keys, drop=drop, append=True)
result = df.set_index(keys, drop=drop, append=True)
tm.assert_frame_equal(result, expected)
def test_set_index_after_mutation(self):
# GH#1590
df = DataFrame({"val": [0, 1, 2], "key": ["a", "b", "c"]})
expected = DataFrame({"val": [1, 2]}, Index(["b", "c"], name="key"))
df2 = df.loc[df.index.map(lambda indx: indx >= 1)]
result = df2.set_index("key")
tm.assert_frame_equal(result, expected)
# MultiIndex constructor does not work directly on Series -> lambda
# Add list-of-list constructor because list is ambiguous -> lambda
# also test index name if append=True (name is duplicate here for B)
@pytest.mark.parametrize(
"box",
[
Series,
Index,
np.array,
list,
lambda x: [list(x)],
lambda x: MultiIndex.from_arrays([x]),
],
)
@pytest.mark.parametrize(
"append, index_name", [(True, None), (True, "B"), (True, "test"), (False, None)]
)
@pytest.mark.parametrize("drop", [True, False])
def test_set_index_pass_single_array(
self, frame_of_index_cols, drop, append, index_name, box
):
df = frame_of_index_cols
df.index.name = index_name
key = box(df["B"])
if box == list:
# list of strings gets interpreted as list of keys
msg = "['one', 'two', 'three', 'one', 'two']"
with pytest.raises(KeyError, match=msg):
df.set_index(key, drop=drop, append=append)
else:
# np.array/list-of-list "forget" the name of B
name_mi = getattr(key, "names", None)
name = [getattr(key, "name", None)] if name_mi is None else name_mi
result = df.set_index(key, drop=drop, append=append)
# only valid column keys are dropped
# since B is always passed as array above, nothing is dropped
expected = df.set_index(["B"], drop=False, append=append)
expected.index.names = [index_name] + name if append else name
tm.assert_frame_equal(result, expected)
# MultiIndex constructor does not work directly on Series -> lambda
# also test index name if append=True (name is duplicate here for A & B)
@pytest.mark.parametrize(
"box", [Series, Index, np.array, list, lambda x: MultiIndex.from_arrays([x])]
)
@pytest.mark.parametrize(
"append, index_name",
[(True, None), (True, "A"), (True, "B"), (True, "test"), (False, None)],
)
@pytest.mark.parametrize("drop", [True, False])
def test_set_index_pass_arrays(
self, frame_of_index_cols, drop, append, index_name, box
):
df = frame_of_index_cols
df.index.name = index_name
keys = ["A", box(df["B"])]
# np.array/list "forget" the name of B
names = ["A", None if box in [np.array, list, tuple, iter] else "B"]
result = df.set_index(keys, drop=drop, append=append)
# only valid column keys are dropped
# since B is always passed as array above, only A is dropped, if at all
expected = df.set_index(["A", "B"], drop=False, append=append)
expected = expected.drop("A", axis=1) if drop else expected
expected.index.names = [index_name] + names if append else names
tm.assert_frame_equal(result, expected)
# MultiIndex constructor does not work directly on Series -> lambda
# We also emulate a "constructor" for the label -> lambda
# also test index name if append=True (name is duplicate here for A)
@pytest.mark.parametrize(
"box2",
[
Series,
Index,
np.array,
list,
iter,
lambda x: MultiIndex.from_arrays([x]),
lambda x: x.name,
],
)
@pytest.mark.parametrize(
"box1",
[
Series,
Index,
np.array,
list,
iter,
lambda x: MultiIndex.from_arrays([x]),
lambda x: x.name,
],
)
@pytest.mark.parametrize(
"append, index_name", [(True, None), (True, "A"), (True, "test"), (False, None)]
)
@pytest.mark.parametrize("drop", [True, False])
def test_set_index_pass_arrays_duplicate(
self, frame_of_index_cols, drop, append, index_name, box1, box2
):
df = frame_of_index_cols
df.index.name = index_name
keys = [box1(df["A"]), box2(df["A"])]
result = df.set_index(keys, drop=drop, append=append)
# if either box is iter, it has been consumed; re-read
keys = [box1(df["A"]), box2(df["A"])]
# need to adapt first drop for case that both keys are 'A' --
# cannot drop the same column twice;
# plain == would give ambiguous Boolean error for containers
first_drop = (
False
if (
isinstance(keys[0], str)
and keys[0] == "A"
and isinstance(keys[1], str)
and keys[1] == "A"
)
else drop
)
# to test against already-tested behaviour, we add sequentially,
# hence second append always True; must wrap keys in list, otherwise
# box = list would be interpreted as keys
expected = df.set_index([keys[0]], drop=first_drop, append=append)
expected = expected.set_index([keys[1]], drop=drop, append=True)
tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize("append", [True, False])
@pytest.mark.parametrize("drop", [True, False])
def test_set_index_pass_multiindex(self, frame_of_index_cols, drop, append):
df = frame_of_index_cols
keys = MultiIndex.from_arrays([df["A"], df["B"]], names=["A", "B"])
result = df.set_index(keys, drop=drop, append=append)
# setting with a MultiIndex will never drop columns
expected = df.set_index(["A", "B"], drop=False, append=append)
tm.assert_frame_equal(result, expected)
def test_construction_with_categorical_index(self):
ci = CategoricalIndex(list("ab") * 5, name="B")
# with Categorical
df = DataFrame(
{"A": np.random.default_rng(2).standard_normal(10), "B": ci.values}
)
idf = df.set_index("B")
tm.assert_index_equal(idf.index, ci)
# from a CategoricalIndex
df = DataFrame({"A": np.random.default_rng(2).standard_normal(10), "B": ci})
idf = df.set_index("B")
tm.assert_index_equal(idf.index, ci)
# round-trip
idf = idf.reset_index().set_index("B")
tm.assert_index_equal(idf.index, ci)
def test_set_index_preserve_categorical_dtype(self):
# GH#13743, GH#13854
df = DataFrame(
{
"A": [1, 2, 1, 1, 2],
"B": [10, 16, 22, 28, 34],
"C1": Categorical(list("abaab"), categories=list("bac"), ordered=False),
"C2": Categorical(list("abaab"), categories=list("bac"), ordered=True),
}
)
for cols in ["C1", "C2", ["A", "C1"], ["A", "C2"], ["C1", "C2"]]:
result = df.set_index(cols).reset_index()
result = result.reindex(columns=df.columns)
tm.assert_frame_equal(result, df)
def test_set_index_datetime(self):
# GH#3950
df = DataFrame(
{
"label": ["a", "a", "a", "b", "b", "b"],
"datetime": [
"2011-07-19 07:00:00",
"2011-07-19 08:00:00",
"2011-07-19 09:00:00",
"2011-07-19 07:00:00",
"2011-07-19 08:00:00",
"2011-07-19 09:00:00",
],
"value": range(6),
}
)
df.index = to_datetime(df.pop("datetime"), utc=True)
df.index = df.index.tz_convert("US/Pacific")
expected = DatetimeIndex(
["2011-07-19 07:00:00", "2011-07-19 08:00:00", "2011-07-19 09:00:00"],
name="datetime",
)
expected = expected.tz_localize("UTC").tz_convert("US/Pacific")
df = df.set_index("label", append=True)
tm.assert_index_equal(df.index.levels[0], expected)
tm.assert_index_equal(df.index.levels[1], Index(["a", "b"], name="label"))
assert df.index.names == ["datetime", "label"]
df = df.swaplevel(0, 1)
tm.assert_index_equal(df.index.levels[0], Index(["a", "b"], name="label"))
tm.assert_index_equal(df.index.levels[1], expected)
assert df.index.names == ["label", "datetime"]
df = DataFrame(np.random.default_rng(2).random(6))
idx1 = DatetimeIndex(
[
"2011-07-19 07:00:00",
"2011-07-19 08:00:00",
"2011-07-19 09:00:00",
"2011-07-19 07:00:00",
"2011-07-19 08:00:00",
"2011-07-19 09:00:00",
],
tz="US/Eastern",
)
idx2 = DatetimeIndex(
[
"2012-04-01 09:00",
"2012-04-01 09:00",
"2012-04-01 09:00",
"2012-04-02 09:00",
"2012-04-02 09:00",
"2012-04-02 09:00",
],
tz="US/Eastern",
)
idx3 = date_range("2011-01-01 09:00", periods=6, tz="Asia/Tokyo")
idx3 = idx3._with_freq(None)
df = df.set_index(idx1)
df = df.set_index(idx2, append=True)
df = df.set_index(idx3, append=True)
expected1 = DatetimeIndex(
["2011-07-19 07:00:00", "2011-07-19 08:00:00", "2011-07-19 09:00:00"],
tz="US/Eastern",
)
expected2 = DatetimeIndex(
["2012-04-01 09:00", "2012-04-02 09:00"], tz="US/Eastern"
)
tm.assert_index_equal(df.index.levels[0], expected1)
tm.assert_index_equal(df.index.levels[1], expected2)
tm.assert_index_equal(df.index.levels[2], idx3)
# GH#7092
tm.assert_index_equal(df.index.get_level_values(0), idx1)
tm.assert_index_equal(df.index.get_level_values(1), idx2)
tm.assert_index_equal(df.index.get_level_values(2), idx3)
def test_set_index_period(self):
# GH#6631
df = DataFrame(np.random.default_rng(2).random(6))
idx1 = period_range("2011-01-01", periods=3, freq="M")
idx1 = idx1.append(idx1)
idx2 = period_range("2013-01-01 09:00", periods=2, freq="h")
idx2 = idx2.append(idx2).append(idx2)
idx3 = period_range("2005", periods=6, freq="Y")
df = df.set_index(idx1)
df = df.set_index(idx2, append=True)
df = df.set_index(idx3, append=True)
expected1 = period_range("2011-01-01", periods=3, freq="M")
expected2 = period_range("2013-01-01 09:00", periods=2, freq="h")
tm.assert_index_equal(df.index.levels[0], expected1)
tm.assert_index_equal(df.index.levels[1], expected2)
tm.assert_index_equal(df.index.levels[2], idx3)
tm.assert_index_equal(df.index.get_level_values(0), idx1)
tm.assert_index_equal(df.index.get_level_values(1), idx2)
tm.assert_index_equal(df.index.get_level_values(2), idx3)
| TestSetIndex |
python | django__django | tests/fixtures_regress/models.py | {
"start": 7015,
"end": 7123
} | class ____(BaseNKModel):
b_set = models.ManyToManyField("M2MComplexB", through="M2MThroughAB")
| M2MComplexA |
python | openai__openai-python | src/openai/types/realtime/realtime_audio_input_turn_detection.py | {
"start": 328,
"end": 2381
} | class ____(BaseModel):
type: Literal["server_vad"]
"""Type of turn detection, `server_vad` to turn on simple Server VAD."""
create_response: Optional[bool] = None
"""
Whether or not to automatically generate a response when a VAD stop event
occurs.
"""
idle_timeout_ms: Optional[int] = None
"""Optional timeout after which a model response will be triggered automatically.
This is useful for situations in which a long pause from the user is unexpected,
such as a phone call. The model will effectively prompt the user to continue the
conversation based on the current context.
The timeout value will be applied after the last model response's audio has
finished playing, i.e. it's set to the `response.done` time plus audio playback
duration.
An `input_audio_buffer.timeout_triggered` event (plus events associated with the
Response) will be emitted when the timeout is reached. Idle timeout is currently
only supported for `server_vad` mode.
"""
interrupt_response: Optional[bool] = None
"""
Whether or not to automatically interrupt any ongoing response with output to
the default conversation (i.e. `conversation` of `auto`) when a VAD start event
occurs.
"""
prefix_padding_ms: Optional[int] = None
"""Used only for `server_vad` mode.
Amount of audio to include before the VAD detected speech (in milliseconds).
Defaults to 300ms.
"""
silence_duration_ms: Optional[int] = None
"""Used only for `server_vad` mode.
Duration of silence to detect speech stop (in milliseconds). Defaults to 500ms.
With shorter values the model will respond more quickly, but may jump in on
short pauses from the user.
"""
threshold: Optional[float] = None
"""Used only for `server_vad` mode.
Activation threshold for VAD (0.0 to 1.0), this defaults to 0.5. A higher
threshold will require louder audio to activate the model, and thus might
perform better in noisy environments.
"""
| ServerVad |
python | dagster-io__dagster | python_modules/dagster-test/dagster_test/components/simple_pipes_script_asset.py | {
"start": 706,
"end": 854
} | class ____(BaseModel):
asset_key: str
filename: str
# Same schema used for file generation and defs generation
| SimplePipesScriptScaffoldParams |
python | gevent__gevent | src/gevent/tests/test__server.py | {
"start": 15978,
"end": 17632
} | class ____(TestDefaultSpawn):
def get_spawn(self):
return 2
@greentest.skipIf(greentest.EXPECT_POOR_TIMER_RESOLUTION,
"If we have bad timer resolution and hence increase timeouts, "
"it can be hard to sleep for a correct amount of time that lets "
"requests in the pool be full.")
def test_pool_full(self):
self.init_server()
with self.makefile() as long_request:
with self.makefile() as short_request:
self.send_request_to_fd(short_request, '/short')
self.send_request_to_fd(long_request, '/long')
# keep long_request in scope, otherwise the connection will be closed
gevent.get_hub().loop.update_now()
gevent.sleep(_DEFAULT_SOCKET_TIMEOUT / 10.0)
self.assertPoolFull()
self.assertPoolFull()
# XXX Not entirely clear why this fails (timeout) on appveyor;
# underlying socket timeout causing the long_request to close?
self.assertPoolFull()
# gevent.http and gevent.wsgi cannot detect socket close, so sleep a little
# to let /short request finish
gevent.sleep(_DEFAULT_SOCKET_TIMEOUT)
# XXX: This tends to timeout. Which is weird, because what would have
# been the third call to assertPoolFull() DID NOT timeout, hence why it
# was removed.
try:
self.assertRequestSucceeded()
except socket.timeout:
greentest.reraiseFlakyTestTimeout()
test_pool_full.error_fatal = False
| TestPoolSpawn |
python | python__mypy | mypy/literals.py | {
"start": 4180,
"end": 9303
} | class ____(ExpressionVisitor[Key | None]):
def visit_int_expr(self, e: IntExpr) -> Key:
return ("Literal", e.value)
def visit_str_expr(self, e: StrExpr) -> Key:
return ("Literal", e.value)
def visit_bytes_expr(self, e: BytesExpr) -> Key:
return ("Literal", e.value)
def visit_float_expr(self, e: FloatExpr) -> Key:
return ("Literal", e.value)
def visit_complex_expr(self, e: ComplexExpr) -> Key:
return ("Literal", e.value)
def visit_star_expr(self, e: StarExpr) -> Key:
return ("Star", literal_hash(e.expr))
def visit_name_expr(self, e: NameExpr) -> Key:
if isinstance(e.node, Var) and e.node.is_final and e.node.final_value is not None:
return ("Literal", e.node.final_value)
# N.B: We use the node itself as the key, and not the name,
# because using the name causes issues when there is shadowing
# (for example, in list comprehensions).
return ("Var", e.node)
def visit_member_expr(self, e: MemberExpr) -> Key:
return ("Member", literal_hash(e.expr), e.name)
def visit_op_expr(self, e: OpExpr) -> Key:
return ("Binary", e.op, literal_hash(e.left), literal_hash(e.right))
def visit_comparison_expr(self, e: ComparisonExpr) -> Key:
rest: tuple[str | Key | None, ...] = tuple(e.operators)
rest += tuple(literal_hash(o) for o in e.operands)
return ("Comparison",) + rest
def visit_unary_expr(self, e: UnaryExpr) -> Key:
return ("Unary", e.op, literal_hash(e.expr))
def seq_expr(self, e: ListExpr | TupleExpr | SetExpr, name: str) -> Key | None:
if all(literal(x) == LITERAL_YES for x in e.items):
rest: tuple[Key | None, ...] = tuple(literal_hash(x) for x in e.items)
return (name,) + rest
return None
def visit_list_expr(self, e: ListExpr) -> Key | None:
return self.seq_expr(e, "List")
def visit_dict_expr(self, e: DictExpr) -> Key | None:
if all(a and literal(a) == literal(b) == LITERAL_YES for a, b in e.items):
rest: tuple[Key | None, ...] = tuple(
(literal_hash(a) if a else None, literal_hash(b)) for a, b in e.items
)
return ("Dict",) + rest
return None
def visit_tuple_expr(self, e: TupleExpr) -> Key | None:
return self.seq_expr(e, "Tuple")
def visit_set_expr(self, e: SetExpr) -> Key | None:
return self.seq_expr(e, "Set")
def visit_index_expr(self, e: IndexExpr) -> Key | None:
if literal(e.index) == LITERAL_YES:
return ("Index", literal_hash(e.base), literal_hash(e.index))
return None
def visit_assignment_expr(self, e: AssignmentExpr) -> Key | None:
return literal_hash(e.target)
def visit_call_expr(self, e: CallExpr) -> None:
return None
def visit_slice_expr(self, e: SliceExpr) -> None:
return None
def visit_cast_expr(self, e: CastExpr) -> None:
return None
def visit_type_form_expr(self, e: TypeFormExpr) -> None:
return None
def visit_assert_type_expr(self, e: AssertTypeExpr) -> None:
return None
def visit_conditional_expr(self, e: ConditionalExpr) -> None:
return None
def visit_ellipsis(self, e: EllipsisExpr) -> None:
return None
def visit_yield_from_expr(self, e: YieldFromExpr) -> None:
return None
def visit_yield_expr(self, e: YieldExpr) -> None:
return None
def visit_reveal_expr(self, e: RevealExpr) -> None:
return None
def visit_super_expr(self, e: SuperExpr) -> None:
return None
def visit_type_application(self, e: TypeApplication) -> None:
return None
def visit_lambda_expr(self, e: LambdaExpr) -> None:
return None
def visit_list_comprehension(self, e: ListComprehension) -> None:
return None
def visit_set_comprehension(self, e: SetComprehension) -> None:
return None
def visit_dictionary_comprehension(self, e: DictionaryComprehension) -> None:
return None
def visit_generator_expr(self, e: GeneratorExpr) -> None:
return None
def visit_type_var_expr(self, e: TypeVarExpr) -> None:
return None
def visit_paramspec_expr(self, e: ParamSpecExpr) -> None:
return None
def visit_type_var_tuple_expr(self, e: TypeVarTupleExpr) -> None:
return None
def visit_type_alias_expr(self, e: TypeAliasExpr) -> None:
return None
def visit_namedtuple_expr(self, e: NamedTupleExpr) -> None:
return None
def visit_enum_call_expr(self, e: EnumCallExpr) -> None:
return None
def visit_typeddict_expr(self, e: TypedDictExpr) -> None:
return None
def visit_newtype_expr(self, e: NewTypeExpr) -> None:
return None
def visit__promote_expr(self, e: PromoteExpr) -> None:
return None
def visit_await_expr(self, e: AwaitExpr) -> None:
return None
def visit_temp_node(self, e: TempNode) -> None:
return None
_hasher: Final = _Hasher()
| _Hasher |
python | PrefectHQ__prefect | src/prefect/server/events/actions.py | {
"start": 37123,
"end": 37584
} | class ____(DeploymentCommandAction):
"""Resumes the given Deployment"""
type: Literal["resume-deployment"] = "resume-deployment"
_action_description: ClassVar[str] = "Resuming deployment"
async def command(
self,
orchestration: "OrchestrationClient",
deployment_id: UUID,
triggered_action: "TriggeredAction",
) -> Response:
return await orchestration.resume_deployment(deployment_id)
| ResumeDeployment |
python | great-expectations__great_expectations | great_expectations/_docs_decorators.py | {
"start": 854,
"end": 12775
} | class ____:
_public_api: dict[str, list[_PublicApiInfo]] = {}
# Only used for testing
_class_registry: dict[str, set[str]] = defaultdict(set)
_docstring_violations: set[str] = set()
# This is a special key that is used to indicate that a class definition
# is being added to the registry.
CLASS_DEFINITION: ClassVar[str] = "<class_def>"
@property
def class_registry(self) -> dict[str, set[str]]:
return self._class_registry
@property
def docstring_violations(self) -> set[str]:
return self._docstring_violations
def add(self, func: F) -> None:
self._add_to_docstring_violations(func)
self._add_to_class_registry(func)
try:
# We use an if statement instead of a ternary to work around
# mypy's inability to type narrow inside a ternary.
f: F
if isinstance(func, classmethod):
f = func.__func__
else:
f = func
info = _PublicApiInfo(
name=f.__name__,
qualname=f.__qualname__,
type=f.__class__.__name__,
module=f.__module__ if hasattr(func, "__module__") else None,
)
if info.type not in self._public_api:
self._public_api[info.type] = []
self._public_api[info.type].append(info)
except Exception:
logger.exception(f"Could not add this function to the public API list: {func}")
raise
def _add_to_docstring_violations(self, func: F) -> None:
name = f"{func.__module__}.{func.__qualname__}"
if not func.__doc__ and name.startswith("great_expectations"):
self._docstring_violations.add(name)
def _add_to_class_registry(self, func: F) -> None:
if isinstance(func, type):
self._add_class_definition_to_registry(func)
else:
self._add_method_to_registry(func)
def _add_class_definition_to_registry(self, cls: type) -> None:
key = f"{cls.__module__}.{cls.__qualname__}"
self._class_registry[key].add(self.CLASS_DEFINITION)
def _add_method_to_registry(self, func: F) -> None:
parts = func.__qualname__.split(".")
METHOD_PARTS_LENGTH = 2
if len(parts) == METHOD_PARTS_LENGTH:
cls = parts[0]
method = parts[1]
key = f"{func.__module__}.{cls}"
self._class_registry[key].add(method)
elif len(parts) > METHOD_PARTS_LENGTH:
# public_api interacts oddly with closures so we ignore
# This is only present in DataSourceManager and its dynamic registry
logger.info(
"Skipping registering function %s because it is a closure",
func.__qualname__,
)
else:
# Standalone functions will have a length of 1
logger.info(
"Skipping registering function %s because it does not have a class",
func.__qualname__,
)
@override
def __str__(self) -> str:
out = []
for t in sorted(list(self._public_api.keys())):
out.append(f"{t}")
for info in sorted(self._public_api[t], key=lambda info: info.qualname):
supporting_info = ""
if info.name != info.qualname:
supporting_info = _remove_suffix(info.qualname, "." + info.name)
elif info.module is not None:
supporting_info = info.module
out.append(f" {info.name}, {supporting_info}")
return "\n".join(out)
public_api_introspector = _PublicApiIntrospector()
def public_api(func: F) -> F:
"""Add the public API tag for processing by the auto documentation generator.
Used as a decorator:
@public_api
def my_method(some_argument):
...
This tag is added at import time.
"""
public_api_introspector.add(func)
existing_docstring = func.__doc__ or ""
func.__doc__ = WHITELISTED_TAG + existing_docstring
return func
def deprecated_method_or_class(
version: str,
message: str = "",
) -> Callable[[F], F]:
"""Add a deprecation warning to the docstring of the decorated method or class.
Used as a decorator:
@deprecated_method_or_class(version="1.2.3", message="Optional message")
def my_method(some_argument):
...
or
@deprecated_method_or_class(version="1.2.3", message="Optional message")
class MyClass:
...
Args:
version: Version number when the method was deprecated.
message: Optional deprecation message.
"""
text = f".. deprecated:: {version}\n {message}"
def wrapper(func: F) -> F:
"""Wrapper method that accepts func, so we can modify the docstring."""
return _add_text_to_function_docstring_after_summary(
func=func,
text=text,
)
return wrapper
def new_method_or_class(
version: str,
message: str = "",
) -> Callable[[Callable[P, T]], Callable[P, T]]:
"""Add a version added note to the docstring of the decorated method or class.
Used as a decorator:
@new_method_or_class(version="1.2.3", message="Optional message")
def my_method(some_argument):
...
or
@new_method_or_class(version="1.2.3", message="Optional message")
class MyClass:
...
Args:
version: Version number when the method was added.
message: Optional message.
"""
text = f".. versionadded:: {version}\n {message}"
def wrapper(func: Callable[P, T]) -> Callable[P, T]:
"""Wrapper method that accepts func, so we can modify the docstring."""
return _add_text_to_function_docstring_after_summary(
func=func,
text=text,
)
return wrapper
def deprecated_argument(
argument_name: str,
version: str,
message: str = "",
) -> Callable[[F], F]:
"""Add an arg-specific deprecation warning to the decorated method or class.
Used as a decorator:
@deprecated_argument(argument_name="some_argument", version="1.2.3", message="Optional message")
def my_method(some_argument):
...
or
@deprecated_argument(argument_name="some_argument", version="1.2.3", message="Optional message")
class MyClass:
...
If docstring_parser is not installed, this will not modify the docstring.
Args:
argument_name: Name of the argument to associate with the deprecation note.
version: Version number when the method was deprecated.
message: Optional deprecation message.
""" # noqa: E501 # FIXME CoP
text = f".. deprecated:: {version}\n {message}"
def wrapper(func: F) -> F:
"""Wrapper method that accepts func, so we can modify the docstring."""
if not docstring_parser.docstring_parser:
return func
return _add_text_below_function_docstring_argument(
func=func,
argument_name=argument_name,
text=text,
)
return wrapper
def new_argument(
argument_name: str,
version: str,
message: str = "",
) -> Callable[[F], F]:
"""Add an arg-specific version added note to the decorated method or class.
Used as a decorator:
@new_argument(argument_name="some_argument", version="1.2.3", message="Optional message")
def my_method(some_argument):
...
or
@new_argument(argument_name="some_argument", version="1.2.3", message="Optional message")
class MyClass:
...
If docstring_parser is not installed, this will not modify the docstring.
Args:
argument_name: Name of the argument to associate with the note.
version: The version number to associate with the note.
message: Optional message.
"""
text = f".. versionadded:: {version}\n {message}"
def wrapper(func: F) -> F:
"""Wrapper method that accepts func, so we can modify the docstring."""
if not docstring_parser.docstring_parser:
return func
return _add_text_below_function_docstring_argument(
func=func,
argument_name=argument_name,
text=text,
)
return wrapper
def _add_text_to_function_docstring_after_summary(func: F, text: str) -> F:
"""Insert text into docstring, e.g. rst directive.
Args:
func: Add text to provided func docstring.
text: String to add to the docstring, can be a rst directive e.g.:
text = (
".. versionadded:: 1.2.3\n"
" Added in version 1.2.3\n"
)
Returns:
func with modified docstring.
"""
existing_docstring = func.__doc__ if func.__doc__ else ""
split_docstring = existing_docstring.split("\n", 1)
docstring = ""
if len(split_docstring) == 2: # noqa: PLR2004 # FIXME CoP
short_description, docstring = split_docstring
docstring = f"{short_description.strip()}\n\n{text}\n\n{dedent(docstring)}"
elif len(split_docstring) == 1:
short_description = split_docstring[0]
docstring = f"{short_description.strip()}\n\n{text}\n"
elif len(split_docstring) == 0:
docstring = f"{text}\n"
func.__doc__ = docstring
return func
def _add_text_below_function_docstring_argument(
func: F,
argument_name: str,
text: str,
) -> F:
"""Add text below specified docstring argument.
Args:
func: Callable[P, T]unction whose docstring will be modified.
argument_name: Name of the argument to add text to its description.
text: Text to add to the argument description.
Returns:
func with modified docstring.
"""
existing_docstring = func.__doc__ if func.__doc__ else ""
func.__doc__ = _add_text_below_string_docstring_argument(
docstring=existing_docstring, argument_name=argument_name, text=text
)
return func
def _add_text_below_string_docstring_argument(docstring: str, argument_name: str, text: str) -> str:
"""Add text below an argument in a docstring.
Note: Can be used for rst directives.
Args:
docstring: Docstring to modify.
argument_name: Argument to place text below.
text: Text to place below argument. Can be an rst directive.
Returns:
Modified docstring.
"""
parsed_docstring = docstring_parser.docstring_parser.parse(
text=docstring,
style=docstring_parser.DocstringStyle.GOOGLE,
)
arg_list = list(param.arg_name for param in parsed_docstring.params)
if argument_name not in arg_list:
raise ValueError(f"Please specify an existing argument, you specified {argument_name}.") # noqa: TRY003 # FIXME CoP
for param in parsed_docstring.params:
if param.arg_name == argument_name:
if param.description is None:
param.description = text
else:
param.description += "\n\n" + text + "\n"
# Returns: includes an additional ":\n" that we need to strip out.
if parsed_docstring.returns:
if parsed_docstring.returns.description:
parsed_docstring.returns.description = parsed_docstring.returns.description.strip(":\n")
# RenderingStyle.EXPANDED used to make sure any line breaks before and
# after the added text are included (for Sphinx html rendering).
composed_docstring = docstring_parser.docstring_parser.compose(
docstring=parsed_docstring,
style=docstring_parser.DocstringStyle.GOOGLE,
rendering_style=docstring_parser.docstring_parser.RenderingStyle.EXPANDED,
)
return composed_docstring
| _PublicApiIntrospector |
python | sqlalchemy__sqlalchemy | test/dialect/sqlite/test_dialect.py | {
"start": 1610,
"end": 5964
} | class ____(fixtures.TestBase, AssertsCompiledSQL):
__only_on__ = "sqlite"
__backend__ = True
def test_default_reflection(self, connection, metadata):
specs = [
(String(3), '"foo"'),
(sqltypes.NUMERIC(10, 2), "100.50"),
(Integer, "5"),
(Boolean, "False"),
]
columns = [
Column("c%i" % (i + 1), t[0], server_default=text(t[1]))
for (i, t) in enumerate(specs)
]
Table("t_defaults", metadata, *columns)
metadata.create_all(connection)
m2 = MetaData()
rt = Table("t_defaults", m2, autoload_with=connection)
expected = [c[1] for c in specs]
for i, reflected in enumerate(rt.c):
eq_(str(reflected.server_default.arg), expected[i])
@testing.exclude(
"sqlite",
"<",
(3, 3, 8),
"sqlite3 changesets 3353 and 3440 modified "
"behavior of default displayed in pragma "
"table_info()",
)
def test_default_reflection_2(self):
db = testing.db
m = MetaData()
expected = ["'my_default'", "0"]
table = """CREATE TABLE r_defaults (
data VARCHAR(40) DEFAULT 'my_default',
val INTEGER NOT NULL DEFAULT 0
)"""
try:
exec_sql(db, table)
rt = Table("r_defaults", m, autoload_with=db)
for i, reflected in enumerate(rt.c):
eq_(str(reflected.server_default.arg), expected[i])
finally:
exec_sql(db, "DROP TABLE r_defaults")
def test_default_reflection_3(self):
db = testing.db
table = """CREATE TABLE r_defaults (
data VARCHAR(40) DEFAULT 'my_default',
val INTEGER NOT NULL DEFAULT 0
)"""
try:
exec_sql(db, table)
m1 = MetaData()
t1 = Table("r_defaults", m1, autoload_with=db)
exec_sql(db, "DROP TABLE r_defaults")
t1.create(db)
m2 = MetaData()
t2 = Table("r_defaults", m2, autoload_with=db)
self.assert_compile(
CreateTable(t2),
"CREATE TABLE r_defaults (data VARCHAR(40) "
"DEFAULT 'my_default', val INTEGER DEFAULT 0 "
"NOT NULL)",
)
finally:
exec_sql(db, "DROP TABLE r_defaults")
@testing.provide_metadata
def test_boolean_default(self):
t = Table(
"t",
self.metadata,
Column("x", Boolean, server_default=sql.false()),
)
t.create(testing.db)
with testing.db.begin() as conn:
conn.execute(t.insert())
conn.execute(t.insert().values(x=True))
eq_(
conn.execute(t.select().order_by(t.c.x)).fetchall(),
[(False,), (True,)],
)
@testing.provide_metadata
def test_function_default(self):
t = Table(
"t",
self.metadata,
Column("id", Integer, primary_key=True),
Column("x", String(), server_default=func.lower("UPPERCASE")),
)
t.create(testing.db)
with testing.db.begin() as conn:
conn.execute(t.insert())
conn.execute(t.insert().values(x="foobar"))
eq_(
conn.execute(select(t.c.x).order_by(t.c.id)).fetchall(),
[("uppercase",), ("foobar",)],
)
@testing.provide_metadata
def test_expression_with_function_default(self):
t = Table(
"t",
self.metadata,
Column("id", Integer, primary_key=True),
Column("x", Integer(), server_default=func.abs(-5) + 17),
)
t.create(testing.db)
with testing.db.begin() as conn:
conn.execute(t.insert())
conn.execute(t.insert().values(x=35))
eq_(
conn.execute(select(t.c.x).order_by(t.c.id)).fetchall(),
[(22,), (35,)],
)
def test_old_style_default(self):
"""test non-quoted integer value on older sqlite pragma"""
dialect = sqlite.dialect()
info = dialect._get_column_info(
"foo", "INTEGER", False, 3, False, False, False, None
)
eq_(info["default"], "3")
| DefaultsTest |
python | astropy__astropy | astropy/utils/masked/tests/test_table.py | {
"start": 450,
"end": 820
} | class ____:
@classmethod
def setup_arrays(cls):
cls.a = np.array([3.0, 5.0, 0.0])
cls.mask_a = np.array([True, False, False])
@classmethod
def setup_class(cls):
cls.setup_arrays()
cls.ma = Masked(cls.a, mask=cls.mask_a)
cls.ma.info.format = ".1f"
cls.t = QTable([cls.ma], names=["ma"])
| MaskedArrayTableSetup |
python | astropy__astropy | astropy/timeseries/tests/test_common.py | {
"start": 528,
"end": 2355
} | class ____:
def test_stacking(self):
ts = vstack([self.series, self.series])
assert isinstance(ts, self.series.__class__)
def test_row_slicing(self):
ts = self.series[:2]
assert isinstance(ts, self.series.__class__)
def test_row_indexing(self):
assert self.series[1][self.time_attr] == Time("2015-01-21T12:30:32")
assert self.series[self.time_attr][1] == Time("2015-01-21T12:30:32")
def test_column_indexing(self):
assert_equal(self.series["a"], [1, 2, 11])
def test_column_slicing_notime(self):
tab = self.series["a", "b"]
assert not isinstance(tab, self.series.__class__)
assert isinstance(tab, QTable)
def test_add_column(self):
self.series["d"] = [1, 2, 3]
def test_add_row(self):
self.series.add_row(self._row)
def test_set_unit(self):
self.series["d"] = [1, 2, 3]
self.series["d"].unit = "s"
def test_replace_column(self):
self.series.replace_column("c", [1, 3, 4])
def test_required_after_stacking(self):
# When stacking, we have to temporarily relax the checking of the
# columns in the time series, but we need to make sure that the
# checking works again afterwards
ts = vstack([self.series, self.series])
with pytest.raises(ValueError, match=r"TimeSeries object is invalid"):
ts.remove_columns(ts.colnames)
def test_join(self):
ts_other = self.series.copy()
ts_other.add_row(self._row)
ts_other["d"] = [11, 22, 33, 44]
ts_other.remove_columns(["a", "b"])
ts = join(self.series, ts_other)
assert len(ts) == len(self.series)
ts = join(self.series, ts_other, join_type="outer")
assert len(ts) == len(ts_other)
| CommonTimeSeriesTests |
python | huggingface__transformers | tests/models/kosmos2_5/test_modeling_kosmos2_5.py | {
"start": 9612,
"end": 19637
} | class ____(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase):
all_model_classes = (Kosmos2_5Model, Kosmos2_5ForConditionalGeneration) if is_torch_available() else ()
all_generative_model_classes = (Kosmos2_5ForConditionalGeneration,) if is_torch_available() else ()
pipeline_model_mapping = (
{
"feature-extraction": Kosmos2_5Model,
"image-to-text": Kosmos2_5ForConditionalGeneration,
}
if is_torch_available()
else {}
)
test_resize_embeddings = False
test_attention_outputs = False
_is_composite = True
# TODO: `image-to-text` pipeline for this model needs Processor.
def is_pipeline_test_to_skip(
self,
pipeline_test_casse_name,
config_class,
model_architecture,
tokenizer_name,
processor_name,
):
return pipeline_test_casse_name == "ImageToTextPipelineTests"
def _prepare_for_class(self, inputs_dict, model_class, return_labels=False):
inputs_dict = copy.deepcopy(inputs_dict)
if return_labels:
if model_class.__name__ == "Kosmos2_5ForConditionalGeneration":
inputs_dict["labels"] = torch.zeros(
(
self.model_tester.text_model_tester.batch_size,
self.model_tester.text_model_tester.seq_length,
),
dtype=torch.long,
device=torch_device,
)
if model_class.__name__ in [
"Kosmos2_5Model",
"Kosmos2_5ForConditionalGeneration",
]:
bs, _ = inputs_dict["input_ids"].shape
seqlen = self.model_tester.text_model_tester.seq_length
inputs_dict["input_ids"] = torch.arange(seqlen, device=torch_device).unsqueeze(0).expand(bs, seqlen)
inputs_dict["input_ids"] = inputs_dict["input_ids"] % self.model_tester.text_model_tester.vocab_size
inputs_dict["attention_mask"] = torch.ones((bs, seqlen), device=torch_device)
inputs_dict["image_embeds_position_mask"] = torch.zeros((bs, seqlen), device=torch_device)
inputs_dict["image_embeds_position_mask"][:, : self.model_tester.latent_query_num] = 1
return inputs_dict
def setUp(self):
self.model_tester = Kosmos2_5ModelTester(self)
self.config_tester = ConfigTester(self, config_class=Kosmos2_5Config, hidden_size=37)
@unittest.skip("KOSMOS-2.5 doesn't support padding")
def test_eager_padding_matches_padding_free_with_position_ids(self):
pass
@unittest.skip("KOSMOS-2.5 doesn't support padding")
def test_sdpa_padding_matches_padding_free_with_position_ids(self):
pass
@parameterized.expand([("random",), ("same",)])
@pytest.mark.generate
@unittest.skip(
"Kosmos-2.5 doesn't support assisted generation due to the need to extend `image_embeds_position_mask` length."
)
def test_assisted_decoding_matches_greedy_search(self):
pass
@pytest.mark.generate
@unittest.skip(
"Kosmos-2.5 doesn't support assisted generation due to the need to extend `image_embeds_position_mask` length."
)
def test_assisted_decoding_sample(self):
pass
@unittest.skip(
"Kosmos-2.5 doesn't support assisted generation due to the need to extend `image_embeds_position_mask` length."
)
def test_prompt_lookup_decoding_matches_greedy_search(self):
pass
@unittest.skip(reason="Kosmos2-3 has no separate base model without a head.")
def test_model_base_model_prefix(self):
pass
def test_model(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*config_and_inputs)
def test_forward_signature(self):
config, _ = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
model = model_class(config)
signature = inspect.signature(model.forward)
# signature.parameters is an OrderedDict => so arg_names order is deterministic
arg_names = [*signature.parameters.keys()]
expected_arg_names = ["input_ids"]
self.assertListEqual(arg_names[:1], expected_arg_names)
def test_load_save_without_tied_weights(self):
config, _ = self.model_tester.prepare_config_and_inputs_for_common()
config.text_config.tie_word_embeddings = False
for model_class in self.all_model_classes:
model = model_class(config)
with tempfile.TemporaryDirectory() as d:
model.save_pretrained(d)
model_reloaded, infos = model_class.from_pretrained(d, output_loading_info=True)
# Checking the state dicts are correct
reloaded_state = model_reloaded.state_dict()
for k, v in model.state_dict().items():
self.assertIn(k, reloaded_state, f"Key {k} is missing from reloaded")
torch.testing.assert_close(
v,
reloaded_state[k],
msg=lambda x: f"{model_class.__name__}: Tensor {k}: {x}",
)
# Checking there was no complain of missing weights
self.assertEqual(infos["missing_keys"], set())
# overwrite from common in order to use `self.model_tester.text_model_tester.num_hidden_layers`
def test_hidden_states_output(self):
def check_hidden_states_output(inputs_dict, config, model_class):
model = model_class(config)
model.to(torch_device)
model.eval()
with torch.no_grad():
outputs = model(**self._prepare_for_class(inputs_dict, model_class))
hidden_states = outputs.hidden_states
expected_num_layers = getattr(
self.model_tester,
"expected_num_hidden_layers",
self.model_tester.text_model_tester.num_hidden_layers + 1,
)
self.assertEqual(len(hidden_states), expected_num_layers)
seq_length = self.model_tester.text_model_tester.seq_length
self.assertListEqual(
list(hidden_states[0].shape[-2:]),
[seq_length, self.model_tester.text_model_tester.hidden_size],
)
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
inputs_dict["output_hidden_states"] = True
check_hidden_states_output(inputs_dict, config, model_class)
# check that output_hidden_states also work using config
del inputs_dict["output_hidden_states"]
config.output_hidden_states = True
check_hidden_states_output(inputs_dict, config, model_class)
@slow
def test_model_from_pretrained(self):
model_name = "microsoft/kosmos-2.5"
model = Kosmos2_5Model.from_pretrained(model_name)
self.assertIsNotNone(model)
@unittest.skip(reason="Does not work on the tiny model as we keep hitting edge cases.")
def test_model_parallelism(self):
pass
# TODO: ydshieh
@require_torch_gpu
@slow
@unittest.skip(reason="_update_causal_mask is not implemented yet which fails this test")
def test_sdpa_can_dispatch_on_flash(self):
pass
# TODO: ydshieh
@unittest.skip(reason="doesn't support padding yet")
def test_eager_matches_sdpa_inference_1_bfloat16(self):
pass
# TODO: ydshieh
@unittest.skip(reason=" the model hasn't been added to auto class")
def test_flash_attn_2_from_config(self):
pass
@unittest.skip("This test is currently not well designed for multimodal model (float type as an input).")
def test_flash_attn_2_fp32_ln(self):
pass
@unittest.skip("This test is currently not well designed for multimodal model (float type as an input).")
def test_flash_attention_2_padding_matches_padding_free_with_position_ids(self):
pass
@unittest.skip("Kosmos 2.5 is multimodel and has specific input shapes.")
def test_flash_attn_2_generate_reuse_cache(self):
pass
@pytest.mark.generate
@parameterized.expand([("greedy", 1), ("beam search", 2)])
@unittest.skip(
"KOSMOS-2.5 doesn't support inputs embeds. The test isn't skipped by checking input args because KOSMOS-2 has `generate()` overwritten",
)
def test_generate_from_inputs_embeds(self):
pass
@pytest.mark.generate
def test_left_padding_compatibility(self):
# Overwrite -- Kosmos-2.5 needs to prepare `image_embeds_position_mask`, and it must be padded accordingly
_, inputs_dict = self.prepare_config_and_inputs_for_generate()
input_ids = inputs_dict["input_ids"]
def _prepare_image_embeds_position_mask(input_ids, pad_size):
image_embeds_position_mask = torch.zeros(
input_ids.shape[0], input_ids.shape[1] + pad_size, device=torch_device, dtype=input_ids.dtype
)
image_embeds_position_mask[:, (pad_size + 1) : pad_size + 1 + self.model_tester.latent_query_num] = 1
return image_embeds_position_mask
# `image_embeds_position_mask` is randomly generated in `prepare_config_and_inputs_for_generate`, and it must
# match its padded version for the test to be valid -- we need to pass both
unpadded_custom_inputs = {"image_embeds_position_mask": _prepare_image_embeds_position_mask(input_ids, 0)}
padded_custom_inputs = {"image_embeds_position_mask": _prepare_image_embeds_position_mask(input_ids, 32)}
super().test_left_padding_compatibility(
unpadded_custom_inputs=unpadded_custom_inputs, padded_custom_inputs=padded_custom_inputs
)
@require_vision
@require_torch
@slow
| Kosmos2_5ModelTest |
python | pytorch__pytorch | test/distributed/fsdp/test_fsdp_comm_hooks.py | {
"start": 2302,
"end": 2506
} | class ____:
__slots__ = ["process_group", "noise"]
def __init__(self, process_group: dist.ProcessGroup, noise: int):
self.process_group = process_group
self.noise = noise
| DummyState |
python | bokeh__bokeh | src/bokeh/util/compiler.py | {
"start": 4843,
"end": 4989
} | class ____(Inline):
''' An implementation of a Less CSS style sheet.
'''
@property
def lang(self) -> str:
return "less"
| Less |
python | pennersr__django-allauth | allauth/socialaccount/providers/twitter/views.py | {
"start": 562,
"end": 1373
} | class ____(OAuthAdapter):
provider_id = "twitter"
request_token_url = "https://api.x.com/oauth/request_token" # nosec
access_token_url = "https://api.x.com/oauth/access_token" # nosec
# Issue #42 -- this one authenticates over and over again...
# authorize_url = 'https://api.twitter.com/oauth/authorize'
authorize_url = "https://api.x.com/oauth/authenticate"
def complete_login(self, request, app, token, response):
client = TwitterAPI(request, app.client_id, app.secret, self.request_token_url)
extra_data = client.get_user_info()
return self.get_provider().sociallogin_from_response(request, extra_data)
oauth_login = OAuthLoginView.adapter_view(TwitterOAuthAdapter)
oauth_callback = OAuthCallbackView.adapter_view(TwitterOAuthAdapter)
| TwitterOAuthAdapter |
python | sympy__sympy | sympy/integrals/integrals.py | {
"start": 1531,
"end": 65075
} | class ____(AddWithLimits):
"""Represents unevaluated integral."""
__slots__ = ()
args: tuple[Expr, Tuple] # type: ignore
def __new__(cls, function, *symbols, **assumptions) -> Integral:
"""Create an unevaluated integral.
Explanation
===========
Arguments are an integrand followed by one or more limits.
If no limits are given and there is only one free symbol in the
expression, that symbol will be used, otherwise an error will be
raised.
>>> from sympy import Integral
>>> from sympy.abc import x, y
>>> Integral(x)
Integral(x, x)
>>> Integral(y)
Integral(y, y)
When limits are provided, they are interpreted as follows (using
``x`` as though it were the variable of integration):
(x,) or x - indefinite integral
(x, a) - "evaluate at" integral is an abstract antiderivative
(x, a, b) - definite integral
The ``as_dummy`` method can be used to see which symbols cannot be
targeted by subs: those with a prepended underscore cannot be
changed with ``subs``. (Also, the integration variables themselves --
the first element of a limit -- can never be changed by subs.)
>>> i = Integral(x, x)
>>> at = Integral(x, (x, x))
>>> i.as_dummy()
Integral(x, x)
>>> at.as_dummy()
Integral(_0, (_0, x))
"""
#This will help other classes define their own definitions
#of behaviour with Integral.
if hasattr(function, '_eval_Integral'):
return function._eval_Integral(*symbols, **assumptions)
if isinstance(function, Poly):
sympy_deprecation_warning(
"""
integrate(Poly) and Integral(Poly) are deprecated. Instead,
use the Poly.integrate() method, or convert the Poly to an
Expr first with the Poly.as_expr() method.
""",
deprecated_since_version="1.6",
active_deprecations_target="deprecated-integrate-poly")
obj = AddWithLimits.__new__(cls, function, *symbols, **assumptions)
return obj
def __getnewargs__(self):
return (self.function,) + tuple([tuple(xab) for xab in self.limits])
@property
def free_symbols(self):
"""
This method returns the symbols that will exist when the
integral is evaluated. This is useful if one is trying to
determine whether an integral depends on a certain
symbol or not.
Examples
========
>>> from sympy import Integral
>>> from sympy.abc import x, y
>>> Integral(x, (x, y, 1)).free_symbols
{y}
See Also
========
sympy.concrete.expr_with_limits.ExprWithLimits.function
sympy.concrete.expr_with_limits.ExprWithLimits.limits
sympy.concrete.expr_with_limits.ExprWithLimits.variables
"""
return super().free_symbols
def _eval_is_zero(self):
# This is a very naive and quick test, not intended to do the integral to
# answer whether it is zero or not, e.g. Integral(sin(x), (x, 0, 2*pi))
# is zero but this routine should return None for that case. But, like
# Mul, there are trivial situations for which the integral will be
# zero so we check for those.
if self.function.is_zero:
return True
got_none = False
for l in self.limits:
if len(l) == 3:
z = (l[1] == l[2]) or (l[1] - l[2]).is_zero
if z:
return True
elif z is None:
got_none = True
free = self.function.free_symbols
for xab in self.limits:
if len(xab) == 1:
free.add(xab[0])
continue
if len(xab) == 2 and xab[0] not in free:
if xab[1].is_zero:
return True
elif xab[1].is_zero is None:
got_none = True
# take integration symbol out of free since it will be replaced
# with the free symbols in the limits
free.discard(xab[0])
# add in the new symbols
for i in xab[1:]:
free.update(i.free_symbols)
if self.function.is_zero is False and got_none is False:
return False
def transform(self, x, u):
r"""
Performs a change of variables from `x` to `u` using the relationship
given by `x` and `u` which will define the transformations `f` and `F`
(which are inverses of each other) as follows:
1) If `x` is a Symbol (which is a variable of integration) then `u`
will be interpreted as some function, f(u), with inverse F(u).
This, in effect, just makes the substitution of x with f(x).
2) If `u` is a Symbol then `x` will be interpreted as some function,
F(x), with inverse f(u). This is commonly referred to as
u-substitution.
Once f and F have been identified, the transformation is made as
follows:
.. math:: \int_a^b x \mathrm{d}x \rightarrow \int_{F(a)}^{F(b)} f(x)
\frac{\mathrm{d}}{\mathrm{d}x}
where `F(x)` is the inverse of `f(x)` and the limits and integrand have
been corrected so as to retain the same value after integration.
Notes
=====
The mappings, F(x) or f(u), must lead to a unique integral. Linear
or rational linear expression, ``2*x``, ``1/x`` and ``sqrt(x)``, will
always work; quadratic expressions like ``x**2 - 1`` are acceptable
as long as the resulting integrand does not depend on the sign of
the solutions (see examples).
The integral will be returned unchanged if ``x`` is not a variable of
integration.
``x`` must be (or contain) only one of of the integration variables. If
``u`` has more than one free symbol then it should be sent as a tuple
(``u``, ``uvar``) where ``uvar`` identifies which variable is replacing
the integration variable.
XXX can it contain another integration variable?
Examples
========
>>> from sympy.abc import a, x, u
>>> from sympy import Integral, cos, sqrt
>>> i = Integral(x*cos(x**2 - 1), (x, 0, 1))
transform can change the variable of integration
>>> i.transform(x, u)
Integral(u*cos(u**2 - 1), (u, 0, 1))
transform can perform u-substitution as long as a unique
integrand is obtained:
>>> ui = i.transform(x**2 - 1, u)
>>> ui
Integral(cos(u)/2, (u, -1, 0))
This attempt fails because x = +/-sqrt(u + 1) and the
sign does not cancel out of the integrand:
>>> Integral(cos(x**2 - 1), (x, 0, 1)).transform(x**2 - 1, u)
Traceback (most recent call last):
...
ValueError:
The mapping between F(x) and f(u) did not give a unique integrand.
transform can do a substitution. Here, the previous
result is transformed back into the original expression
using "u-substitution":
>>> ui.transform(sqrt(u + 1), x) == i
True
We can accomplish the same with a regular substitution:
>>> ui.transform(u, x**2 - 1) == i
True
If the `x` does not contain a symbol of integration then
the integral will be returned unchanged. Integral `i` does
not have an integration variable `a` so no change is made:
>>> i.transform(a, x) == i
True
When `u` has more than one free symbol the symbol that is
replacing `x` must be identified by passing `u` as a tuple:
>>> Integral(x, (x, 0, 1)).transform(x, (u + a, u))
Integral(a + u, (u, -a, 1 - a))
>>> Integral(x, (x, 0, 1)).transform(x, (u + a, a))
Integral(a + u, (a, -u, 1 - u))
See Also
========
sympy.concrete.expr_with_limits.ExprWithLimits.variables : Lists the integration variables
as_dummy : Replace integration variables with dummy ones
"""
d = Dummy('d')
xfree = x.free_symbols.intersection(self.variables)
if len(xfree) > 1:
raise ValueError(
'F(x) can only contain one of: %s' % self.variables)
xvar = xfree.pop() if xfree else d
if xvar not in self.variables:
return self
u = sympify(u)
if isinstance(u, Expr):
ufree = u.free_symbols
if len(ufree) == 0:
raise ValueError(filldedent('''
f(u) cannot be a constant'''))
if len(ufree) > 1:
raise ValueError(filldedent('''
When f(u) has more than one free symbol, the one replacing x
must be identified: pass f(u) as (f(u), u)'''))
uvar = ufree.pop()
else:
u, uvar = u
if uvar not in u.free_symbols:
raise ValueError(filldedent('''
Expecting a tuple (expr, symbol) where symbol identified
a free symbol in expr, but symbol is not in expr's free
symbols.'''))
if not isinstance(uvar, Symbol):
# This probably never evaluates to True
raise ValueError(filldedent('''
Expecting a tuple (expr, symbol) but didn't get
a symbol; got %s''' % uvar))
if x.is_Symbol and u.is_Symbol:
return self.xreplace({x: u})
if not x.is_Symbol and not u.is_Symbol:
raise ValueError('either x or u must be a symbol')
if uvar == xvar:
return self.transform(x, (u.subs(uvar, d), d)).xreplace({d: uvar})
if uvar in self.limits:
raise ValueError(filldedent('''
u must contain the same variable as in x
or a variable that is not already an integration variable'''))
from sympy.solvers.solvers import solve
if not x.is_Symbol:
F = [x.subs(xvar, d)]
soln = solve(u - x, xvar, check=False)
if not soln:
raise ValueError('no solution for solve(F(x) - f(u), x)')
f = [fi.subs(uvar, d) for fi in soln]
else:
f = [u.subs(uvar, d)]
from sympy.simplify.simplify import posify
pdiff, reps = posify(u - x)
puvar = uvar.subs([(v, k) for k, v in reps.items()])
soln = [s.subs(reps) for s in solve(pdiff, puvar)]
if not soln:
raise ValueError('no solution for solve(F(x) - f(u), u)')
F = [fi.subs(xvar, d) for fi in soln]
newfuncs = {(self.function.subs(xvar, fi)*fi.diff(d)
).subs(d, uvar) for fi in f}
if len(newfuncs) > 1:
raise ValueError(filldedent('''
The mapping between F(x) and f(u) did not give
a unique integrand.'''))
newfunc = newfuncs.pop()
def _calc_limit_1(F, a, b):
"""
replace d with a, using subs if possible, otherwise limit
where sign of b is considered
"""
wok = F.subs(d, a)
if wok is S.NaN or wok.is_finite is False and a.is_finite:
return limit(sign(b)*F, d, a)
return wok
def _calc_limit(a, b):
"""
replace d with a, using subs if possible, otherwise limit
where sign of b is considered
"""
avals = list({_calc_limit_1(Fi, a, b) for Fi in F})
if len(avals) > 1:
raise ValueError(filldedent('''
The mapping between F(x) and f(u) did not
give a unique limit.'''))
return avals[0]
newlimits = []
for xab in self.limits:
sym = xab[0]
if sym == xvar:
if len(xab) == 3:
a, b = xab[1:]
a, b = _calc_limit(a, b), _calc_limit(b, a)
if fuzzy_bool(a - b > 0):
a, b = b, a
newfunc = -newfunc
newlimits.append((uvar, a, b))
elif len(xab) == 2:
a = _calc_limit(xab[1], 1)
newlimits.append((uvar, a))
else:
newlimits.append(uvar)
else:
newlimits.append(xab)
return self.func(newfunc, *newlimits)
def doit(self, **hints):
"""
Perform the integration using any hints given.
Examples
========
>>> from sympy import Piecewise, S
>>> from sympy.abc import x, t
>>> p = x**2 + Piecewise((0, x/t < 0), (1, True))
>>> p.integrate((t, S(4)/5, 1), (x, -1, 1))
1/3
See Also
========
sympy.integrals.trigonometry.trigintegrate
sympy.integrals.heurisch.heurisch
sympy.integrals.rationaltools.ratint
as_sum : Approximate the integral using a sum
"""
if not hints.get('integrals', True):
return self
deep = hints.get('deep', True)
meijerg = hints.get('meijerg', None)
conds = hints.get('conds', 'piecewise')
risch = hints.get('risch', None)
heurisch = hints.get('heurisch', None)
manual = hints.get('manual', None)
if len(list(filter(None, (manual, meijerg, risch, heurisch)))) > 1:
raise ValueError("At most one of manual, meijerg, risch, heurisch can be True")
elif manual:
meijerg = risch = heurisch = False
elif meijerg:
manual = risch = heurisch = False
elif risch:
manual = meijerg = heurisch = False
elif heurisch:
manual = meijerg = risch = False
eval_kwargs = {"meijerg": meijerg, "risch": risch, "manual": manual, "heurisch": heurisch,
"conds": conds}
if conds not in ('separate', 'piecewise', 'none'):
raise ValueError('conds must be one of "separate", "piecewise", '
'"none", got: %s' % conds)
if risch and any(len(xab) > 1 for xab in self.limits):
raise ValueError('risch=True is only allowed for indefinite integrals.')
# check for the trivial zero
if self.is_zero:
return S.Zero
# hacks to handle integrals of
# nested summations
from sympy.concrete.summations import Sum
if isinstance(self.function, Sum):
if any(v in self.function.limits[0] for v in self.variables):
raise ValueError('Limit of the sum cannot be an integration variable.')
if any(l.is_infinite for l in self.function.limits[0][1:]):
return self
_i = self
_sum = self.function
return _sum.func(_i.func(_sum.function, *_i.limits).doit(), *_sum.limits).doit()
# now compute and check the function
function = self.function
# hack to use a consistent Heaviside(x, 1/2)
function = function.replace(
lambda x: isinstance(x, Heaviside) and x.args[1]*2 != 1,
lambda x: Heaviside(x.args[0]))
if deep:
function = function.doit(**hints)
if function.is_zero:
return S.Zero
# hacks to handle special cases
if isinstance(function, MatrixBase):
return function.applyfunc(
lambda f: self.func(f, *self.limits).doit(**hints))
if isinstance(function, FormalPowerSeries):
if len(self.limits) > 1:
raise NotImplementedError
xab = self.limits[0]
if len(xab) > 1:
return function.integrate(xab, **eval_kwargs)
else:
return function.integrate(xab[0], **eval_kwargs)
# There is no trivial answer and special handling
# is done so continue
# first make sure any definite limits have integration
# variables with matching assumptions
reps = {}
for xab in self.limits:
if len(xab) != 3:
# it makes sense to just make
# all x real but in practice with the
# current state of integration...this
# doesn't work out well
# x = xab[0]
# if x not in reps and not x.is_real:
# reps[x] = Dummy(real=True)
continue
x, a, b = xab
l = (a, b)
if all(i.is_nonnegative for i in l) and not x.is_nonnegative:
d = Dummy(positive=True)
elif all(i.is_nonpositive for i in l) and not x.is_nonpositive:
d = Dummy(negative=True)
elif all(i.is_real for i in l) and not x.is_real:
d = Dummy(real=True)
else:
d = None
if d:
reps[x] = d
if reps:
undo = {v: k for k, v in reps.items()}
did = self.xreplace(reps).doit(**hints)
if isinstance(did, tuple): # when separate=True
did = tuple([i.xreplace(undo) for i in did])
else:
did = did.xreplace(undo)
return did
# continue with existing assumptions
undone_limits = []
# ulj = free symbols of any undone limits' upper and lower limits
ulj = set()
for xab in self.limits:
# compute uli, the free symbols in the
# Upper and Lower limits of limit I
if len(xab) == 1:
uli = set(xab[:1])
elif len(xab) == 2:
uli = xab[1].free_symbols
elif len(xab) == 3:
uli = xab[1].free_symbols.union(xab[2].free_symbols)
# this integral can be done as long as there is no blocking
# limit that has been undone. An undone limit is blocking if
# it contains an integration variable that is in this limit's
# upper or lower free symbols or vice versa
if xab[0] in ulj or any(v[0] in uli for v in undone_limits):
undone_limits.append(xab)
ulj.update(uli)
function = self.func(*([function] + [xab]))
factored_function = function.factor()
if not isinstance(factored_function, Integral):
function = factored_function
continue
if function.has(Abs, sign) and (
(len(xab) < 3 and all(x.is_extended_real for x in xab)) or
(len(xab) == 3 and all(x.is_extended_real and not x.is_infinite for
x in xab[1:]))):
# some improper integrals are better off with Abs
xr = Dummy("xr", real=True)
function = (function.xreplace({xab[0]: xr})
.rewrite(Piecewise).xreplace({xr: xab[0]}))
elif function.has(Min, Max):
function = function.rewrite(Piecewise)
if (function.has(Piecewise) and
not isinstance(function, Piecewise)):
function = piecewise_fold(function)
if isinstance(function, Piecewise):
if len(xab) == 1:
antideriv = function._eval_integral(xab[0],
**eval_kwargs)
else:
antideriv = self._eval_integral(
function, xab[0], **eval_kwargs)
else:
# There are a number of tradeoffs in using the
# Meijer G method. It can sometimes be a lot faster
# than other methods, and sometimes slower. And
# there are certain types of integrals for which it
# is more likely to work than others. These
# heuristics are incorporated in deciding what
# integration methods to try, in what order. See the
# integrate() docstring for details.
def try_meijerg(function, xab):
ret = None
if len(xab) == 3 and meijerg is not False:
x, a, b = xab
try:
res = meijerint_definite(function, x, a, b)
except NotImplementedError:
_debug('NotImplementedError '
'from meijerint_definite')
res = None
if res is not None:
f, cond = res
if conds == 'piecewise':
u = self.func(function, (x, a, b))
# if Piecewise modifies cond too
# much it may not be recognized by
# _condsimp pattern matching so just
# turn off all evaluation
return Piecewise((f, cond), (u, True),
evaluate=False)
elif conds == 'separate':
if len(self.limits) != 1:
raise ValueError(filldedent('''
conds=separate not supported in
multiple integrals'''))
ret = f, cond
else:
ret = f
return ret
meijerg1 = meijerg
if (meijerg is not False and
len(xab) == 3 and xab[1].is_extended_real and xab[2].is_extended_real
and not function.is_Poly and
(xab[1].has(oo, -oo) or xab[2].has(oo, -oo))):
ret = try_meijerg(function, xab)
if ret is not None:
function = ret
continue
meijerg1 = False
# If the special meijerg code did not succeed in
# finding a definite integral, then the code using
# meijerint_indefinite will not either (it might
# find an antiderivative, but the answer is likely
# to be nonsensical). Thus if we are requested to
# only use Meijer G-function methods, we give up at
# this stage. Otherwise we just disable G-function
# methods.
if meijerg1 is False and meijerg is True:
antideriv = None
else:
antideriv = self._eval_integral(
function, xab[0], **eval_kwargs)
if antideriv is None and meijerg is True:
ret = try_meijerg(function, xab)
if ret is not None:
function = ret
continue
final = hints.get('final', True)
# dotit may be iterated but floor terms making atan and acot
# continuous should only be added in the final round
if (final and not isinstance(antideriv, Integral) and
antideriv is not None):
for atan_term in antideriv.atoms(atan):
atan_arg = atan_term.args[0]
# Checking `atan_arg` to be linear combination of `tan` or `cot`
for tan_part in atan_arg.atoms(tan):
x1 = Dummy('x1')
tan_exp1 = atan_arg.subs(tan_part, x1)
# The coefficient of `tan` should be constant
coeff = tan_exp1.diff(x1)
if x1 not in coeff.free_symbols:
a = tan_part.args[0]
antideriv = antideriv.subs(atan_term, Add(atan_term,
sign(coeff)*pi*floor((a-pi/2)/pi)))
for cot_part in atan_arg.atoms(cot):
x1 = Dummy('x1')
cot_exp1 = atan_arg.subs(cot_part, x1)
# The coefficient of `cot` should be constant
coeff = cot_exp1.diff(x1)
if x1 not in coeff.free_symbols:
a = cot_part.args[0]
antideriv = antideriv.subs(atan_term, Add(atan_term,
sign(coeff)*pi*floor((a)/pi)))
if antideriv is None:
undone_limits.append(xab)
function = self.func(*([function] + [xab])).factor()
factored_function = function.factor()
if not isinstance(factored_function, Integral):
function = factored_function
continue
else:
if len(xab) == 1:
function = antideriv
else:
if len(xab) == 3:
x, a, b = xab
elif len(xab) == 2:
x, b = xab
a = None
else:
raise NotImplementedError
if deep:
if isinstance(a, Basic):
a = a.doit(**hints)
if isinstance(b, Basic):
b = b.doit(**hints)
if antideriv.is_Poly:
gens = list(antideriv.gens)
gens.remove(x)
antideriv = antideriv.as_expr()
function = antideriv._eval_interval(x, a, b)
function = Poly(function, *gens)
else:
def is_indef_int(g, x):
return (isinstance(g, Integral) and
any(i == (x,) for i in g.limits))
def eval_factored(f, x, a, b):
# _eval_interval for integrals with
# (constant) factors
# a single indefinite integral is assumed
args = []
for g in Mul.make_args(f):
if is_indef_int(g, x):
args.append(g._eval_interval(x, a, b))
else:
args.append(g)
return Mul(*args)
integrals, others, piecewises = [], [], []
for f in Add.make_args(antideriv):
if any(is_indef_int(g, x)
for g in Mul.make_args(f)):
integrals.append(f)
elif any(isinstance(g, Piecewise)
for g in Mul.make_args(f)):
piecewises.append(piecewise_fold(f))
else:
others.append(f)
uneval = Add(*[eval_factored(f, x, a, b)
for f in integrals])
try:
evalued = Add(*others)._eval_interval(x, a, b)
evalued_pw = piecewise_fold(Add(*piecewises))._eval_interval(x, a, b)
function = uneval + evalued + evalued_pw
except NotImplementedError:
# This can happen if _eval_interval depends in a
# complicated way on limits that cannot be computed
undone_limits.append(xab)
function = self.func(*([function] + [xab]))
factored_function = function.factor()
if not isinstance(factored_function, Integral):
function = factored_function
return function
def _eval_derivative(self, sym):
"""Evaluate the derivative of the current Integral object by
differentiating under the integral sign [1], using the Fundamental
Theorem of Calculus [2] when possible.
Explanation
===========
Whenever an Integral is encountered that is equivalent to zero or
has an integrand that is independent of the variable of integration
those integrals are performed. All others are returned as Integral
instances which can be resolved with doit() (provided they are integrable).
References
==========
.. [1] https://en.wikipedia.org/wiki/Differentiation_under_the_integral_sign
.. [2] https://en.wikipedia.org/wiki/Fundamental_theorem_of_calculus
Examples
========
>>> from sympy import Integral
>>> from sympy.abc import x, y
>>> i = Integral(x + y, y, (y, 1, x))
>>> i.diff(x)
Integral(x + y, (y, x)) + Integral(1, y, (y, 1, x))
>>> i.doit().diff(x) == i.diff(x).doit()
True
>>> i.diff(y)
0
The previous must be true since there is no y in the evaluated integral:
>>> i.free_symbols
{x}
>>> i.doit()
2*x**3/3 - x/2 - 1/6
"""
# differentiate under the integral sign; we do not
# check for regularity conditions (TODO), see issue 4215
# get limits and the function
f, limits = self.function, list(self.limits)
# the order matters if variables of integration appear in the limits
# so work our way in from the outside to the inside.
limit = limits.pop(-1)
if len(limit) == 3:
x, a, b = limit
elif len(limit) == 2:
x, b = limit
a = None
else:
a = b = None
x = limit[0]
if limits: # f is the argument to an integral
f = self.func(f, *tuple(limits))
# assemble the pieces
def _do(f, ab):
dab_dsym = diff(ab, sym)
if not dab_dsym:
return S.Zero
if isinstance(f, Integral):
limits = [(x, x) if (len(l) == 1 and l[0] == x) else l
for l in f.limits]
f = self.func(f.function, *limits)
return f.subs(x, ab)*dab_dsym
rv = S.Zero
if b is not None:
rv += _do(f, b)
if a is not None:
rv -= _do(f, a)
if len(limit) == 1 and sym == x:
# the dummy variable *is* also the real-world variable
arg = f
rv += arg
else:
# the dummy variable might match sym but it's
# only a dummy and the actual variable is determined
# by the limits, so mask off the variable of integration
# while differentiating
u = Dummy('u')
arg = f.subs(x, u).diff(sym).subs(u, x)
if arg:
rv += self.func(arg, (x, a, b))
return rv
def _eval_integral(self, f, x, meijerg=None, risch=None, manual=None,
heurisch=None, conds='piecewise',final=None):
"""
Calculate the anti-derivative to the function f(x).
Explanation
===========
The following algorithms are applied (roughly in this order):
1. Simple heuristics (based on pattern matching and integral table):
- most frequently used functions (e.g. polynomials, products of
trig functions)
2. Integration of rational functions:
- A complete algorithm for integrating rational functions is
implemented (the Lazard-Rioboo-Trager algorithm). The algorithm
also uses the partial fraction decomposition algorithm
implemented in apart() as a preprocessor to make this process
faster. Note that the integral of a rational function is always
elementary, but in general, it may include a RootSum.
3. Full Risch algorithm:
- The Risch algorithm is a complete decision
procedure for integrating elementary functions, which means that
given any elementary function, it will either compute an
elementary antiderivative, or else prove that none exists.
Currently, part of transcendental case is implemented, meaning
elementary integrals containing exponentials, logarithms, and
(soon!) trigonometric functions can be computed. The algebraic
case, e.g., functions containing roots, is much more difficult
and is not implemented yet.
- If the routine fails (because the integrand is not elementary, or
because a case is not implemented yet), it continues on to the
next algorithms below. If the routine proves that the integrals
is nonelementary, it still moves on to the algorithms below,
because we might be able to find a closed-form solution in terms
of special functions. If risch=True, however, it will stop here.
4. The Meijer G-Function algorithm:
- This algorithm works by first rewriting the integrand in terms of
very general Meijer G-Function (meijerg in SymPy), integrating
it, and then rewriting the result back, if possible. This
algorithm is particularly powerful for definite integrals (which
is actually part of a different method of Integral), since it can
compute closed-form solutions of definite integrals even when no
closed-form indefinite integral exists. But it also is capable
of computing many indefinite integrals as well.
- Another advantage of this method is that it can use some results
about the Meijer G-Function to give a result in terms of a
Piecewise expression, which allows to express conditionally
convergent integrals.
- Setting meijerg=True will cause integrate() to use only this
method.
5. The "manual integration" algorithm:
- This algorithm tries to mimic how a person would find an
antiderivative by hand, for example by looking for a
substitution or applying integration by parts. This algorithm
does not handle as many integrands but can return results in a
more familiar form.
- Sometimes this algorithm can evaluate parts of an integral; in
this case integrate() will try to evaluate the rest of the
integrand using the other methods here.
- Setting manual=True will cause integrate() to use only this
method.
6. The Heuristic Risch algorithm:
- This is a heuristic version of the Risch algorithm, meaning that
it is not deterministic. This is tried as a last resort because
it can be very slow. It is still used because not enough of the
full Risch algorithm is implemented, so that there are still some
integrals that can only be computed using this method. The goal
is to implement enough of the Risch and Meijer G-function methods
so that this can be deleted.
Setting heurisch=True will cause integrate() to use only this
method. Set heurisch=False to not use it.
"""
from sympy.integrals.risch import risch_integrate, NonElementaryIntegral
from sympy.integrals.manualintegrate import manualintegrate
if risch:
try:
return risch_integrate(f, x, conds=conds)
except NotImplementedError:
return None
if manual:
try:
result = manualintegrate(f, x)
if result is not None and result.func != Integral:
return result
except (ValueError, PolynomialError):
pass
eval_kwargs = {"meijerg": meijerg, "risch": risch, "manual": manual,
"heurisch": heurisch, "conds": conds}
# if it is a poly(x) then let the polynomial integrate itself (fast)
#
# It is important to make this check first, otherwise the other code
# will return a SymPy expression instead of a Polynomial.
#
# see Polynomial for details.
if isinstance(f, Poly) and not (manual or meijerg or risch):
# Note: this is deprecated, but the deprecation warning is already
# issued in the Integral constructor.
return f.integrate(x)
# Piecewise antiderivatives need to call special integrate.
if isinstance(f, Piecewise):
return f.piecewise_integrate(x, **eval_kwargs)
# let's cut it short if `f` does not depend on `x`; if
# x is only a dummy, that will be handled below
if not f.has(x):
return f*x
# try to convert to poly(x) and then integrate if successful (fast)
poly = f.as_poly(x)
if poly is not None and not (manual or meijerg or risch):
return poly.integrate().as_expr()
if risch is not False:
try:
result, i = risch_integrate(f, x, separate_integral=True,
conds=conds)
except NotImplementedError:
pass
else:
if i:
# There was a nonelementary integral. Try integrating it.
# if no part of the NonElementaryIntegral is integrated by
# the Risch algorithm, then use the original function to
# integrate, instead of re-written one
if result == 0:
return NonElementaryIntegral(f, x).doit(risch=False)
else:
return result + i.doit(risch=False)
else:
return result
# since Integral(f=g1+g2+...) == Integral(g1) + Integral(g2) + ...
# we are going to handle Add terms separately,
# if `f` is not Add -- we only have one term
# Note that in general, this is a bad idea, because Integral(g1) +
# Integral(g2) might not be computable, even if Integral(g1 + g2) is.
# For example, Integral(x**x + x**x*log(x)). But many heuristics only
# work term-wise. So we compute this step last, after trying
# risch_integrate. We also try risch_integrate again in this loop,
# because maybe the integral is a sum of an elementary part and a
# nonelementary part (like erf(x) + exp(x)). risch_integrate() is
# quite fast, so this is acceptable.
from sympy.simplify.fu import sincos_to_sum
parts = []
args = Add.make_args(f)
for g in args:
coeff, g = g.as_independent(x)
# g(x) = const
if g is S.One and not meijerg:
parts.append(coeff*x)
continue
# g(x) = expr + O(x**n)
order_term = g.getO()
if order_term is not None:
h = self._eval_integral(g.removeO(), x, **eval_kwargs)
if h is not None:
h_order_expr = self._eval_integral(order_term.expr, x, **eval_kwargs)
if h_order_expr is not None:
h_order_term = order_term.func(
h_order_expr, *order_term.variables)
parts.append(coeff*(h + h_order_term))
continue
# NOTE: if there is O(x**n) and we fail to integrate then
# there is no point in trying other methods because they
# will fail, too.
return None
# c
# g(x) = (a*x+b)
if g.is_Pow and not g.exp.has(x) and not meijerg:
a = Wild('a', exclude=[x])
b = Wild('b', exclude=[x])
M = g.base.match(a*x + b)
if M is not None:
if g.exp == -1:
h = log(g.base)
elif conds != 'piecewise':
h = g.base**(g.exp + 1) / (g.exp + 1)
else:
h1 = log(g.base)
h2 = g.base**(g.exp + 1) / (g.exp + 1)
h = Piecewise((h2, Ne(g.exp, -1)), (h1, True))
parts.append(coeff * h / M[a])
continue
# poly(x)
# g(x) = -------
# poly(x)
if g.is_rational_function(x) and not (manual or meijerg or risch):
parts.append(coeff * ratint(g, x))
continue
if not (manual or meijerg or risch):
# g(x) = Mul(trig)
h = trigintegrate(g, x, conds=conds)
if h is not None:
parts.append(coeff * h)
continue
# g(x) has at least a DiracDelta term
h = deltaintegrate(g, x)
if h is not None:
parts.append(coeff * h)
continue
from .singularityfunctions import singularityintegrate
# g(x) has at least a Singularity Function term
h = singularityintegrate(g, x)
if h is not None:
parts.append(coeff * h)
continue
# Try risch again.
if risch is not False:
try:
h, i = risch_integrate(g, x,
separate_integral=True, conds=conds)
except NotImplementedError:
h = None
else:
if i:
h = h + i.doit(risch=False)
parts.append(coeff*h)
continue
# fall back to heurisch
if heurisch is not False:
from sympy.integrals.heurisch import (heurisch as heurisch_,
heurisch_wrapper)
try:
if conds == 'piecewise':
h = heurisch_wrapper(g, x, hints=[])
else:
h = heurisch_(g, x, hints=[])
except PolynomialError:
# XXX: this exception means there is a bug in the
# implementation of heuristic Risch integration
# algorithm.
h = None
else:
h = None
if meijerg is not False and h is None:
# rewrite using G functions
try:
h = meijerint_indefinite(g, x)
except NotImplementedError:
_debug('NotImplementedError from meijerint_definite')
if h is not None:
parts.append(coeff * h)
continue
if h is None and manual is not False:
try:
result = manualintegrate(g, x)
if result is not None and not isinstance(result, Integral):
if result.has(Integral) and not manual:
# Try to have other algorithms do the integrals
# manualintegrate can't handle,
# unless we were asked to use manual only.
# Keep the rest of eval_kwargs in case another
# method was set to False already
new_eval_kwargs = eval_kwargs
new_eval_kwargs["manual"] = False
new_eval_kwargs["final"] = False
result = result.func(*[
arg.doit(**new_eval_kwargs) if
arg.has(Integral) else arg
for arg in result.args
]).expand(multinomial=False,
log=False,
power_exp=False,
power_base=False)
if not result.has(Integral):
parts.append(coeff * result)
continue
except (ValueError, PolynomialError):
# can't handle some SymPy expressions
pass
# if we failed maybe it was because we had
# a product that could have been expanded,
# so let's try an expansion of the whole
# thing before giving up; we don't try this
# at the outset because there are things
# that cannot be solved unless they are
# NOT expanded e.g., x**x*(1+log(x)). There
# should probably be a checker somewhere in this
# routine to look for such cases and try to do
# collection on the expressions if they are already
# in an expanded form
if not h and len(args) == 1:
f = sincos_to_sum(f).expand(mul=True, deep=False)
if f.is_Add:
# Note: risch will be identical on the expanded
# expression, but maybe it will be able to pick out parts,
# like x*(exp(x) + erf(x)).
return self._eval_integral(f, x, **eval_kwargs)
if h is not None:
parts.append(coeff * h)
else:
return None
return Add(*parts)
def _eval_lseries(self, x, logx=None, cdir=0):
expr = self.as_dummy()
symb = x
for l in expr.limits:
if x in l[1:]:
symb = l[0]
break
for term in expr.function.lseries(symb, logx):
yield integrate(term, *expr.limits)
def _eval_nseries(self, x, n, logx=None, cdir=0):
symb = x
for l in self.limits:
if x in l[1:]:
symb = l[0]
break
terms, order = self.function.nseries(
x=symb, n=n, logx=logx).as_coeff_add(Order)
order = [o.subs(symb, x) for o in order]
return integrate(terms, *self.limits) + Add(*order)*x
def _eval_as_leading_term(self, x, logx, cdir):
series_gen = self.args[0].lseries(x)
for leading_term in series_gen:
if leading_term != 0:
break
return integrate(leading_term, *self.args[1:])
def _eval_simplify(self, **kwargs):
expr = factor_terms(self)
if isinstance(expr, Integral):
from sympy.simplify.simplify import simplify
return expr.func(*[simplify(i, **kwargs) for i in expr.args])
return expr.simplify(**kwargs)
def as_sum(self, n=None, method="midpoint", evaluate=True):
"""
Approximates a definite integral by a sum.
Parameters
==========
n :
The number of subintervals to use, optional.
method :
One of: 'left', 'right', 'midpoint', 'trapezoid'.
evaluate : bool
If False, returns an unevaluated Sum expression. The default
is True, evaluate the sum.
Notes
=====
These methods of approximate integration are described in [1].
Examples
========
>>> from sympy import Integral, sin, sqrt
>>> from sympy.abc import x, n
>>> e = Integral(sin(x), (x, 3, 7))
>>> e
Integral(sin(x), (x, 3, 7))
For demonstration purposes, this interval will only be split into 2
regions, bounded by [3, 5] and [5, 7].
The left-hand rule uses function evaluations at the left of each
interval:
>>> e.as_sum(2, 'left')
2*sin(5) + 2*sin(3)
The midpoint rule uses evaluations at the center of each interval:
>>> e.as_sum(2, 'midpoint')
2*sin(4) + 2*sin(6)
The right-hand rule uses function evaluations at the right of each
interval:
>>> e.as_sum(2, 'right')
2*sin(5) + 2*sin(7)
The trapezoid rule uses function evaluations on both sides of the
intervals. This is equivalent to taking the average of the left and
right hand rule results:
>>> s = e.as_sum(2, 'trapezoid')
>>> s
2*sin(5) + sin(3) + sin(7)
>>> (e.as_sum(2, 'left') + e.as_sum(2, 'right'))/2 == s
True
Here, the discontinuity at x = 0 can be avoided by using the
midpoint or right-hand method:
>>> e = Integral(1/sqrt(x), (x, 0, 1))
>>> e.as_sum(5).n(4)
1.730
>>> e.as_sum(10).n(4)
1.809
>>> e.doit().n(4) # the actual value is 2
2.000
The left- or trapezoid method will encounter the discontinuity and
return infinity:
>>> e.as_sum(5, 'left')
zoo
The number of intervals can be symbolic. If omitted, a dummy symbol
will be used for it.
>>> e = Integral(x**2, (x, 0, 2))
>>> e.as_sum(n, 'right').expand()
8/3 + 4/n + 4/(3*n**2)
This shows that the midpoint rule is more accurate, as its error
term decays as the square of n:
>>> e.as_sum(method='midpoint').expand()
8/3 - 2/(3*_n**2)
A symbolic sum is returned with evaluate=False:
>>> e.as_sum(n, 'midpoint', evaluate=False)
2*Sum((2*_k/n - 1/n)**2, (_k, 1, n))/n
See Also
========
Integral.doit : Perform the integration using any hints
References
==========
.. [1] https://en.wikipedia.org/wiki/Riemann_sum#Riemann_summation_methods
"""
from sympy.concrete.summations import Sum
limits = self.limits
if len(limits) > 1:
raise NotImplementedError(
"Multidimensional midpoint rule not implemented yet")
else:
limit = limits[0]
if (len(limit) != 3 or limit[1].is_finite is False or
limit[2].is_finite is False):
raise ValueError("Expecting a definite integral over "
"a finite interval.")
if n is None:
n = Dummy('n', integer=True, positive=True)
else:
n = sympify(n)
if (n.is_positive is False or n.is_integer is False or
n.is_finite is False):
raise ValueError("n must be a positive integer, got %s" % n)
x, a, b = limit
dx = (b - a)/n
k = Dummy('k', integer=True, positive=True)
f = self.function
if method == "left":
result = dx*Sum(f.subs(x, a + (k-1)*dx), (k, 1, n))
elif method == "right":
result = dx*Sum(f.subs(x, a + k*dx), (k, 1, n))
elif method == "midpoint":
result = dx*Sum(f.subs(x, a + k*dx - dx/2), (k, 1, n))
elif method == "trapezoid":
result = dx*((f.subs(x, a) + f.subs(x, b))/2 +
Sum(f.subs(x, a + k*dx), (k, 1, n - 1)))
else:
raise ValueError("Unknown method %s" % method)
return result.doit() if evaluate else result
def principal_value(self, **kwargs):
"""
Compute the Cauchy Principal Value of the definite integral of a real function in the given interval
on the real axis.
Explanation
===========
In mathematics, the Cauchy principal value, is a method for assigning values to certain improper
integrals which would otherwise be undefined.
Examples
========
>>> from sympy import Integral, oo
>>> from sympy.abc import x
>>> Integral(x+1, (x, -oo, oo)).principal_value()
oo
>>> f = 1 / (x**3)
>>> Integral(f, (x, -oo, oo)).principal_value()
0
>>> Integral(f, (x, -10, 10)).principal_value()
0
>>> Integral(f, (x, -10, oo)).principal_value() + Integral(f, (x, -oo, 10)).principal_value()
0
References
==========
.. [1] https://en.wikipedia.org/wiki/Cauchy_principal_value
.. [2] https://mathworld.wolfram.com/CauchyPrincipalValue.html
"""
if len(self.limits) != 1 or len(list(self.limits[0])) != 3:
raise ValueError("You need to insert a variable, lower_limit, and upper_limit correctly to calculate "
"cauchy's principal value")
x, a, b = self.limits[0]
if not (a.is_comparable and b.is_comparable and a <= b):
raise ValueError("The lower_limit must be smaller than or equal to the upper_limit to calculate "
"cauchy's principal value. Also, a and b need to be comparable.")
if a == b:
return S.Zero
from sympy.calculus.singularities import singularities
r = Dummy('r')
f = self.function
singularities_list = [s for s in singularities(f, x) if s.is_comparable and a <= s <= b]
for i in singularities_list:
if i in (a, b):
raise ValueError(
'The principal value is not defined in the given interval due to singularity at %d.' % (i))
F = integrate(f, x, **kwargs)
if F.has(Integral):
return self
if a is -oo and b is oo:
I = limit(F - F.subs(x, -x), x, oo)
else:
I = limit(F, x, b, '-') - limit(F, x, a, '+')
for s in singularities_list:
I += limit(((F.subs(x, s - r)) - F.subs(x, s + r)), r, 0, '+')
return I
def integrate(function, *symbols: SymbolLimits, meijerg=None, conds='piecewise',
risch=None, heurisch=None, manual=None, **kwargs):
"""integrate(f, var, ...)
.. deprecated:: 1.6
Using ``integrate()`` with :class:`~.Poly` is deprecated. Use
:meth:`.Poly.integrate` instead. See :ref:`deprecated-integrate-poly`.
Explanation
===========
Compute definite or indefinite integral of one or more variables
using Risch-Norman algorithm and table lookup. This procedure is
able to handle elementary algebraic and transcendental functions
and also a huge class of special functions, including Airy,
Bessel, Whittaker and Lambert.
var can be:
- a symbol -- indefinite integration
- a tuple (symbol, a) -- indefinite integration with result
given with ``a`` replacing ``symbol``
- a tuple (symbol, a, b) -- definite integration
Several variables can be specified, in which case the result is
multiple integration. (If var is omitted and the integrand is
univariate, the indefinite integral in that variable will be performed.)
Indefinite integrals are returned without terms that are independent
of the integration variables. (see examples)
Definite improper integrals often entail delicate convergence
conditions. Pass conds='piecewise', 'separate' or 'none' to have
these returned, respectively, as a Piecewise function, as a separate
result (i.e. result will be a tuple), or not at all (default is
'piecewise').
**Strategy**
SymPy uses various approaches to definite integration. One method is to
find an antiderivative for the integrand, and then use the fundamental
theorem of calculus. Various functions are implemented to integrate
polynomial, rational and trigonometric functions, and integrands
containing DiracDelta terms.
SymPy also implements the part of the Risch algorithm, which is a decision
procedure for integrating elementary functions, i.e., the algorithm can
either find an elementary antiderivative, or prove that one does not
exist. There is also a (very successful, albeit somewhat slow) general
implementation of the heuristic Risch algorithm. This algorithm will
eventually be phased out as more of the full Risch algorithm is
implemented. See the docstring of Integral._eval_integral() for more
details on computing the antiderivative using algebraic methods.
The option risch=True can be used to use only the (full) Risch algorithm.
This is useful if you want to know if an elementary function has an
elementary antiderivative. If the indefinite Integral returned by this
function is an instance of NonElementaryIntegral, that means that the
Risch algorithm has proven that integral to be non-elementary. Note that
by default, additional methods (such as the Meijer G method outlined
below) are tried on these integrals, as they may be expressible in terms
of special functions, so if you only care about elementary answers, use
risch=True. Also note that an unevaluated Integral returned by this
function is not necessarily a NonElementaryIntegral, even with risch=True,
as it may just be an indication that the particular part of the Risch
algorithm needed to integrate that function is not yet implemented.
Another family of strategies comes from re-writing the integrand in
terms of so-called Meijer G-functions. Indefinite integrals of a
single G-function can always be computed, and the definite integral
of a product of two G-functions can be computed from zero to
infinity. Various strategies are implemented to rewrite integrands
as G-functions, and use this information to compute integrals (see
the ``meijerint`` module).
The option manual=True can be used to use only an algorithm that tries
to mimic integration by hand. This algorithm does not handle as many
integrands as the other algorithms implemented but may return results in
a more familiar form. The ``manualintegrate`` module has functions that
return the steps used (see the module docstring for more information).
In general, the algebraic methods work best for computing
antiderivatives of (possibly complicated) combinations of elementary
functions. The G-function methods work best for computing definite
integrals from zero to infinity of moderately complicated
combinations of special functions, or indefinite integrals of very
simple combinations of special functions.
The strategy employed by the integration code is as follows:
- If computing a definite integral, and both limits are real,
and at least one limit is +- oo, try the G-function method of
definite integration first.
- Try to find an antiderivative, using all available methods, ordered
by performance (that is try fastest method first, slowest last; in
particular polynomial integration is tried first, Meijer
G-functions second to last, and heuristic Risch last).
- If still not successful, try G-functions irrespective of the
limits.
The option meijerg=True, False, None can be used to, respectively:
always use G-function methods and no others, never use G-function
methods, or use all available methods (in order as described above).
It defaults to None.
Examples
========
>>> from sympy import integrate, log, exp, oo
>>> from sympy.abc import a, x, y
>>> integrate(x*y, x)
x**2*y/2
>>> integrate(log(x), x)
x*log(x) - x
>>> integrate(log(x), (x, 1, a))
a*log(a) - a + 1
>>> integrate(x)
x**2/2
Terms that are independent of x are dropped by indefinite integration:
>>> from sympy import sqrt
>>> integrate(sqrt(1 + x), (x, 0, x))
2*(x + 1)**(3/2)/3 - 2/3
>>> integrate(sqrt(1 + x), x)
2*(x + 1)**(3/2)/3
>>> integrate(x*y)
Traceback (most recent call last):
...
ValueError: specify integration variables to integrate x*y
Note that ``integrate(x)`` syntax is meant only for convenience
in interactive sessions and should be avoided in library code.
>>> integrate(x**a*exp(-x), (x, 0, oo)) # same as conds='piecewise'
Piecewise((gamma(a + 1), re(a) > -1),
(Integral(x**a*exp(-x), (x, 0, oo)), True))
>>> integrate(x**a*exp(-x), (x, 0, oo), conds='none')
gamma(a + 1)
>>> integrate(x**a*exp(-x), (x, 0, oo), conds='separate')
(gamma(a + 1), re(a) > -1)
See Also
========
Integral, Integral.doit
"""
doit_flags = {
'deep': False,
'meijerg': meijerg,
'conds': conds,
'risch': risch,
'heurisch': heurisch,
'manual': manual
}
integral = Integral(function, *symbols, **kwargs)
if isinstance(integral, Integral):
return integral.doit(**doit_flags)
else:
new_args = [a.doit(**doit_flags) if isinstance(a, Integral) else a
for a in integral.args]
return integral.func(*new_args)
def line_integrate(field, curve, vars):
"""line_integrate(field, Curve, variables)
Compute the line integral.
Examples
========
>>> from sympy import Curve, line_integrate, E, ln
>>> from sympy.abc import x, y, t
>>> C = Curve([E**t + 1, E**t - 1], (t, 0, ln(2)))
>>> line_integrate(x + y, C, [x, y])
3*sqrt(2)
See Also
========
sympy.integrals.integrals.integrate, Integral
"""
from sympy.geometry import Curve
F = sympify(field)
if not F:
raise ValueError(
"Expecting function specifying field as first argument.")
if not isinstance(curve, Curve):
raise ValueError("Expecting Curve entity as second argument.")
if not is_sequence(vars):
raise ValueError("Expecting ordered iterable for variables.")
if len(curve.functions) != len(vars):
raise ValueError("Field variable size does not match curve dimension.")
if curve.parameter in vars:
raise ValueError("Curve parameter clashes with field parameters.")
# Calculate derivatives for line parameter functions
# F(r) -> F(r(t)) and finally F(r(t)*r'(t))
Ft = F
dldt = 0
for i, var in enumerate(vars):
_f = curve.functions[i]
_dn = diff(_f, curve.parameter)
# ...arc length
dldt = dldt + (_dn * _dn)
Ft = Ft.subs(var, _f)
Ft = Ft * sqrt(dldt)
integral = Integral(Ft, curve.limits).doit(deep=False)
return integral
### Property function dispatching ###
@shape.register(Integral)
def _(expr):
return shape(expr.function)
# Delayed imports
from .deltafunctions import deltaintegrate
from .meijerint import meijerint_definite, meijerint_indefinite, _debug
from .trigonometry import trigintegrate
| Integral |
python | great-expectations__great_expectations | great_expectations/util.py | {
"start": 2305,
"end": 49347
} | class ____(dict):
"""
Bi-directional hashmap: https://stackoverflow.com/a/21894086
"""
def __init__(self, *args: List[Any], **kwargs: Dict[str, Any]) -> None:
super().__init__(*args, **kwargs)
self.inverse: Dict = {}
for key, value in self.items():
self.inverse.setdefault(value, []).append(key)
@override
def __setitem__(self, key: str, value: Any) -> None:
if key in self:
self.inverse[self[key]].remove(key)
super().__setitem__(key, value)
self.inverse.setdefault(value, []).append(key)
@override
def __delitem__(self, key: str):
self.inverse.setdefault(self[key], []).remove(key)
if self[key] in self.inverse and not self.inverse[self[key]]:
del self.inverse[self[key]]
super().__delitem__(key)
def camel_to_snake(name: str) -> str:
name = p1.sub(r"\1_\2", name)
return p2.sub(r"\1_\2", name).lower()
def hyphen(txt: str):
return txt.replace("_", "-")
def measure_execution_time(
execution_time_holder_object_reference_name: str = "execution_time_holder",
execution_time_property_name: str = "execution_time",
method: str = "process_time",
pretty_print: bool = True,
include_arguments: bool = True,
) -> Callable:
"""
Parameterizes template "execution_time_decorator" function with options, supplied as arguments.
Args:
execution_time_holder_object_reference_name: Handle, provided in "kwargs", holds execution time property setter.
execution_time_property_name: Property attribute name, provided in "kwargs", sets execution time value.
method: Name of method in "time" module (default: "process_time") to be used for recording timestamps.
pretty_print: If True (default), prints execution time summary to standard output; if False, "silent" mode.
include_arguments: If True (default), prints arguments of function, whose execution time is measured.
Note: Method "time.perf_counter()" keeps going during sleep, while method "time.process_time()" does not.
Using "time.process_time()" is the better suited method for measuring code computational efficiency.
Returns:
Callable -- configured "execution_time_decorator" function.
""" # noqa: E501 # FIXME CoP
def execution_time_decorator(func: Callable) -> Callable:
@wraps(func)
def compute_delta_t(*args, **kwargs) -> Any:
"""
Computes return value of decorated function, calls back "execution_time_holder_object_reference_name", and
saves execution time (in seconds) into specified "execution_time_property_name" of passed object reference.
Settable "{execution_time_holder_object_reference_name}.{execution_time_property_name}" property must exist.
Args:
args: Positional arguments of original function being decorated.
kwargs: Keyword arguments of original function being decorated.
Returns:
Any (output value of original function being decorated).
""" # noqa: E501 # FIXME CoP
time_begin: float = (getattr(time, method))()
try:
return func(*args, **kwargs)
finally:
time_end: float = (getattr(time, method))()
delta_t: float = time_end - time_begin
if kwargs is None:
kwargs = {}
execution_time_holder: type = kwargs.get( # type: ignore[assignment] # FIXME CoP
execution_time_holder_object_reference_name
)
if execution_time_holder is not None and hasattr(
execution_time_holder, execution_time_property_name
):
setattr(execution_time_holder, execution_time_property_name, delta_t)
if pretty_print:
if include_arguments:
bound_args: BoundArguments = signature(func).bind(*args, **kwargs)
call_args: OrderedDict = bound_args.arguments
print(
f"""Total execution time of function {func.__name__}({dict(call_args)!s}): {delta_t} \
seconds.""" # noqa: E501 # FIXME CoP
)
else:
print(
f"Total execution time of function {func.__name__}(): {delta_t} seconds." # noqa: E501 # FIXME CoP
)
return compute_delta_t
return execution_time_decorator
def verify_dynamic_loading_support(module_name: str, package_name: Optional[str] = None) -> None:
"""
:param module_name: a possibly-relative name of a module
:param package_name: the name of a package, to which the given module belongs
"""
# noinspection PyUnresolvedReferences
module_spec: Optional[importlib.machinery.ModuleSpec]
try:
# noinspection PyUnresolvedReferences
module_spec = importlib.util.find_spec(module_name, package=package_name)
except ModuleNotFoundError:
module_spec = None
if not module_spec:
if not package_name:
package_name = ""
message: str = f"""No module named "{package_name + module_name}" could be found in the repository. Please \
make sure that the file, corresponding to this package and module, exists and that dynamic loading of code modules, \
templates, and assets is supported in your execution environment. This error is unrecoverable.
""" # noqa: E501 # FIXME CoP
raise FileNotFoundError(message)
def import_library_module(module_name: str) -> Optional[ModuleType]:
"""
:param module_name: a fully-qualified name of a module (e.g., "great_expectations.dataset.sqlalchemy_dataset")
:return: raw source code of the module (if can be retrieved)
""" # noqa: E501 # FIXME CoP
module_obj: Optional[ModuleType]
try:
module_obj = importlib.import_module(module_name)
except ImportError:
module_obj = None
return module_obj
def is_library_loadable(library_name: str) -> bool:
module_obj: Optional[ModuleType] = import_library_module(module_name=library_name)
return module_obj is not None
def load_class(class_name: str, module_name: str) -> type:
if class_name is None:
raise TypeError("class_name must not be None") # noqa: TRY003 # FIXME CoP
if not isinstance(class_name, str):
raise TypeError("class_name must be a string") # noqa: TRY003 # FIXME CoP
if module_name is None:
raise TypeError("module_name must not be None") # noqa: TRY003 # FIXME CoP
if not isinstance(module_name, str):
raise TypeError("module_name must be a string") # noqa: TRY003 # FIXME CoP
try:
verify_dynamic_loading_support(module_name=module_name)
except FileNotFoundError:
raise PluginModuleNotFoundError(module_name)
module_obj: Optional[ModuleType] = import_library_module(module_name=module_name)
if module_obj is None:
raise PluginModuleNotFoundError(module_name)
try:
klass_ = getattr(module_obj, class_name)
except AttributeError:
raise PluginClassNotFoundError(module_name=module_name, class_name=class_name)
return klass_
def build_in_memory_runtime_context() -> AbstractDataContext:
"""
Create generic in-memory "BaseDataContext" context for manipulations as required by tests.
Args:
include_pandas (bool): If True, include pandas datasource
include_spark (bool): If True, include spark datasource
"""
from great_expectations.data_context.types.base import (
DataContextConfig,
InMemoryStoreBackendDefaults,
)
data_context_config: DataContextConfig = DataContextConfig(
expectations_store_name="expectations_store",
validation_results_store_name="validation_results_store",
checkpoint_store_name="checkpoint_store",
store_backend_defaults=InMemoryStoreBackendDefaults(),
)
from great_expectations.data_context.data_context.context_factory import (
get_context as context_factory,
)
context = context_factory(project_config=data_context_config, mode="ephemeral")
return context
# https://stackoverflow.com/questions/9727673/list-directory-tree-structure-in-python
def gen_directory_tree_str(startpath: PathStr):
"""Print the structure of directory as a tree:
Ex:
project_dir0/
AAA/
BBB/
aaa.txt
bbb.txt
#Note: files and directories are sorted alphabetically, so that this method can be used for testing.
""" # noqa: E501 # FIXME CoP
output_str = ""
tuples = list(os.walk(startpath))
tuples.sort()
for root, dirs, files in tuples:
level = root.replace(str(startpath), "").count(os.sep)
indent = " " * 4 * level
output_str += f"{indent}{os.path.basename(root)}/\n" # noqa: PTH119 # FIXME CoP
subindent = " " * 4 * (level + 1)
files.sort()
for f in files:
output_str += f"{subindent}{f}\n"
return output_str
def filter_properties_dict( # noqa: C901, PLR0912, PLR0913 # FIXME CoP
properties: Optional[dict] = None,
keep_fields: Optional[Set[str]] = None,
delete_fields: Optional[Set[str]] = None,
clean_nulls: bool = True,
clean_falsy: bool = False,
keep_falsy_numerics: bool = True,
inplace: bool = False,
) -> Optional[dict]:
"""Filter the entries of the source dictionary according to directives concerning the existing keys and values.
Args:
properties: source dictionary to be filtered according to the supplied filtering directives
keep_fields: list of keys that must be retained, with the understanding that all other entries will be deleted
delete_fields: list of keys that must be deleted, with the understanding that all other entries will be retained
clean_nulls: If True, then in addition to other filtering directives, delete entries, whose values are None
clean_falsy: If True, then in addition to other filtering directives, delete entries, whose values are Falsy
(If the "clean_falsy" argument is specified as "True", then "clean_nulls" is assumed to be "True" as well.)
inplace: If True, then modify the source properties dictionary; otherwise, make a copy for filtering purposes
keep_falsy_numerics: If True, then in addition to other filtering directives, do not delete zero-valued numerics
Returns:
The (possibly) filtered properties dictionary (or None if no entries remain after filtering is performed)
""" # noqa: E501 # FIXME CoP
if keep_fields is None:
keep_fields = set()
if delete_fields is None:
delete_fields = set()
if keep_fields & delete_fields:
raise ValueError( # noqa: TRY003 # FIXME CoP
"Common keys between sets of keep_fields and delete_fields filtering directives are illegal." # noqa: E501 # FIXME CoP
)
if clean_falsy:
clean_nulls = True
if properties is None:
properties = {}
if not isinstance(properties, dict):
raise ValueError( # noqa: TRY003, TRY004 # FIXME CoP
f'Source "properties" must be a dictionary (illegal type "{type(properties)!s}" detected).' # noqa: E501 # FIXME CoP
)
if not inplace:
properties = copy.deepcopy(properties)
keys_for_deletion: list = []
key: str
value: Any
if keep_fields:
keys_for_deletion.extend(
[key for key, value in properties.items() if key not in keep_fields]
)
if delete_fields:
keys_for_deletion.extend([key for key, value in properties.items() if key in delete_fields])
if clean_nulls:
keys_for_deletion.extend(
[
key
for key, value in properties.items()
if not (
(keep_fields and key in keep_fields)
or (delete_fields and key in delete_fields)
or value is not None
)
]
)
if clean_falsy:
if keep_falsy_numerics:
keys_for_deletion.extend(
[
key
for key, value in properties.items()
if not (
(keep_fields and key in keep_fields)
or (delete_fields and key in delete_fields)
or is_truthy(value=value)
or is_numeric(value=value)
)
]
)
else:
keys_for_deletion.extend(
[
key
for key, value in properties.items()
if not (
(keep_fields and key in keep_fields)
or (delete_fields and key in delete_fields)
or is_truthy(value=value)
)
]
)
keys_for_deletion = list(set(keys_for_deletion))
for key in keys_for_deletion:
del properties[key]
if inplace:
return None
return properties
@overload
def deep_filter_properties_iterable(
properties: dict,
keep_fields: Optional[Set[str]] = ...,
delete_fields: Optional[Set[str]] = ...,
clean_nulls: bool = ...,
clean_falsy: bool = ...,
keep_falsy_numerics: bool = ...,
inplace: bool = ...,
) -> dict: ...
@overload
def deep_filter_properties_iterable(
properties: list,
keep_fields: Optional[Set[str]] = ...,
delete_fields: Optional[Set[str]] = ...,
clean_nulls: bool = ...,
clean_falsy: bool = ...,
keep_falsy_numerics: bool = ...,
inplace: bool = ...,
) -> list: ...
@overload
def deep_filter_properties_iterable(
properties: set,
keep_fields: Optional[Set[str]] = ...,
delete_fields: Optional[Set[str]] = ...,
clean_nulls: bool = ...,
clean_falsy: bool = ...,
keep_falsy_numerics: bool = ...,
inplace: bool = ...,
) -> set: ...
@overload
def deep_filter_properties_iterable(
properties: tuple,
keep_fields: Optional[Set[str]] = ...,
delete_fields: Optional[Set[str]] = ...,
clean_nulls: bool = ...,
clean_falsy: bool = ...,
keep_falsy_numerics: bool = ...,
inplace: bool = ...,
) -> tuple: ...
@overload
def deep_filter_properties_iterable(
properties: None,
keep_fields: Optional[Set[str]] = ...,
delete_fields: Optional[Set[str]] = ...,
clean_nulls: bool = ...,
clean_falsy: bool = ...,
keep_falsy_numerics: bool = ...,
inplace: bool = ...,
) -> None: ...
def deep_filter_properties_iterable( # noqa: C901, PLR0913 # FIXME CoP
properties: Union[dict, list, set, tuple, None] = None,
keep_fields: Optional[Set[str]] = None,
delete_fields: Optional[Set[str]] = None,
clean_nulls: bool = True,
clean_falsy: bool = False,
keep_falsy_numerics: bool = True,
inplace: bool = False,
) -> Union[dict, list, set, tuple, None]:
if keep_fields is None:
keep_fields = set()
if delete_fields is None:
delete_fields = set()
if isinstance(properties, dict):
if not inplace:
properties = copy.deepcopy(properties)
filter_properties_dict(
properties=properties,
keep_fields=keep_fields,
delete_fields=delete_fields,
clean_nulls=clean_nulls,
clean_falsy=clean_falsy,
keep_falsy_numerics=keep_falsy_numerics,
inplace=True,
)
key: str
value: Any
for key, value in properties.items():
deep_filter_properties_iterable(
properties=value,
keep_fields=keep_fields,
delete_fields=delete_fields,
clean_nulls=clean_nulls,
clean_falsy=clean_falsy,
keep_falsy_numerics=keep_falsy_numerics,
inplace=True,
)
# Upon unwinding the call stack, do a sanity check to ensure cleaned properties.
keys_to_delete: List[str] = list(
filter(
lambda k: k not in keep_fields # type: ignore[arg-type] # FIXME CoP
and _is_to_be_removed_from_deep_filter_properties_iterable(
value=properties[k],
clean_nulls=clean_nulls,
clean_falsy=clean_falsy,
keep_falsy_numerics=keep_falsy_numerics,
),
properties.keys(),
)
)
for key in keys_to_delete:
properties.pop(key)
elif isinstance(properties, (list, set, tuple)):
if not inplace:
properties = copy.deepcopy(properties)
for value in properties:
deep_filter_properties_iterable(
properties=value,
keep_fields=keep_fields,
delete_fields=delete_fields,
clean_nulls=clean_nulls,
clean_falsy=clean_falsy,
keep_falsy_numerics=keep_falsy_numerics,
inplace=True,
)
# Upon unwinding the call stack, do a sanity check to ensure cleaned properties.
properties_type: type = type(properties)
properties = properties_type(
filter(
lambda v: not _is_to_be_removed_from_deep_filter_properties_iterable(
value=v,
clean_nulls=clean_nulls,
clean_falsy=clean_falsy,
keep_falsy_numerics=keep_falsy_numerics,
),
properties,
)
)
if inplace:
return None
return properties
def _is_to_be_removed_from_deep_filter_properties_iterable(
value: Any, clean_nulls: bool, clean_falsy: bool, keep_falsy_numerics: bool
) -> bool:
conditions: Tuple[bool, ...] = (
clean_nulls and value is None,
not keep_falsy_numerics and is_numeric(value) and value == 0,
clean_falsy and not (is_numeric(value) or value),
)
return any(condition for condition in conditions)
def is_truthy(value: Any) -> bool:
try:
return bool(value)
except ValueError:
return False
def is_numeric(value: Any) -> bool:
return value is not None and (is_int(value=value) or is_float(value=value))
def is_int(value: Any) -> bool:
try:
int(value)
except (TypeError, ValueError):
return False
return True
def is_float(value: Any) -> bool:
try:
float(value)
except (TypeError, ValueError):
return False
return True
def is_nan(value: Any) -> bool:
"""
If value is an array, test element-wise for NaN and return result as a boolean array.
If value is a scalar, return boolean.
Args:
value: The value to test
Returns:
The results of the test
"""
import numpy as np
try:
return np.isnan(value)
except TypeError:
return True
def convert_decimal_to_float(d: SupportsFloat) -> float:
"""
This method convers "decimal.Decimal" to standard "float" type.
"""
rule_based_profiler_call: bool = (
len(
list(
filter(
lambda frame_info: Path(frame_info.filename).name == "parameter_builder.py"
and frame_info.function == "get_metrics",
stack(),
)
)
)
> 0
)
if (
not rule_based_profiler_call
and isinstance(d, decimal.Decimal)
and requires_lossy_conversion(d=d)
):
logger.warning(
f"Using lossy conversion for decimal {d} to float object to support serialization."
)
# noinspection PyTypeChecker
return float(d)
def requires_lossy_conversion(d: decimal.Decimal) -> bool:
"""
This method determines whether or not conversion from "decimal.Decimal" to standard "float" type cannot be lossless.
""" # noqa: E501 # FIXME CoP
return d - decimal.Context(prec=sys.float_info.dig).create_decimal(d) != 0
def isclose(
operand_a: Union[datetime.datetime, datetime.timedelta, Number],
operand_b: Union[datetime.datetime, datetime.timedelta, Number],
rtol: float = 1.0e-5, # controls relative weight of "operand_b" (when its magnitude is large)
atol: float = 1.0e-8, # controls absolute accuracy (based on floating point machine precision)
equal_nan: bool = False,
) -> bool:
"""
Checks whether or not two numbers (or timestamps) are approximately close to one another.
According to "https://numpy.org/doc/stable/reference/generated/numpy.isclose.html",
For finite values, isclose uses the following equation to test whether two floating point values are equivalent:
"absolute(a - b) <= (atol + rtol * absolute(b))".
This translates to:
"absolute(operand_a - operand_b) <= (atol + rtol * absolute(operand_b))", where "operand_a" is "target" quantity
under evaluation for being close to a "control" value, and "operand_b" serves as the "control" ("reference") value.
The values of the absolute tolerance ("atol") parameter is chosen as a sufficiently small constant for most floating
point machine representations (e.g., 1.0e-8), so that even if the "control" value is small in magnitude and "target"
and "control" are close in absolute value, then the accuracy of the assessment can still be high up to the precision
of the "atol" value (here, 8 digits as the default). However, when the "control" value is large in magnitude, the
relative tolerance ("rtol") parameter carries a greater weight in the comparison assessment, because the acceptable
deviation between the two quantities can be relatively larger for them to be deemed as "close enough" in this case.
""" # noqa: E501 # FIXME CoP
if isinstance(operand_a, str) and isinstance(operand_b, str):
return operand_a == operand_b
if isinstance(operand_a, datetime.datetime) and isinstance(operand_b, datetime.datetime):
operand_a = operand_a.timestamp() # type: ignore[assignment] # FIXME CoP
operand_b = operand_b.timestamp() # type: ignore[assignment] # FIXME CoP
elif isinstance(operand_a, datetime.timedelta) and isinstance(operand_b, datetime.timedelta):
operand_a = operand_a.total_seconds() # type: ignore[assignment] # FIXME CoP
operand_b = operand_b.total_seconds() # type: ignore[assignment] # FIXME CoP
return cast(
"bool",
np.isclose(
a=np.float64(operand_a), # type: ignore[arg-type] # FIXME CoP
b=np.float64(operand_b), # type: ignore[arg-type] # FIXME CoP
rtol=rtol,
atol=atol,
equal_nan=equal_nan,
),
)
def is_candidate_subset_of_target(candidate: Any, target: Any) -> bool:
"""
This method checks whether or not candidate object is subset of target object.
"""
if isinstance(candidate, dict):
key: Any # must be "hashable"
value: Any
return all(
key in target and is_candidate_subset_of_target(candidate=val, target=target[key])
for key, val in candidate.items()
)
if isinstance(candidate, (list, set, tuple)):
subitem: Any
superitem: Any
return all(
any(is_candidate_subset_of_target(subitem, superitem) for superitem in target)
for subitem in candidate
)
return candidate == target
def is_parseable_date(value: Any, fuzzy: bool = False) -> bool:
try:
_ = parse(value, fuzzy=fuzzy)
return True
except (TypeError, ValueError):
try:
_ = datetime.datetime.fromisoformat(value)
return True
except (TypeError, ValueError):
return False
def is_ndarray_datetime_dtype(
data: npt.NDArray, parse_strings_as_datetimes: bool = False, fuzzy: bool = False
) -> bool:
"""
Determine whether or not all elements of 1-D "np.ndarray" argument are "datetime.datetime" type objects.
""" # noqa: E501 # FIXME CoP
value: Any
result: bool = all(isinstance(value, datetime.datetime) for value in data)
return result or (
parse_strings_as_datetimes
and all(is_parseable_date(value=value, fuzzy=fuzzy) for value in data)
)
def convert_ndarray_to_datetime_dtype_best_effort(
data: npt.NDArray,
datetime_detected: bool = False,
parse_strings_as_datetimes: bool = False,
fuzzy: bool = False,
) -> Tuple[bool, bool, npt.NDArray]:
"""
Attempt to parse all elements of 1-D "np.ndarray" argument into "datetime.datetime" type objects.
Returns:
Boolean flag -- True if all elements of original "data" were "datetime.datetime" type objects; False, otherwise.
Boolean flag -- True, if conversion was performed; False, otherwise.
Output "np.ndarray" (converted, if necessary).
""" # noqa: E501 # FIXME CoP
if is_ndarray_datetime_dtype(data=data, parse_strings_as_datetimes=False, fuzzy=fuzzy):
return True, False, data
value: Any
if datetime_detected or is_ndarray_datetime_dtype(
data=data, parse_strings_as_datetimes=parse_strings_as_datetimes, fuzzy=fuzzy
):
try:
return (
False,
True,
np.asarray([parse(value, fuzzy=fuzzy) for value in data]),
)
except (TypeError, ValueError):
pass
return False, False, data
def convert_ndarray_datetime_to_float_dtype_utc_timezone(
data: np.ndarray,
) -> np.ndarray:
"""
Convert all elements of 1-D "np.ndarray" argument from "datetime.datetime" type to "timestamp" "float" type objects.
Note: Conversion of "datetime.datetime" to "float" uses "UTC" TimeZone to normalize all "datetime.datetime" values.
""" # noqa: E501 # FIXME CoP
value: Any
return np.asarray([value.replace(tzinfo=datetime.timezone.utc).timestamp() for value in data])
def convert_ndarray_float_to_datetime_dtype(data: np.ndarray) -> np.ndarray:
"""
Convert all elements of 1-D "np.ndarray" argument from "float" type to "datetime.datetime" type objects.
Note: Converts to "naive" "datetime.datetime" values (assumes "UTC" TimeZone based floating point timestamps).
""" # noqa: E501 # FIXME CoP
value: Any
return np.asarray(
[
datetime.datetime.fromtimestamp(value, datetime.timezone.utc).replace(tzinfo=None)
for value in data
]
)
def convert_ndarray_float_to_datetime_tuple(
data: np.ndarray,
) -> Tuple[datetime.datetime, ...]:
"""
Convert all elements of 1-D "np.ndarray" argument from "float" type to "datetime.datetime" type tuple elements.
Note: Converts to "naive" "datetime.datetime" values (assumes "UTC" TimeZone based floating point timestamps).
""" # noqa: E501 # FIXME CoP
return tuple(convert_ndarray_float_to_datetime_dtype(data=data).tolist())
def does_ndarray_contain_decimal_dtype(
data: npt.NDArray,
) -> TypeGuard[npt.NDArray]:
"""
Determine whether or not all elements of 1-D "np.ndarray" argument are "decimal.Decimal" type objects.
""" # noqa: E501 # FIXME CoP
value: Any
result: bool = any(isinstance(value, decimal.Decimal) for value in data)
return result
def convert_ndarray_decimal_to_float_dtype(data: np.ndarray) -> np.ndarray:
"""
Convert all elements of N-D "np.ndarray" argument from "decimal.Decimal" type to "float" type objects.
""" # noqa: E501 # FIXME CoP
convert_decimal_to_float_vectorized: Callable[[np.ndarray], np.ndarray] = np.vectorize(
pyfunc=convert_decimal_to_float
)
return convert_decimal_to_float_vectorized(data)
def convert_pandas_series_decimal_to_float_dtype(
data: pd.Series, inplace: bool = False
) -> pd.Series | None:
"""
Convert all elements of "pd.Series" argument from "decimal.Decimal" type to "float" type objects "pd.Series" result.
""" # noqa: E501 # FIXME CoP
series_data: np.ndarray = data.to_numpy()
series_data_has_decimal: bool = does_ndarray_contain_decimal_dtype(data=series_data)
if series_data_has_decimal:
series_data = convert_ndarray_decimal_to_float_dtype(data=series_data)
if inplace:
data.update(pd.Series(series_data))
return None
return pd.Series(series_data)
if inplace:
return None
return data
def is_sane_slack_webhook(url: str) -> bool:
"""Really basic sanity checking."""
if url is None:
return False
return url.strip().startswith("https://hooks.slack.com/")
def is_list_of_strings(_list) -> TypeGuard[List[str]]:
return isinstance(_list, list) and all(isinstance(site, str) for site in _list)
def generate_temporary_table_name(
default_table_name_prefix: str = "gx_temp_",
num_digits: int = 8,
) -> str:
table_name: str = f"{default_table_name_prefix}{str(uuid.uuid4())[:num_digits]}"
return table_name
def get_sqlalchemy_url(drivername, **credentials):
if version.parse(sa.__version__) < version.parse("1.4"):
# Calling URL() deprecated since 1.4, URL.create() should be used instead
url = sa.engine.url.URL(drivername, **credentials)
else:
url = sa.engine.url.URL.create(drivername, **credentials)
return url
def get_sqlalchemy_selectable(
selectable: Union[sa.Table, sqlalchemy.Select],
) -> Union[sa.Table, sqlalchemy.Select]:
"""
Beginning from SQLAlchemy 1.4, a select() can no longer be embedded inside of another select() directly,
without explicitly turning the inner select() into a subquery first. This helper method ensures that this
conversion takes place.
For versions of SQLAlchemy < 1.4 the implicit conversion to a subquery may not always work, so that
also needs to be handled here, using the old equivalent method.
https://docs.sqlalchemy.org/en/14/changelog/migration_14.html#change-4617
""" # noqa: E501 # FIXME CoP
if sqlalchemy.Select and isinstance(selectable, sqlalchemy.Select): # type: ignore[truthy-function] # FIXME CoP
if version.parse(sa.__version__) >= version.parse("1.4"):
selectable = selectable.subquery() # type: ignore[assignment] # FIXME CoP
else:
selectable = selectable.alias() # type: ignore[assignment] # FIXME CoP
return selectable
def get_sqlalchemy_subquery_type():
"""
Beginning from SQLAlchemy 1.4, `sqlalchemy.sql.Alias` has been deprecated in favor of `sqlalchemy.sql.Subquery`.
This helper method ensures that the appropriate type is returned.
https://docs.sqlalchemy.org/en/14/changelog/migration_14.html#change-4617
""" # noqa: E501 # FIXME CoP
try:
return sa.sql.Subquery
except AttributeError:
return sa.sql.Alias
def get_sqlalchemy_domain_data(domain_data):
if version.parse(sa.__version__) < version.parse("1.4"):
# Implicit coercion of SELECT and SELECT constructs is deprecated since 1.4
# select(query).subquery() should be used instead
domain_data = sa.select(sa.text("*")).select_from(domain_data)
# engine.get_domain_records returns a valid select object;
# calling fetchall at execution is equivalent to a SELECT *
return domain_data
def import_make_url():
"""
Beginning from SQLAlchemy 1.4, make_url is accessed from sqlalchemy.engine; earlier versions must
still be accessed from sqlalchemy.engine.url to avoid import errors.
""" # noqa: E501 # FIXME CoP
if version.parse(sa.__version__) < version.parse("1.4"):
make_url = sqlalchemy.url.make_url
else:
make_url = sqlalchemy.engine.make_url
return make_url
def get_clickhouse_sqlalchemy_potential_type(type_module, type_) -> Any:
ch_type = type_
if type(ch_type) is str:
if type_.lower() in ("decimal", "decimaltype()"):
ch_type = type_module.types.Decimal
elif type_.lower() in ("fixedstring"):
ch_type = type_module.types.String
else:
ch_type = type_module.ClickHouseDialect()._get_column_type("", ch_type)
if hasattr(ch_type, "nested_type"):
ch_type = type(ch_type.nested_type)
if not inspect.isclass(ch_type):
ch_type = type(ch_type)
return ch_type
def get_pyathena_potential_type(type_module, type_) -> str:
if version.parse(type_module.pyathena.__version__) >= version.parse("2.5.0"):
# introduction of new column type mapping in 2.5
potential_type = type_module.AthenaDialect()._get_column_type(type_)
else:
if type_ == "string":
type_ = "varchar"
# < 2.5 column type mapping
potential_type = type_module._TYPE_MAPPINGS.get(type_)
return potential_type
def get_trino_potential_type(type_module: ModuleType, type_: str) -> object:
"""
Leverage on Trino Package to return sqlalchemy sql type
"""
# noinspection PyUnresolvedReferences
potential_type = type_module.parse_sqltype(type_)
return potential_type
Inclusive = Literal["left", "right", "neither", "both"]
def pandas_series_between(
series: pd.Series, min_value: int, max_value: int, inclusive: Inclusive
) -> pd.Series:
"""
As of Pandas 1.3.0, the 'inclusive' arg in between() is a string literal: {"left", "right", "neither", "both"}
""" # noqa: E501 # FIXME CoP
metric_series: pd.Series
if version.parse(pd.__version__) >= version.parse("1.3.0"):
metric_series = series.between(min_value, max_value, inclusive=inclusive)
elif inclusive == "left":
metric_series = (series >= min_value) & (series < max_value)
elif inclusive == "right":
metric_series = (series > min_value) & (series <= max_value)
elif inclusive == "neither":
metric_series = series.between(min_value, max_value, inclusive=False) # type: ignore[arg-type] # valid for pandas < 1.3
elif inclusive == "both":
metric_series = series.between(min_value, max_value, inclusive=True) # type: ignore[arg-type] # valid for pandas < 1.3
else:
metric_series = series.between(min_value, max_value)
return metric_series
ToBool: TypeAlias = bool
ToFloat: TypeAlias = Union[float, np.floating]
ToInt: TypeAlias = Union[int, np.integer]
ToStr: TypeAlias = Union[
str, bytes, slice, uuid.UUID, datetime.date, datetime.datetime, np.datetime64
]
ToList: TypeAlias = Union[list, set, tuple, "npt.NDArray", pd.Index, pd.Series]
ToDict: TypeAlias = Union[
dict,
"CommentedMap",
pd.DataFrame,
SerializableDictDot,
SerializableDotDict,
pydantic.BaseModel,
]
JSONConvertable: TypeAlias = Union[
ToDict, ToList, ToStr, ToInt, ToFloat, ToBool, ToBool, None # noqa: PYI016 # FIXME CoP
]
@overload
def convert_to_json_serializable(
data: ToDict,
) -> dict: ...
@overload
def convert_to_json_serializable(
data: ToList,
) -> list: ...
@overload
def convert_to_json_serializable(
data: ToBool,
) -> bool: ...
@overload
def convert_to_json_serializable(
data: ToFloat,
) -> float: ...
@overload
def convert_to_json_serializable(
data: ToInt,
) -> int: ...
@overload
def convert_to_json_serializable(
data: ToStr,
) -> str: ...
@overload
def convert_to_json_serializable(
data: None,
) -> None: ...
def convert_to_json_serializable( # noqa: C901, PLR0911, PLR0912 # FIXME CoP
data: JSONConvertable,
) -> JSONValues:
"""Converts an object to one that is JSON-serializable.
WARNING, data may be converted in place.
Args:
data: an object to convert to a JSON-serializable object
Returns:
A JSON-serializable object. For example:
>>> convert_to_json_serializable(1)
1
>>> convert_to_json_serializable("hello")
"hello"
>>> convert_to_json_serializable(Polygon([(0, 0), (2, 0), (2, 2), (0, 2)]))
"POLYGON ((0 0, 2 0, 2 2, 0 2, 0 0))"
Raises:
TypeError: A non-JSON-serializable field was found.
"""
if isinstance(data, pydantic.BaseModel):
return json.loads(data.json())
if isinstance(data, (SerializableDictDot, SerializableDotDict)):
return data.to_json_dict()
# Handling "float(nan)" separately is required by Python-3.6 and Pandas-0.23 versions.
if isinstance(data, float) and np.isnan(data):
return None
if isinstance(data, (str, int, float, bool)):
# No problem to encode json
return data
if isinstance(data, Enum):
return data.value
if isinstance(data, range):
return list(data)
if isinstance(data, dict):
new_dict = {}
for key in data:
# A pandas index can be numeric, and a dict key can be numeric, but a json key must be a string # noqa: E501 # FIXME CoP
new_dict[str(key)] = convert_to_json_serializable(data[key])
return new_dict
if isinstance(data, (list, tuple, set)):
new_list: List[JSONValues] = []
for val in data:
new_list.append(convert_to_json_serializable(val))
return new_list
if isinstance(data, (np.ndarray, pd.Index)):
# test_obj[key] = test_obj[key].tolist()
# If we have an array or index, convert it first to a list--causing coercion to float--and then round # noqa: E501 # FIXME CoP
# to the number of digits for which the string representation will equal the float representation # noqa: E501 # FIXME CoP
return [convert_to_json_serializable(x) for x in data.tolist()]
if isinstance(data, np.int64):
return int(data)
if isinstance(data, np.float64):
return float(data)
if isinstance(data, (datetime.datetime, datetime.date, datetime.time)):
return data.isoformat()
if isinstance(data, (np.datetime64)):
return np.datetime_as_string(data)
if isinstance(data, uuid.UUID):
return str(data)
if isinstance(data, bytes):
return str(data)
if isinstance(data, slice):
return str(data)
if isinstance(data, pathlib.PurePath):
return str(data)
# noinspection PyTypeChecker
if Polygon is not None and isinstance(data, (Point, Polygon, MultiPolygon, LineString)):
return str(data)
# Use built in base type from numpy, https://docs.scipy.org/doc/numpy-1.13.0/user/basics.types.html
# https://github.com/numpy/numpy/pull/9505
if np.issubdtype(type(data), np.bool_):
return bool(data)
if np.issubdtype(type(data), np.integer) or np.issubdtype(type(data), np.uint):
return int(data) # type: ignore[arg-type] # could be None
if np.issubdtype(type(data), np.floating):
# Note: Use np.floating to avoid FutureWarning from numpy
return float(round(data, sys.float_info.dig)) # type: ignore[arg-type] # could be None
# Note: This clause has to come after checking for np.ndarray or we get:
# `ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()` # noqa: E501 # FIXME CoP
if data is None:
# No problem to encode json
return data
try:
if not isinstance(data, list) and pd.isna(data): # FIXME CoP
# pd.isna is functionally vectorized, but we only want to apply this to single objects
# Hence, why we test for `not isinstance(list)`
return None
except TypeError:
pass
except ValueError:
pass
if isinstance(data, pd.Series):
# Converting a series is tricky since the index may not be a string, but all json
# keys must be strings. So, we use a very ugly serialization strategy
index_name = data.index.name or "index"
value_name = data.name or "value"
return [
{
index_name: convert_to_json_serializable(idx), # type: ignore[call-overload,dict-item] # FIXME CoP
value_name: convert_to_json_serializable(val), # type: ignore[dict-item] # FIXME CoP
}
for idx, val in data.items()
]
if isinstance(data, pd.DataFrame):
return convert_to_json_serializable(data.to_dict(orient="records"))
if pyspark.DataFrame and isinstance(data, pyspark.DataFrame): # type: ignore[truthy-function] # FIXME CoP
# using StackOverflow suggestion for converting pyspark df into dictionary
# https://stackoverflow.com/questions/43679880/pyspark-dataframe-to-dictionary-columns-as-keys-and-list-of-column-values-ad-di
return convert_to_json_serializable(
dict(zip(data.schema.names, zip(*data.collect(), strict=False), strict=False))
)
# SQLAlchemy serialization
if LegacyRow and isinstance(data, LegacyRow):
return dict(data)
# sqlalchemy text for SqlAlchemy 2 compatibility
if sqlalchemy.TextClause and isinstance(data, sqlalchemy.TextClause): # type: ignore[truthy-function] # FIXME CoP
return str(data)
if Row and isinstance(data, Row): # type: ignore[truthy-function] # FIXME CoP
return str(data)
if isinstance(data, decimal.Decimal):
return convert_decimal_to_float(d=data)
from great_expectations.core.run_identifier import RunIdentifier
if isinstance(data, RunIdentifier):
return data.to_json_dict()
# PySpark schema serialization
if pyspark.types and isinstance(data, pyspark.types.StructType):
return dict(data.jsonValue())
if sqlalchemy.Connection and isinstance(data, sqlalchemy.Connection): # type: ignore[truthy-function] # FIXME CoP
# Connection is a module, which is non-serializable. Return module name instead.
return "sqlalchemy.engine.base.Connection"
if isinstance(data, RenderedContent):
return data.to_json_dict()
if isinstance(data, re.Pattern):
return data.pattern
# Unable to serialize (unrecognized data type).
raise TypeError(f"{data!s} is of type {type(data).__name__} which cannot be serialized.") # noqa: TRY003 # FIXME CoP
def ensure_json_serializable(data: Any) -> None: # noqa: C901, PLR0911, PLR0912 # FIXME CoP
"""
Helper function to convert an object to one that is json serializable
Args:
data: an object to attempt to convert a corresponding json-serializable object
Warning:
test_obj may also be converted in place.
"""
if isinstance(data, pydantic.BaseModel):
return
if isinstance(data, (SerializableDictDot, SerializableDotDict)):
return
if isinstance(data, ((str,), (int,), float, bool)):
# No problem to encode json
return
if isinstance(data, dict):
for key in data:
str(key) # key must be cast-able to string
ensure_json_serializable(data[key])
return
if isinstance(data, (list, tuple, set)):
for val in data:
ensure_json_serializable(val)
return
if isinstance(data, (np.ndarray, pd.Index)):
# test_obj[key] = test_obj[key].tolist()
# If we have an array or index, convert it first to a list--causing coercion to float--and then round # noqa: E501 # FIXME CoP
# to the number of digits for which the string representation will equal the float representation # noqa: E501 # FIXME CoP
_ = [ensure_json_serializable(x) for x in data.tolist()] # type: ignore[func-returns-value] # FIXME CoP
return
if isinstance(data, (datetime.datetime, datetime.date, datetime.time)):
return
if isinstance(data, pathlib.PurePath):
return
# Use built in base type from numpy, https://docs.scipy.org/doc/numpy-1.13.0/user/basics.types.html
# https://github.com/numpy/numpy/pull/9505
if np.issubdtype(type(data), np.bool_):
return
if np.issubdtype(type(data), np.integer) or np.issubdtype(type(data), np.uint):
return
if np.issubdtype(type(data), np.floating):
# Note: Use np.floating to avoid FutureWarning from numpy
return
# Note: This clause has to come after checking for np.ndarray or we get:
# `ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()` # noqa: E501 # FIXME CoP
if data is None:
# No problem to encode json
return
try:
if not isinstance(data, list) and pd.isna(data):
# pd.isna is functionally vectorized, but we only want to apply this to single objects
# Hence, why we test for `not isinstance(list))`
return
except TypeError:
pass
except ValueError:
pass
if isinstance(data, pd.Series):
# Converting a series is tricky since the index may not be a string, but all json
# keys must be strings. So, we use a very ugly serialization strategy
index_name = data.index.name or "index"
value_name = data.name or "value"
_ = [
{
index_name: ensure_json_serializable(idx), # type: ignore[func-returns-value] # FIXME CoP
value_name: ensure_json_serializable(val), # type: ignore[func-returns-value] # FIXME CoP
}
for idx, val in data.items()
]
return
if pyspark.DataFrame and isinstance(data, pyspark.DataFrame): # type: ignore[truthy-function] # ensure pyspark is installed
# using StackOverflow suggestion for converting pyspark df into dictionary
# https://stackoverflow.com/questions/43679880/pyspark-dataframe-to-dictionary-columns-as-keys-and-list-of-column-values-ad-di
return ensure_json_serializable(
dict(zip(data.schema.names, zip(*data.collect(), strict=False), strict=False))
)
if isinstance(data, pd.DataFrame):
return ensure_json_serializable(data.to_dict(orient="records"))
if isinstance(data, decimal.Decimal):
return
from great_expectations.core.run_identifier import RunIdentifier
if isinstance(data, RunIdentifier):
return
if sqlalchemy.TextClause and isinstance(data, sqlalchemy.TextClause): # type: ignore[truthy-function] # FIXME CoP
# TextClause is handled manually by convert_to_json_serializable()
return
if sqlalchemy.Connection and isinstance(data, sqlalchemy.Connection): # type: ignore[truthy-function] # FIXME CoP
# Connection module is handled manually by convert_to_json_serializable()
return
raise InvalidExpectationConfigurationError( # noqa: TRY003 # FIXME CoP
f"{data!s} is of type {type(data).__name__} which cannot be serialized to json"
)
| bidict |
python | streamlit__streamlit | lib/tests/streamlit/elements/text_test.py | {
"start": 888,
"end": 3545
} | class ____(DeltaGeneratorTestCase):
"""Test st.text API."""
def test_st_text(self):
"""Test st.text."""
st.text("some text")
el = self.get_delta_from_queue().new_element
assert el.text.body == "some text"
def test_st_text_with_help(self):
"""Test st.text with help."""
st.text("some text", help="help text")
el = self.get_delta_from_queue().new_element
assert el.text.body == "some text"
assert el.text.help == "help text"
def test_st_text_with_width(self):
"""Test st.text with different width types."""
test_cases = [
(500, WidthConfigFields.PIXEL_WIDTH.value, "pixel_width", 500),
("stretch", WidthConfigFields.USE_STRETCH.value, "use_stretch", True),
("content", WidthConfigFields.USE_CONTENT.value, "use_content", True),
(None, WidthConfigFields.USE_CONTENT.value, "use_content", True),
]
for width_value, expected_width_spec, field_name, field_value in test_cases:
with self.subTest(width_value=width_value):
if width_value is None:
st.text("some text")
else:
st.text("some text", width=width_value)
el = self.get_delta_from_queue().new_element
assert el.text.body == "some text"
assert el.width_config.WhichOneof("width_spec") == expected_width_spec
assert getattr(el.width_config, field_name) == field_value
def test_st_text_with_invalid_width(self):
"""Test st.text with invalid width values."""
test_cases = [
(
"invalid",
"Invalid width value: 'invalid'. Width must be either an integer (pixels), 'stretch', or 'content'.",
),
(
-100,
"Invalid width value: -100. Width must be either an integer (pixels), 'stretch', or 'content'.",
),
(
0,
"Invalid width value: 0. Width must be either an integer (pixels), 'stretch', or 'content'.",
),
(
100.5,
"Invalid width value: 100.5. Width must be either an integer (pixels), 'stretch', or 'content'.",
),
]
for width_value, expected_error_message in test_cases:
with self.subTest(width_value=width_value):
with pytest.raises(StreamlitAPIException) as exc:
st.text("some text", width=width_value)
assert str(exc.value) == expected_error_message
| StTextAPITest |
python | great-expectations__great_expectations | contrib/capitalone_dataprofiler_expectations/capitalone_dataprofiler_expectations/rule_based_profiler/data_assistant_result/data_profiler_structured_data_assistant_result.py | {
"start": 243,
"end": 1117
} | class ____(DataAssistantResult):
"""
Note (10/18/2022): Plotting functionality is not implemented.
"""
@property
def metric_expectation_map(self) -> Dict[Union[str, Tuple[str]], str]:
"""
A mapping is defined for which metrics to plot and their associated expectations.
"""
return {}
@property
def metric_types(self) -> Dict[str, AltairDataTypes]:
"""
A mapping is defined for the Altair data type associated with each metric.
"""
# Altair data types can be one of:
# - Nominal: Metric is a discrete unordered category
# - Ordinal: Metric is a discrete ordered quantity
# - Quantitative: Metric is a continuous real-valued quantity
# - Temporal: Metric is a time or date value
return {}
| DataProfilerStructuredDataAssistantResult |
python | ray-project__ray | python/ray/train/xgboost/_xgboost_utils.py | {
"start": 5267,
"end": 8873
} | class ____(RayReportCallback):
"""XGBoost callback to save checkpoints and report metrics.
Args:
metrics: Metrics to report. If this is a list,
each item describes the metric key reported to XGBoost,
and it will be reported under the same name.
This can also be a dict of {<key-to-report>: <xgboost-metric-key>},
which can be used to rename xgboost default metrics.
filename: Customize the saved checkpoint file type by passing
a filename. Defaults to "model.ubj".
frequency: How often to save checkpoints, in terms of iterations.
Defaults to 0 (no checkpoints are saved during training).
checkpoint_at_end: Whether or not to save a checkpoint at the end of training.
results_postprocessing_fn: An optional Callable that takes in
the metrics dict that will be reported (after it has been flattened)
and returns a modified dict. For example, this can be used to
average results across CV fold when using ``xgboost.cv``.
Examples
--------
Reporting checkpoints and metrics to Ray Tune when running many
independent xgboost trials (without data parallelism within a trial).
.. testcode::
:skipif: True
import xgboost
from ray.tune import Tuner
from ray.train.xgboost import RayTrainReportCallback
def train_fn(config):
# Report log loss to Ray Tune after each validation epoch.
bst = xgboost.train(
...,
callbacks=[
RayTrainReportCallback(
metrics={"loss": "eval-logloss"}, frequency=1
)
],
)
tuner = Tuner(train_fn)
results = tuner.fit()
Loading a model from a checkpoint reported by this callback.
.. testcode::
:skipif: True
from ray.train.xgboost import RayTrainReportCallback
# Get a `Checkpoint` object that is saved by the callback during training.
result = trainer.fit()
booster = RayTrainReportCallback.get_model(result.checkpoint)
"""
def __init__(
self,
metrics: Optional[Union[str, List[str], Dict[str, str]]] = None,
filename: str = RayReportCallback.CHECKPOINT_NAME,
frequency: int = 0,
checkpoint_at_end: bool = True,
results_postprocessing_fn: Optional[
Callable[[Dict[str, Union[float, List[float]]]], Dict[str, float]]
] = None,
):
super().__init__(
metrics=metrics,
filename=filename,
frequency=frequency,
checkpoint_at_end=checkpoint_at_end,
results_postprocessing_fn=results_postprocessing_fn,
)
@contextmanager
def _get_checkpoint(self, model: Booster) -> Optional[Checkpoint]:
# NOTE: The world rank returns None for Tune usage without Train.
if ray.train.get_context().get_world_rank() in (0, None):
with tempfile.TemporaryDirectory() as temp_checkpoint_dir:
model.save_model(Path(temp_checkpoint_dir, self._filename).as_posix())
yield Checkpoint(temp_checkpoint_dir)
else:
yield None
def _save_and_report_checkpoint(self, report_dict: Dict, model: Booster):
with self._get_checkpoint(model=model) as checkpoint:
ray.train.report(report_dict, checkpoint=checkpoint)
def _report_metrics(self, report_dict: Dict):
ray.train.report(report_dict)
| RayTrainReportCallback |
python | pytorch__pytorch | test/onnx/model_defs/op_test.py | {
"start": 559,
"end": 661
} | class ____(nn.Module):
def forward(self, input):
return input.permute(2, 3, 0, 1)
| PermuteNet |
python | getsentry__sentry | src/sentry/workflow_engine/models/action_alertruletriggeraction.py | {
"start": 202,
"end": 533
} | class ____(DefaultFieldsModel):
"""
A lookup model for Actions (new) and AlertRuleTriggerActions (legacy)
"""
__relocation_scope__ = RelocationScope.Excluded
alert_rule_trigger_action_id = BoundedBigIntegerField(db_index=True)
action = FlexibleForeignKey("workflow_engine.Action")
| ActionAlertRuleTriggerAction |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_bugbear/B004.py | {
"start": 956,
"end": 1839
} | class ____:
def __init__(self): self.__call__ = None
assert hasattr(A(), "__call__")
assert callable(A()) is False
# https://github.com/astral-sh/ruff/issues/20440
def test_invalid_hasattr_calls():
hasattr(0, "__call__", 0) # 3 args - invalid
hasattr(0, "__call__", x=0) # keyword arg - invalid
hasattr(0, "__call__", 0, x=0) # 3 args + keyword - invalid
hasattr() # no args - invalid
hasattr(0) # 1 arg - invalid
hasattr(*(), "__call__", "extra") # unpacking - invalid
hasattr(*()) # unpacking - invalid
def test_invalid_getattr_calls():
getattr(0, "__call__", None, "extra") # 4 args - invalid
getattr(0, "__call__", default=None) # keyword arg - invalid
getattr() # no args - invalid
getattr(0) # 1 arg - invalid
getattr(*(), "__call__", None, "extra") # unpacking - invalid
getattr(*()) # unpacking - invalid
| A |
python | run-llama__llama_index | llama-index-integrations/storage/kvstore/llama-index-storage-kvstore-duckdb/tests/test_storage_kvstore_duckdb.py | {
"start": 1491,
"end": 4897
} | class ____:
@pytest.fixture
def kv_store(self, persistent: str) -> DuckDBKVStore:
if persistent == "memory":
return memory_store()
return disk_store()
def test_put(self, kv_store: DuckDBKVStore):
key = "id_1"
value = {"name": "John Doe", "text": "Hello, world!"}
_ = kv_store.put(key, value)
def test_put_all(self, kv_store: DuckDBKVStore):
kv_pairs = [
("id_1", {"name": "John Doe", "text": "Hello, world!"}),
("id_2", {"name": "Jane Doe", "text": "Hello, world!"}),
]
_ = kv_store.put_all(kv_pairs)
def test_put_all_empty(self, kv_store: DuckDBKVStore):
kv_pairs = []
_ = kv_store.put_all(kv_pairs)
def test_put_twice(self, kv_store: DuckDBKVStore):
key = "id_1"
value = {"name": "John Doe", "text": "Hello, world!"}
value_updated = {"name": "Jane Doe", "text": "Hello, world!"}
_ = kv_store.put(key, value)
_ = kv_store.put(key, value_updated)
assert kv_store.get(key) == value_updated
def test_put_get(self, kv_store: DuckDBKVStore):
key = "id_1"
value = {"name": "John Doe", "text": "Hello, world!"}
_ = kv_store.put(key, value)
assert kv_store.get(key) == value
def test_put_get_collection(self, kv_store: DuckDBKVStore):
key = "id_1"
value = {"name": "John Doe", "text": "Hello, world!"}
_ = kv_store.put(key, value, collection="collection_1")
assert kv_store.get(key, collection="collection_1") == value
def test_put_get_all(self, kv_store: DuckDBKVStore):
key_1 = "id_1"
value_1 = {"name": "John Doe", "text": "Hello, world!"}
key_2 = "id_2"
value_2 = {"name": "Jane Doe", "text": "Hello, world!"}
_ = kv_store.put(key_1, value_1)
_ = kv_store.put(key_2, value_2)
results = kv_store.get_all()
assert results[key_1] == value_1
assert results[key_2] == value_2
def test_delete(self, kv_store: DuckDBKVStore):
key = "id_1"
value = {"name": "John Doe", "text": "Hello, world!"}
_ = kv_store.put(key, value)
assert kv_store.get(key) == value
_ = kv_store.delete(key)
assert kv_store.get(key) is None
def test_delete_collection(self, kv_store: DuckDBKVStore):
key = "id_1"
value = {"name": "John Doe", "text": "Hello, world!"}
_ = kv_store.put(key, value, collection="collection_1")
assert kv_store.get(key, collection="collection_1") == value
_ = kv_store.delete(key, collection="collection_1")
assert kv_store.get(key, collection="collection_1") is None
@pytest.mark.asyncio
async def test_async(self, kv_store: DuckDBKVStore):
key = "id_1"
value = {"name": "John Doe", "text": "Hello, world!"}
_ = await kv_store.aput(key, value)
assert await kv_store.aget(key) == value
new_key = "id_2"
new_value = {"name": "Jane Doe", "text": "Hello, world!"}
_ = await kv_store.aput_all([(new_key, new_value), (new_key, new_value)])
assert await kv_store.aget_all() == {key: value, new_key: new_value}
_ = await kv_store.adelete(key)
assert await kv_store.aget(key) is None
assert await kv_store.aget_all() == {new_key: new_value}
| TestStore |
python | python__mypy | mypy/server/aststrip.py | {
"start": 3410,
"end": 11278
} | class ____(TraverserVisitor):
def __init__(self, saved_class_attrs: SavedAttributes) -> None:
# The current active class.
self.type: TypeInfo | None = None
# This is True at class scope, but not in methods.
self.is_class_body = False
# By default, process function definitions. If False, don't -- this is used for
# processing module top levels.
self.recurse_into_functions = True
# These attributes were removed from top-level classes during strip and
# will be added afterwards (if no existing definition is found). These
# must be added back before semantically analyzing any methods.
self.saved_class_attrs = saved_class_attrs
def strip_file_top_level(self, file_node: MypyFile) -> None:
"""Strip a module top-level (don't recursive into functions)."""
self.recurse_into_functions = False
file_node.plugin_deps.clear()
file_node.accept(self)
for name in file_node.names.copy():
# TODO: this is a hot fix, we should delete all names,
# see https://github.com/python/mypy/issues/6422.
if "@" not in name:
del file_node.names[name]
def visit_block(self, b: Block) -> None:
if b.is_unreachable:
return
super().visit_block(b)
def visit_class_def(self, node: ClassDef) -> None:
"""Strip class body and type info, but don't strip methods."""
# We need to save the implicitly defined instance variables,
# i.e. those defined as attributes on self. Otherwise, they would
# be lost if we only reprocess top-levels (this kills TypeInfos)
# but not the methods that defined those variables.
if not self.recurse_into_functions:
self.save_implicit_attributes(node)
# We need to delete any entries that were generated by plugins,
# since they will get regenerated.
to_delete = {v.node for v in node.info.names.values() if v.plugin_generated}
node.type_vars = []
node.base_type_exprs.extend(node.removed_base_type_exprs)
node.removed_base_type_exprs = []
node.defs.body = [
s for s in node.defs.body if s not in to_delete # type: ignore[comparison-overlap]
]
with self.enter_class(node.info):
super().visit_class_def(node)
node.defs.body.extend(node.removed_statements)
node.removed_statements = []
type_state.reset_subtype_caches_for(node.info)
# Kill the TypeInfo, since there is none before semantic analysis.
node.info = CLASSDEF_NO_INFO
node.analyzed = None
def save_implicit_attributes(self, node: ClassDef) -> None:
"""Produce callbacks that re-add attributes defined on self."""
for name, sym in node.info.names.items():
if isinstance(sym.node, Var) and sym.implicit:
self.saved_class_attrs[node, name] = sym
def visit_func_def(self, node: FuncDef) -> None:
if not self.recurse_into_functions:
return
node.expanded = []
node.type = node.unanalyzed_type
if node.type:
# Type variable binder binds type variables before the type is analyzed,
# this causes unanalyzed_type to be modified in place. We needed to revert this
# in order to get the state exactly as it was before semantic analysis.
# See also #4814.
assert isinstance(node.type, CallableType)
node.type.variables = ()
with self.enter_method(node.info) if node.info else nullcontext():
super().visit_func_def(node)
def visit_decorator(self, node: Decorator) -> None:
node.var.type = None
for expr in node.decorators:
expr.accept(self)
if self.recurse_into_functions:
node.func.accept(self)
else:
# Only touch the final status if we re-process
# the top level, since decorators are processed there.
node.var.is_final = False
node.func.is_final = False
def visit_overloaded_func_def(self, node: OverloadedFuncDef) -> None:
if not self.recurse_into_functions:
return
# Revert change made during semantic analysis main pass.
node.items = node.unanalyzed_items.copy()
node.impl = None
node.is_final = False
super().visit_overloaded_func_def(node)
def visit_assignment_stmt(self, node: AssignmentStmt) -> None:
node.type = node.unanalyzed_type
node.is_final_def = False
node.is_alias_def = False
if self.type and not self.is_class_body:
for lvalue in node.lvalues:
# Revert assignments made via self attributes.
self.process_lvalue_in_method(lvalue)
super().visit_assignment_stmt(node)
def visit_import_from(self, node: ImportFrom) -> None:
node.assignments = []
def visit_import_all(self, node: ImportAll) -> None:
node.assignments = []
def visit_for_stmt(self, node: ForStmt) -> None:
node.index_type = node.unanalyzed_index_type
node.inferred_item_type = None
node.inferred_iterator_type = None
super().visit_for_stmt(node)
def visit_name_expr(self, node: NameExpr) -> None:
self.strip_ref_expr(node)
def visit_member_expr(self, node: MemberExpr) -> None:
self.strip_ref_expr(node)
super().visit_member_expr(node)
def visit_index_expr(self, node: IndexExpr) -> None:
node.analyzed = None # May have been an alias or type application.
super().visit_index_expr(node)
def visit_op_expr(self, node: OpExpr) -> None:
node.analyzed = None # May have been an alias
super().visit_op_expr(node)
def strip_ref_expr(self, node: RefExpr) -> None:
node.kind = None
node.node = None
node.fullname = ""
node.is_new_def = False
node.is_inferred_def = False
def visit_call_expr(self, node: CallExpr) -> None:
node.analyzed = None
super().visit_call_expr(node)
def visit_super_expr(self, node: SuperExpr) -> None:
node.info = None
super().visit_super_expr(node)
def process_lvalue_in_method(self, lvalue: Node) -> None:
if isinstance(lvalue, MemberExpr):
if lvalue.is_new_def:
# Remove defined attribute from the class symbol table. If is_new_def is
# true for a MemberExpr, we know that it must be an assignment through
# self, since only those can define new attributes.
assert self.type is not None
if lvalue.name in self.type.names:
del self.type.names[lvalue.name]
key = (self.type.defn, lvalue.name)
if key in self.saved_class_attrs:
del self.saved_class_attrs[key]
elif isinstance(lvalue, (TupleExpr, ListExpr)):
for item in lvalue.items:
self.process_lvalue_in_method(item)
elif isinstance(lvalue, StarExpr):
self.process_lvalue_in_method(lvalue.expr)
@contextmanager
def enter_class(self, info: TypeInfo) -> Iterator[None]:
old_type = self.type
old_is_class_body = self.is_class_body
self.type = info
self.is_class_body = True
yield
self.type = old_type
self.is_class_body = old_is_class_body
@contextmanager
def enter_method(self, info: TypeInfo) -> Iterator[None]:
old_type = self.type
old_is_class_body = self.is_class_body
self.type = info
self.is_class_body = False
yield
self.type = old_type
self.is_class_body = old_is_class_body
| NodeStripVisitor |
python | wandb__wandb | wandb/vendor/pygments/styles/murphy.py | {
"start": 383,
"end": 2751
} | class ____(Style):
"""
Murphy's style from CodeRay.
"""
default_style = ""
styles = {
Whitespace: "#bbbbbb",
Comment: "#666 italic",
Comment.Preproc: "#579 noitalic",
Comment.Special: "#c00 bold",
Keyword: "bold #289",
Keyword.Pseudo: "#08f",
Keyword.Type: "#66f",
Operator: "#333",
Operator.Word: "bold #000",
Name.Builtin: "#072",
Name.Function: "bold #5ed",
Name.Class: "bold #e9e",
Name.Namespace: "bold #0e84b5",
Name.Exception: "bold #F00",
Name.Variable: "#036",
Name.Variable.Instance: "#aaf",
Name.Variable.Class: "#ccf",
Name.Variable.Global: "#f84",
Name.Constant: "bold #5ed",
Name.Label: "bold #970",
Name.Entity: "#800",
Name.Attribute: "#007",
Name.Tag: "#070",
Name.Decorator: "bold #555",
String: "bg:#e0e0ff",
String.Char: "#88F bg:",
String.Doc: "#D42 bg:",
String.Interpol: "bg:#eee",
String.Escape: "bold #666",
String.Regex: "bg:#e0e0ff #000",
String.Symbol: "#fc8 bg:",
String.Other: "#f88",
Number: "bold #60E",
Number.Integer: "bold #66f",
Number.Float: "bold #60E",
Number.Hex: "bold #058",
Number.Oct: "bold #40E",
Generic.Heading: "bold #000080",
Generic.Subheading: "bold #800080",
Generic.Deleted: "#A00000",
Generic.Inserted: "#00A000",
Generic.Error: "#FF0000",
Generic.Emph: "italic",
Generic.Strong: "bold",
Generic.Prompt: "bold #c65d09",
Generic.Output: "#888",
Generic.Traceback: "#04D",
Error: "#F00 bg:#FAA"
}
| MurphyStyle |
python | tensorflow__tensorflow | tensorflow/tools/ci_build/osx/arm64/tensorflow_metal_plugin_test.py | {
"start": 40039,
"end": 42613
} | class ____(test.TestCase):
def _testOneHot(
self, truth, use_gpu=False, expected_err_re=None, raises=None, **inputs
):
with self.cached_session(use_gpu=use_gpu):
if raises is not None:
with self.assertRaises(raises):
array_ops.one_hot(**inputs)
else:
ans = array_ops.one_hot(**inputs)
if expected_err_re is None:
tf_ans = self.evaluate(ans)
self.assertEqual(tf_ans.shape, ans.get_shape())
self.assertAllEqual(tf_ans, truth)
else:
with self.assertRaisesOpError(expected_err_re):
self.evaluate(ans)
def _testBothOneHot(self, truth, expected_err_re=None, raises=None, **inputs):
self._testOneHot(truth, True, expected_err_re, raises, **inputs)
self._testOneHot(truth, False, expected_err_re, raises, **inputs)
def _testBasic(self, dtype):
indices = numpy_compat.np_asarray([0, 2, -1, 1], dtype=np.int32)
depth = 3
on_value = numpy_compat.np_asarray(1.0, dtype=dtype)
off_value = numpy_compat.np_asarray(-1.0, dtype=dtype)
truth = numpy_compat.np_asarray(
[
[1.0, -1.0, -1.0],
[-1.0, -1.0, 1.0],
[-1.0, -1.0, -1.0],
[-1.0, 1.0, -1.0],
],
dtype=dtype,
)
# axis == -1
self._testBothOneHot(
indices=indices,
depth=depth,
on_value=on_value,
off_value=off_value,
dtype=dtype,
truth=truth,
)
# axis == 0
self._testBothOneHot(
indices=indices,
depth=depth,
on_value=on_value,
off_value=off_value,
axis=0,
dtype=dtype,
truth=truth.T,
) # Output is transpose version in this case
def _testDefaultBasic(self, dtype):
indices = numpy_compat.np_asarray([0, 2, -1, 1], dtype=np.int32)
depth = 3
truth = numpy_compat.np_asarray(
[[1.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, 0.0, 0.0], [0.0, 1.0, 0.0]],
dtype=dtype,
)
# axis == -1
self._testBothOneHot(indices=indices, depth=depth, truth=truth)
# axis == 0
self._testBothOneHot(
indices=indices, depth=depth, axis=0, truth=truth.T
) # Output is transpose version in this case
def testFloatBasic(self):
self._testBasic(np.float32)
self._testDefaultBasic(np.float32)
def get_test_configs():
"""Get all the valid tests configs to run.
Returns:
all the valid test configs as tuples of data_format and use_gpu.
"""
test_configs = [("NHWC", False), ("NHWC", True)]
return test_configs
| OneHotTest |
python | crytic__slither | slither/printers/functions/cfg.py | {
"start": 104,
"end": 1285
} | class ____(AbstractPrinter):
ARGUMENT = "cfg"
HELP = "Export the CFG of each functions"
WIKI = "https://github.com/trailofbits/slither/wiki/Printer-documentation#cfg"
def output(self, filename: str) -> Output:
"""
_filename is not used
Args:
_filename(string)
"""
info = ""
all_files = []
for contract in self.contracts: # type: ignore
for function in contract.functions + list(contract.modifiers):
if filename:
new_filename = f"{filename}-{contract.name}-{function.full_name}.dot"
else:
new_filename = f"{contract.name}-{function.full_name}.dot"
info += f"Export {new_filename}\n"
content = function.slithir_cfg_to_dot_str()
with open(new_filename, "w", encoding="utf8") as f:
f.write(content)
all_files.append((new_filename, content))
self.info(info)
res = self.generate_output(info)
for filename_result, content in all_files:
res.add_file(filename_result, content)
return res
| CFG |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_gradient08.py | {
"start": 315,
"end": 1440
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_gradient08.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
chart = workbook.add_chart({"type": "column"})
chart.axis_ids = [69014272, 69016192]
data = [
[1, 2, 3, 4, 5],
[2, 4, 6, 8, 10],
[3, 6, 9, 12, 15],
]
worksheet.write_column("A1", data[0])
worksheet.write_column("B1", data[1])
worksheet.write_column("C1", data[2])
chart.add_series({"values": "=Sheet1!$A$1:$A$5"})
chart.set_chartarea({"gradient": {"colors": ["#DDEBCF", "#9CB86E", "#156B13"]}})
chart.add_series({"values": "=Sheet1!$B$1:$B$5"})
chart.add_series({"values": "=Sheet1!$C$1:$C$5"})
worksheet.insert_chart("E9", chart)
workbook.close()
self.assertExcelEqual()
| TestCompareXLSXFiles |
python | spack__spack | var/spack/test_repos/spack_repo/duplicates_test/packages/cycle_b/package.py | {
"start": 216,
"end": 578
} | class ____(Package):
"""Package that would lead to cycles if default variant values are used"""
homepage = "http://www.example.com"
url = "http://www.example.com/tdep-1.0.tar.gz"
version("2.0", md5="0123456789abcdef0123456789abcdef")
variant("cycle", default=True, description="activate cycles")
depends_on("cycle-a", when="+cycle")
| CycleB |
python | xlwings__xlwings | xlwings/main.py | {
"start": 148217,
"end": 150109
} | class ____(Collection):
"""
A collection of all :meth:`sheet <Sheet>` objects:
>>> import xlwings as xw
>>> xw.sheets # active book
Sheets([<Sheet [Book1]Sheet1>, <Sheet [Book1]Sheet2>])
>>> xw.Book('Book1').sheets # specific book
Sheets([<Sheet [Book1]Sheet1>, <Sheet [Book1]Sheet2>])
.. versionadded:: 0.9.0
"""
_wrap = Sheet
@property
def active(self):
"""
Returns the active Sheet.
"""
return Sheet(impl=self.impl.active)
def __call__(self, name_or_index):
if isinstance(name_or_index, Sheet):
return name_or_index
else:
return Sheet(impl=self.impl(name_or_index))
def __delitem__(self, name_or_index):
self[name_or_index].delete()
def add(self, name=None, before=None, after=None):
"""
Creates a new Sheet and makes it the active sheet.
Parameters
----------
name : str, default None
Name of the new sheet. If None, will default to Excel's default name.
before : Sheet, default None
An object that specifies the sheet before which the new sheet is added.
after : Sheet, default None
An object that specifies the sheet after which the new sheet is added.
Returns
-------
sheet : Sheet
Added sheet object
"""
if name is not None:
if name.lower() in (s.name.lower() for s in self):
raise ValueError("Sheet named '%s' already present in workbook" % name)
if before is not None and not isinstance(before, Sheet):
before = self(before)
if after is not None and not isinstance(after, Sheet):
after = self(after)
impl = self.impl.add(before and before.impl, after and after.impl, name)
return Sheet(impl=impl)
| Sheets |
python | kamyu104__LeetCode-Solutions | Python/closest-nodes-queries-in-a-binary-search-tree.py | {
"start": 53,
"end": 177
} | class ____(object):
def __init__(self, val=0, left=None, right=None):
pass
# iterative dfs, binary search
| TreeNode |
python | dask__distributed | distributed/metrics.py | {
"start": 11163,
"end": 14464
} | class ____:
"""Add-on to :class:`ContextMeter` that helps in the case where:
- The code to be metered is not easily expressed as a self-contained code block
e.g. you want to measure latency in the asyncio event loop before and after
running a task
- You want to alter the metrics depending on how the code ends; e.g. you want to
post them differently in case of failure.
Examples
--------
>>> ledger = DelayedMetricsLedger() # Metering starts here
>>> async def wrapper():
... with ledger.record():
... return await metered_function()
>>> task = asyncio.create_task(wrapper())
>>> # (later, elsewhere)
>>> try:
... await task
... coarse_time = False
... except Exception:
... coarse_time = "failed"
... raise
... finally:
... # Metering stops here
... for label, value, unit in ledger.finalize(coarse_time):
... # actually log metrics
"""
func: Callable[[], float]
start: float
metrics: list[tuple[Hashable, float, str]] # (label, value, unit)
def __init__(self, func: Callable[[], float] = timemod.perf_counter):
self.func = func
self.start = func()
self.metrics = []
def _callback(self, label: Hashable, value: float, unit: str) -> None:
self.metrics.append((label, value, unit))
@contextmanager
def record(self, *, key: Hashable | None = None) -> Iterator[None]:
"""Ingest metrics logged with :meth:`ContextMeter.digest_metric` or
:meth:`ContextMeter.meter` and temporarily store them in :ivar:`metrics`.
Parameters
----------
key: Hashable, optional
See :meth:`ContextMeter.add_callback`
"""
with context_meter.add_callback(self._callback, key=key):
yield
def finalize(
self,
coarse_time: str | Literal[False] = False,
floor: float | Literal[False] = 0.0,
) -> Iterator[tuple[Hashable, float, str]]:
"""The metered code is terminated, and we now know how to log it.
Parameters
----------
coarse_time: str | False, optional
False
Yield all acquired metrics, plus an extra time metric, labelled "other",
which is the time between creating the DelayedMetricsLedger and
calling this method, minus any time logged in the metrics.
label
Yield all acquired non-time metrics.
Yield a single metric, labelled <coarse_time>, which is the time
between creating the DelayedMetricsLedger and calling this method.
floor: float | False, optional
Floor either the "other" or the <coarse_time> metric to this value
(default: 0). Set to False to disable.
"""
stop = self.func()
delta = stop - self.start
for label, value, unit in self.metrics:
if unit != "seconds" or not coarse_time:
yield label, value, unit
if unit == "seconds" and not coarse_time:
delta -= value
if floor is not False:
delta = max(floor, delta)
yield coarse_time or "other", delta, "seconds"
| DelayedMetricsLedger |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.