instance_id
stringlengths
14
45
pull_number
int64
74
29.2k
repo
stringlengths
10
39
version
stringclasses
37 values
base_commit
stringlengths
40
40
created_at
stringdate
2015-03-20 20:39:55
2025-01-02 13:53:18
patch
stringlengths
525
15.9k
test_patch
stringlengths
606
17.8k
non_py_patch
stringlengths
0
7.21k
new_components
listlengths
1
3
FAIL_TO_PASS
listlengths
1
202
PASS_TO_PASS
listlengths
0
910
problem_statement
stringlengths
907
23.2k
hints_text
stringclasses
26 values
environment_setup_commit
stringlengths
40
40
PyThaiNLP__pythainlp-1054
1,054
PyThaiNLP/pythainlp
null
2252dee57bd7be9503242fa734bf0abc48c5ddf1
2025-01-02T13:53:18Z
diff --git a/docs/api/lm.rst b/docs/api/lm.rst index 471282fd3..063aecb2d 100644 --- a/docs/api/lm.rst +++ b/docs/api/lm.rst @@ -6,4 +6,5 @@ pythainlp.lm Modules ------- +.. autofunction:: calculate_ngram_counts .. autofunction:: remove_repeated_ngrams \ No newline at end of file diff --git a/pythainlp/lm/__init__.py b/pythainlp/lm/__init__.py index f3e43e801..9fe31c161 100644 --- a/pythainlp/lm/__init__.py +++ b/pythainlp/lm/__init__.py @@ -3,6 +3,9 @@ # SPDX-FileType: SOURCE # SPDX-License-Identifier: Apache-2.0 -__all__ = ["remove_repeated_ngrams"] +__all__ = [ + "calculate_ngram_counts", + "remove_repeated_ngrams" +] -from pythainlp.lm.text_util import remove_repeated_ngrams +from pythainlp.lm.text_util import calculate_ngram_counts, remove_repeated_ngrams diff --git a/pythainlp/lm/text_util.py b/pythainlp/lm/text_util.py index 668ded3c5..0d3181d2a 100644 --- a/pythainlp/lm/text_util.py +++ b/pythainlp/lm/text_util.py @@ -4,7 +4,32 @@ # SPDX-License-Identifier: Apache-2.0 # ruff: noqa: C901 -from typing import List +from typing import List, Tuple, Dict + + +def calculate_ngram_counts( + list_words: List[str], + n_min: int = 2, + n_max: int = 4) -> Dict[Tuple[str], int]: + """ + Calculates the counts of n-grams in the list words for the specified range. + + :param List[str] list_words: List of string + :param int n_min: The minimum n-gram size (default: 2). + :param int n_max: The maximum n-gram size (default: 4). + + :return: A dictionary where keys are n-grams and values are their counts. + :rtype: Dict[Tuple[str], int] + """ + + ngram_counts = {} + + for n in range(n_min, n_max + 1): + for i in range(len(list_words) - n + 1): + ngram = tuple(list_words[i:i + n]) + ngram_counts[ngram] = ngram_counts.get(ngram, 0) + 1 + + return ngram_counts def remove_repeated_ngrams(string_list: List[str], n: int = 2) -> List[str]:
diff --git a/tests/core/test_lm.py b/tests/core/test_lm.py index 5d25cc124..9da213d31 100644 --- a/tests/core/test_lm.py +++ b/tests/core/test_lm.py @@ -5,10 +5,23 @@ import unittest -from pythainlp.lm import remove_repeated_ngrams +from pythainlp.lm import calculate_ngram_counts, remove_repeated_ngrams class LMTestCase(unittest.TestCase): + def test_calculate_ngram_counts(self): + self.assertEqual( + calculate_ngram_counts(['1', '2', '3', '4']), + { + ('1', '2'): 1, + ('2', '3'): 1, + ('3', '4'): 1, + ('1', '2', '3'): 1, + ('2', '3', '4'): 1, + ('1', '2', '3', '4'): 1 + } + ) + def test_remove_repeated_ngrams(self): texts = ['เอา', 'เอา', 'แบบ', 'แบบ', 'แบบ', 'ไหน'] self.assertEqual(
diff --git a/docs/api/lm.rst b/docs/api/lm.rst index 471282fd3..063aecb2d 100644 --- a/docs/api/lm.rst +++ b/docs/api/lm.rst @@ -6,4 +6,5 @@ pythainlp.lm Modules ------- +.. autofunction:: calculate_ngram_counts .. autofunction:: remove_repeated_ngrams \ No newline at end of file
[ { "components": [ { "doc": "Calculates the counts of n-grams in the list words for the specified range.\n\n:param List[str] list_words: List of string\n:param int n_min: The minimum n-gram size (default: 2).\n:param int n_max: The maximum n-gram size (default: 4).\n\n:return: A dictionary where keys are n-grams and values are their counts.\n:rtype: Dict[Tuple[str], int]", "lines": [ 10, 32 ], "name": "calculate_ngram_counts", "signature": "def calculate_ngram_counts( list_words: List[str], n_min: int = 2, n_max: int = 4) -> Dict[Tuple[str], int]:", "type": "function" } ], "file": "pythainlp/lm/text_util.py" } ]
[ "tests/core/test_lm.py::LMTestCase::test_calculate_ngram_counts", "tests/core/test_lm.py::LMTestCase::test_remove_repeated_ngrams" ]
[]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> Add pythainlp.lm.calculate_ngram_counts Calculates the counts of n-grams in the list words for the specified range. ``` >>> from pythainlp.lm import calculate_ngram_counts >>> a=["1","2","3","4"] >>> calculate_ngram_counts(a) {('1', '2'): 1, ('2', '3'): 1, ('3', '4'): 1, ('1', '2', '3'): 1, ('2', '3', '4'): 1, ('1', '2', '3', '4'): 1} >>> ``` ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in pythainlp/lm/text_util.py] (definition of calculate_ngram_counts:) def calculate_ngram_counts( list_words: List[str], n_min: int = 2, n_max: int = 4) -> Dict[Tuple[str], int]: """Calculates the counts of n-grams in the list words for the specified range. :param List[str] list_words: List of string :param int n_min: The minimum n-gram size (default: 2). :param int n_max: The maximum n-gram size (default: 4). :return: A dictionary where keys are n-grams and values are their counts. :rtype: Dict[Tuple[str], int]""" [end of new definitions in pythainlp/lm/text_util.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
2252dee57bd7be9503242fa734bf0abc48c5ddf1
tobymao__sqlglot-4537
4,537
tobymao/sqlglot
null
6992c1855f343a5d0120a3b4c993d8c406dd29ba
2024-12-19T12:43:38Z
diff --git a/sqlglot/dialects/tsql.py b/sqlglot/dialects/tsql.py index 1acc5ca8a7..7aa7a0e22b 100644 --- a/sqlglot/dialects/tsql.py +++ b/sqlglot/dialects/tsql.py @@ -370,6 +370,16 @@ def _timestrtotime_sql(self: TSQL.Generator, expression: exp.TimeStrToTime): return sql +def _build_datetrunc(args: t.List) -> exp.TimestampTrunc: + unit = seq_get(args, 0) + this = seq_get(args, 1) + + if this and this.is_string: + this = exp.cast(this, exp.DataType.Type.DATETIME2) + + return exp.TimestampTrunc(this=this, unit=unit) + + class TSQL(Dialect): SUPPORTS_SEMI_ANTI_JOIN = False LOG_BASE_FIRST = False @@ -570,6 +580,7 @@ class Parser(parser.Parser): "SUSER_SNAME": exp.CurrentUser.from_arg_list, "SYSTEM_USER": exp.CurrentUser.from_arg_list, "TIMEFROMPARTS": _build_timefromparts, + "DATETRUNC": _build_datetrunc, } JOIN_HINTS = {"LOOP", "HASH", "MERGE", "REMOTE"} @@ -936,6 +947,7 @@ class Generator(generator.Generator): exp.Trim: trim_sql, exp.TsOrDsAdd: date_delta_sql("DATEADD", cast=True), exp.TsOrDsDiff: date_delta_sql("DATEDIFF"), + exp.TimestampTrunc: lambda self, e: self.func("DATETRUNC", e.unit, e.this), } TRANSFORMS.pop(exp.ReturnsProperty)
diff --git a/tests/dialects/test_tsql.py b/tests/dialects/test_tsql.py index e8cd69648b..4c61780d76 100644 --- a/tests/dialects/test_tsql.py +++ b/tests/dialects/test_tsql.py @@ -2090,3 +2090,27 @@ def test_next_value_for(self): "oracle": "SELECT NEXT VALUE FOR db.schema.sequence_name", }, ) + + # string literals in the DATETRUNC are casted as DATETIME2 + def test_datetrunc(self): + self.validate_all( + "SELECT DATETRUNC(month, 'foo')", + write={ + "duckdb": "SELECT DATE_TRUNC('MONTH', CAST('foo' AS TIMESTAMP))", + "tsql": "SELECT DATETRUNC(MONTH, CAST('foo' AS DATETIME2))", + }, + ) + self.validate_all( + "SELECT DATETRUNC(month, foo)", + write={ + "duckdb": "SELECT DATE_TRUNC('MONTH', foo)", + "tsql": "SELECT DATETRUNC(MONTH, foo)", + }, + ) + self.validate_all( + "SELECT DATETRUNC(year, CAST('foo1' AS date))", + write={ + "duckdb": "SELECT DATE_TRUNC('YEAR', CAST('foo1' AS DATE))", + "tsql": "SELECT DATETRUNC(YEAR, CAST('foo1' AS DATE))", + }, + )
[ { "components": [ { "doc": "", "lines": [ 373, 380 ], "name": "_build_datetrunc", "signature": "def _build_datetrunc(args: t.List) -> exp.TimestampTrunc:", "type": "function" } ], "file": "sqlglot/dialects/tsql.py" } ]
[ "tests/dialects/test_tsql.py::TestTSQL::test_datetrunc" ]
[ "tests/dialects/test_tsql.py::TestTSQL::test_add_date", "tests/dialects/test_tsql.py::TestTSQL::test_charindex", "tests/dialects/test_tsql.py::TestTSQL::test_commit", "tests/dialects/test_tsql.py::TestTSQL::test_convert", "tests/dialects/test_tsql.py::TestTSQL::test_count", "tests/dialects/test_tsql.py::TestTSQL::test_current_user", "tests/dialects/test_tsql.py::TestTSQL::test_date_diff", "tests/dialects/test_tsql.py::TestTSQL::test_datefromparts", "tests/dialects/test_tsql.py::TestTSQL::test_datename", "tests/dialects/test_tsql.py::TestTSQL::test_datepart", "tests/dialects/test_tsql.py::TestTSQL::test_ddl", "tests/dialects/test_tsql.py::TestTSQL::test_declare", "tests/dialects/test_tsql.py::TestTSQL::test_eomonth", "tests/dialects/test_tsql.py::TestTSQL::test_format", "tests/dialects/test_tsql.py::TestTSQL::test_fullproc", "tests/dialects/test_tsql.py::TestTSQL::test_grant", "tests/dialects/test_tsql.py::TestTSQL::test_hints", "tests/dialects/test_tsql.py::TestTSQL::test_identifier_prefixes", "tests/dialects/test_tsql.py::TestTSQL::test_insert_cte", "tests/dialects/test_tsql.py::TestTSQL::test_isnull", "tests/dialects/test_tsql.py::TestTSQL::test_json", "tests/dialects/test_tsql.py::TestTSQL::test_lateral_subquery", "tests/dialects/test_tsql.py::TestTSQL::test_lateral_table_valued_function", "tests/dialects/test_tsql.py::TestTSQL::test_len", "tests/dialects/test_tsql.py::TestTSQL::test_next_value_for", "tests/dialects/test_tsql.py::TestTSQL::test_openjson", "tests/dialects/test_tsql.py::TestTSQL::test_option", "tests/dialects/test_tsql.py::TestTSQL::test_parsename", "tests/dialects/test_tsql.py::TestTSQL::test_procedure_keywords", "tests/dialects/test_tsql.py::TestTSQL::test_qualify_derived_table_outputs", "tests/dialects/test_tsql.py::TestTSQL::test_replicate", "tests/dialects/test_tsql.py::TestTSQL::test_rollback", "tests/dialects/test_tsql.py::TestTSQL::test_scope_resolution_op", "tests/dialects/test_tsql.py::TestTSQL::test_set", "tests/dialects/test_tsql.py::TestTSQL::test_string", "tests/dialects/test_tsql.py::TestTSQL::test_system_time", "tests/dialects/test_tsql.py::TestTSQL::test_temporal_table", "tests/dialects/test_tsql.py::TestTSQL::test_top", "tests/dialects/test_tsql.py::TestTSQL::test_transaction", "tests/dialects/test_tsql.py::TestTSQL::test_tsql", "tests/dialects/test_tsql.py::TestTSQL::test_types", "tests/dialects/test_tsql.py::TestTSQL::test_types_bin", "tests/dialects/test_tsql.py::TestTSQL::test_types_date", "tests/dialects/test_tsql.py::TestTSQL::test_types_decimals", "tests/dialects/test_tsql.py::TestTSQL::test_types_ints", "tests/dialects/test_tsql.py::TestTSQL::test_types_string", "tests/dialects/test_tsql.py::TestTSQL::test_udf" ]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> feat(tsql): add support for DATETRUNC #4531 Fixes [https://github.com/tobymao/sqlglot/issues/4531](https://github.com/tobymao/sqlglot/issues/4531) This PR adds support for the `DATETRUNC` function of `T-SQL`. In cases, where the `date` parameter is a `string literal`, a casting is applied to produce a `DATETIME2` expression. Based on `T-SQL`, all `string literals` should resolve into `DATETIME2`. Dialects like `duckdb` do not support the direct `string literals` as dates, thus the casting is mandatory. **Docs** [T-SQL DATETRUNC](https://learn.microsoft.com/en-us/sql/t-sql/functions/datetrunc-transact-sql?view=sql-server-ver16) ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in sqlglot/dialects/tsql.py] (definition of _build_datetrunc:) def _build_datetrunc(args: t.List) -> exp.TimestampTrunc: [end of new definitions in sqlglot/dialects/tsql.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
ceb42fabad60312699e4b15936aeebac00e22e4d
tobymao__sqlglot-4486
4,486
tobymao/sqlglot
null
2655d7c11d677cf47f33ac62fbfb86f4117ffd75
2024-12-09T09:14:24Z
diff --git a/sqlglot/dialects/snowflake.py b/sqlglot/dialects/snowflake.py index e0d392b0cd..93731f3049 100644 --- a/sqlglot/dialects/snowflake.py +++ b/sqlglot/dialects/snowflake.py @@ -107,6 +107,13 @@ def _builder(args: t.List) -> E: return _builder +def _build_bitor(args: t.List) -> exp.BitwiseOr | exp.Anonymous: + if len(args) == 3: + return exp.Anonymous(this="BITOR", expressions=args) + + return binary_from_function(exp.BitwiseOr)(args) + + # https://docs.snowflake.com/en/sql-reference/functions/div0 def _build_if_from_div0(args: t.List) -> exp.If: lhs = exp._wrap(seq_get(args, 0), exp.Binary) @@ -393,6 +400,8 @@ class Parser(parser.Parser): ), "BITXOR": binary_from_function(exp.BitwiseXor), "BIT_XOR": binary_from_function(exp.BitwiseXor), + "BITOR": _build_bitor, + "BIT_OR": _build_bitor, "BOOLXOR": binary_from_function(exp.Xor), "DATE": _build_datetime("DATE", exp.DataType.Type.DATE), "DATE_TRUNC": _date_trunc_to_time, @@ -869,6 +878,7 @@ class Generator(generator.Generator): "CONVERT_TIMEZONE", e.args.get("zone"), e.this ), exp.BitwiseXor: rename_func("BITXOR"), + exp.BitwiseOr: rename_func("BITOR"), exp.Create: transforms.preprocess([_flatten_structured_types_unless_iceberg]), exp.DateAdd: date_delta_sql("DATEADD"), exp.DateDiff: date_delta_sql("DATEDIFF"),
diff --git a/tests/dialects/test_snowflake.py b/tests/dialects/test_snowflake.py index 4eb97235da..f70023b9ea 100644 --- a/tests/dialects/test_snowflake.py +++ b/tests/dialects/test_snowflake.py @@ -976,6 +976,12 @@ def test_snowflake(self): "snowflake": "EDITDISTANCE(col1, col2, 3)", }, ) + self.validate_identity("SELECT BITOR(a, b) FROM table") + + self.validate_identity("SELECT BIT_OR(a, b) FROM table", "SELECT BITOR(a, b) FROM table") + + # Test BITOR with three arguments, padding on the left + self.validate_identity("SELECT BITOR(a, b, 'LEFT') FROM table_name") def test_null_treatment(self): self.validate_all(
[ { "components": [ { "doc": "", "lines": [ 110, 114 ], "name": "_build_bitor", "signature": "def _build_bitor(args: t.List) -> exp.BitwiseOr | exp.Anonymous:", "type": "function" } ], "file": "sqlglot/dialects/snowflake.py" } ]
[ "tests/dialects/test_snowflake.py::TestSnowflake::test_snowflake" ]
[ "tests/dialects/test_snowflake.py::TestSnowflake::test_alter_set_unset", "tests/dialects/test_snowflake.py::TestSnowflake::test_copy", "tests/dialects/test_snowflake.py::TestSnowflake::test_ddl", "tests/dialects/test_snowflake.py::TestSnowflake::test_describe_table", "tests/dialects/test_snowflake.py::TestSnowflake::test_flatten", "tests/dialects/test_snowflake.py::TestSnowflake::test_from_changes", "tests/dialects/test_snowflake.py::TestSnowflake::test_grant", "tests/dialects/test_snowflake.py::TestSnowflake::test_historical_data", "tests/dialects/test_snowflake.py::TestSnowflake::test_match_recognize", "tests/dialects/test_snowflake.py::TestSnowflake::test_minus", "tests/dialects/test_snowflake.py::TestSnowflake::test_null_treatment", "tests/dialects/test_snowflake.py::TestSnowflake::test_parse_like_any", "tests/dialects/test_snowflake.py::TestSnowflake::test_querying_semi_structured_data", "tests/dialects/test_snowflake.py::TestSnowflake::test_regexp_replace", "tests/dialects/test_snowflake.py::TestSnowflake::test_regexp_substr", "tests/dialects/test_snowflake.py::TestSnowflake::test_sample", "tests/dialects/test_snowflake.py::TestSnowflake::test_semi_structured_types", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_columns", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_imported_keys", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_objects", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_primary_keys", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_schemas", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_sequences", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_tables", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_unique_keys", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_users", "tests/dialects/test_snowflake.py::TestSnowflake::test_show_views", "tests/dialects/test_snowflake.py::TestSnowflake::test_staged_files", "tests/dialects/test_snowflake.py::TestSnowflake::test_storage_integration", "tests/dialects/test_snowflake.py::TestSnowflake::test_stored_procedures", "tests/dialects/test_snowflake.py::TestSnowflake::test_swap", "tests/dialects/test_snowflake.py::TestSnowflake::test_table_literal", "tests/dialects/test_snowflake.py::TestSnowflake::test_timestamps", "tests/dialects/test_snowflake.py::TestSnowflake::test_try_cast", "tests/dialects/test_snowflake.py::TestSnowflake::test_user_defined_functions", "tests/dialects/test_snowflake.py::TestSnowflake::test_values", "tests/dialects/test_snowflake.py::TestSnowflake::test_window_function_arg" ]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> feat(snowflake): Transpile support for bitor/bit_or snowflake function scenarios involving binary data manipulation, such as managing permission sets or feature flags. BITOR Function: The BITOR function computes the bitwise OR between two numeric or binary expressions. This operation compares each bit of the inputs and returns a result where each bit is set to 1 if at least one of the corresponding bits of the operands is 1; otherwise, it is set to 0. Example: Suppose you have a table user_permissions that stores user IDs along with two permission sets, perm_set1 and perm_set2, represented as integers: ``` CREATE OR REPLACE TABLE user_permissions ( user_id INTEGER, perm_set1 INTEGER, perm_set2 INTEGER ); INSERT INTO user_permissions (user_id, perm_set1, perm_set2) VALUES (1, 2, 4), -- Binary: perm_set1 = 010, perm_set2 = 100 (2, 1, 2); -- Binary: perm_set1 = 001, perm_set2 = 010 ``` To determine the combined permissions for each user, you can use the BITOR function: ``` SELECT user_id, BITOR(perm_set1, perm_set2) AS combined_permissions FROM user_permissions; ``` This query produces: ``` +---------+-------------------------+ | user_id | combined_permissions | +---------+-------------------------+ | 1 | 6 | -- Binary: 110 | 2 | 3 | -- Binary: 011 +---------+-------------------------+ ``` At **Walmart**, we use to use `bitor`, `bit_or` a lot of places. I have observed that this support is not there in `sqlglot` and hence I have added the code and test case for this. Kindly check it once. ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in sqlglot/dialects/snowflake.py] (definition of _build_bitor:) def _build_bitor(args: t.List) -> exp.BitwiseOr | exp.Anonymous: [end of new definitions in sqlglot/dialects/snowflake.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
ceb42fabad60312699e4b15936aeebac00e22e4d
googleapis__python-aiplatform-4748
4,748
googleapis/python-aiplatform
null
91d837ece0c02c381cda9fbe9c0c839f9986f182
2024-12-05T14:26:24Z
diff --git a/samples/model-builder/vector_search/vector_search_find_neighbors_sample.py b/samples/model-builder/vector_search/vector_search_find_neighbors_sample.py index f2bcb4ad3a..31417cbe58 100644 --- a/samples/model-builder/vector_search/vector_search_find_neighbors_sample.py +++ b/samples/model-builder/vector_search/vector_search_find_neighbors_sample.py @@ -25,7 +25,9 @@ def vector_search_find_neighbors( deployed_index_id: str, queries: List[List[float]], num_neighbors: int, -) -> None: +) -> List[ + List[aiplatform.matching_engine.matching_engine_index_endpoint.MatchNeighbor] +]: """Query the vector search index. Args: @@ -38,6 +40,9 @@ def vector_search_find_neighbors( queries (List[List[float]]): Required. A list of queries. Each query is a list of floats, representing a single embedding. num_neighbors (int): Required. The number of neighbors to return. + + Returns: + List[List[aiplatform.matching_engine.matching_engine_index_endpoint.MatchNeighbor]] - A list of nearest neighbors for each query. """ # Initialize the Vertex AI client aiplatform.init(project=project, location=location) @@ -48,12 +53,47 @@ def vector_search_find_neighbors( ) # Query the index endpoint for the nearest neighbors. - resp = my_index_endpoint.find_neighbors( + return my_index_endpoint.find_neighbors( deployed_index_id=deployed_index_id, queries=queries, num_neighbors=num_neighbors, ) - print(resp) + + +# [END aiplatform_sdk_vector_search_find_neighbors_sample] + + +# [START aiplatform_sdk_vector_search_find_neighbors_hybrid_sample] +def vector_search_find_neighbors_hybrid_queries( + project: str, + location: str, + index_endpoint_name: str, + deployed_index_id: str, + num_neighbors: int, +) -> List[ + List[aiplatform.matching_engine.matching_engine_index_endpoint.MatchNeighbor] +]: + """Query the vector search index using example hybrid queries. + + Args: + project (str): Required. Project ID + location (str): Required. The region name + index_endpoint_name (str): Required. Index endpoint to run the query + against. + deployed_index_id (str): Required. The ID of the DeployedIndex to run + the queries against. + num_neighbors (int): Required. The number of neighbors to return. + + Returns: + List[List[aiplatform.matching_engine.matching_engine_index_endpoint.MatchNeighbor]] - A list of nearest neighbors for each query. + """ + # Initialize the Vertex AI client + aiplatform.init(project=project, location=location) + + # Create the index endpoint instance from an existing endpoint. + my_index_endpoint = aiplatform.MatchingEngineIndexEndpoint( + index_endpoint_name=index_endpoint_name + ) # Query hybrid datapoints, sparse-only datapoints, and dense-only datapoints. hybrid_queries = [ @@ -77,13 +117,79 @@ def vector_search_find_neighbors( ), ] - hybrid_resp = my_index_endpoint.find_neighbors( - deployed_index_id=deployed_index_id, - queries=hybrid_queries, - num_neighbors=num_neighbors,) - print(hybrid_resp) + return my_index_endpoint.find_neighbors( + deployed_index_id=deployed_index_id, + queries=hybrid_queries, + num_neighbors=num_neighbors, + ) -# [END aiplatform_sdk_vector_search_find_neighbors_sample] + +# [END aiplatform_sdk_vector_search_find_neighbors_hybrid_sample] + + +# [START aiplatform_sdk_vector_search_find_neighbors_filtering_crowding_sample] +def vector_search_find_neighbors_filtering_crowding( + project: str, + location: str, + index_endpoint_name: str, + deployed_index_id: str, + queries: List[List[float]], + num_neighbors: int, + filter: List[aiplatform.matching_engine.matching_engine_index_endpoint.Namespace], + numeric_filter: List[ + aiplatform.matching_engine.matching_engine_index_endpoint.NumericNamespace + ], + per_crowding_attribute_neighbor_count: int, +) -> List[ + List[aiplatform.matching_engine.matching_engine_index_endpoint.MatchNeighbor] +]: + """Query the vector search index with filtering and crowding. + + Args: + project (str): Required. Project ID + location (str): Required. The region name + index_endpoint_name (str): Required. Index endpoint to run the query + against. + deployed_index_id (str): Required. The ID of the DeployedIndex to run + the queries against. + queries (List[List[float]]): Required. A list of queries. Each query is + a list of floats, representing a single embedding. + num_neighbors (int): Required. The number of neighbors to return. + filter (List[Namespace]): Required. A list of Namespaces for filtering + the matching results. For example, + [Namespace("color", ["red"], []), Namespace("shape", [], ["square"])] + will match datapoints that satisfy "red color" but not include + datapoints with "square shape". + numeric_filter (List[NumericNamespace]): Required. A list of + NumericNamespaces for filtering the matching results. For example, + [NumericNamespace(name="cost", value_int=5, op="GREATER")] will limit + the matching results to datapoints with cost greater than 5. + per_crowding_attribute_neighbor_count (int): Required. The maximum + number of returned matches with the same crowding tag. + + Returns: + List[List[aiplatform.matching_engine.matching_engine_index_endpoint.MatchNeighbor]] - A list of nearest neighbors for each query. + """ + # Initialize the Vertex AI client + aiplatform.init(project=project, location=location) + + # Create the index endpoint instance from an existing endpoint. + my_index_endpoint = aiplatform.MatchingEngineIndexEndpoint( + index_endpoint_name=index_endpoint_name + ) + + # Query the index endpoint for the nearest neighbors. + return my_index_endpoint.find_neighbors( + deployed_index_id=deployed_index_id, + queries=queries, + num_neighbors=num_neighbors, + filter=filter, + numeric_filter=numeric_filter, + per_crowding_attribute_neighbor_count=per_crowding_attribute_neighbor_count, + ) + + +# [END aiplatform_sdk_vector_search_find_neighbors_filtering_crowding_sample] # [START aiplatform_sdk_vector_search_find_neighbors_jwt_sample] @@ -95,7 +201,9 @@ def vector_search_find_neighbors_jwt( queries: List[List[float]], num_neighbors: int, signed_jwt: str, -) -> List[List[aiplatform.matching_engine.matching_engine_index_endpoint.MatchNeighbor]]: +) -> List[ + List[aiplatform.matching_engine.matching_engine_index_endpoint.MatchNeighbor] +]: """Query the vector search index. Args: @@ -132,4 +240,5 @@ def vector_search_find_neighbors_jwt( ) return resp + # [END aiplatform_sdk_vector_search_find_neighbors_jwt_sample]
diff --git a/samples/model-builder/test_constants.py b/samples/model-builder/test_constants.py index 3a7d3ed3c3..5930d8394d 100644 --- a/samples/model-builder/test_constants.py +++ b/samples/model-builder/test_constants.py @@ -382,14 +382,18 @@ # Vector Search VECTOR_SEARCH_INDEX = "123" VECTOR_SEARCH_INDEX_DATAPOINTS = [ - aiplatform.compat.types.index_v1beta1.IndexDatapoint(datapoint_id="datapoint_id_1", feature_vector=[0.1, 0.2]), - aiplatform.compat.types.index_v1beta1.IndexDatapoint(datapoint_id="datapoint_id_2", feature_vector=[0.3, 0.4]), + aiplatform.compat.types.index_v1beta1.IndexDatapoint( + datapoint_id="datapoint_id_1", feature_vector=[0.1, 0.2] + ), + aiplatform.compat.types.index_v1beta1.IndexDatapoint( + datapoint_id="datapoint_id_2", feature_vector=[0.3, 0.4] + ), ] VECTOR_SEARCH_INDEX_DATAPOINT_IDS = ["datapoint_id_1", "datapoint_id_2"] VECTOR_SEARCH_INDEX_ENDPOINT = "456" VECTOR_SEARCH_DEPLOYED_INDEX_ID = "789" -VECTOR_SERACH_INDEX_QUERIES = [[0.1]] -VECTOR_SERACH_INDEX_HYBRID_QUERIES = [ +VECTOR_SEARCH_INDEX_QUERIES = [[0.1]] +VECTOR_SEARCH_INDEX_HYBRID_QUERIES = [ aiplatform.matching_engine.matching_engine_index_endpoint.HybridQuery( dense_embedding=[1, 2, 3], sparse_embedding_dimensions=[10, 20, 30], @@ -409,6 +413,20 @@ dense_embedding=[1, 2, 3] ), ] +VECTOR_SEARCH_FILTER = [ + aiplatform.matching_engine.matching_engine_index_endpoint.Namespace( + "color", ["red"], [] + ), + aiplatform.matching_engine.matching_engine_index_endpoint.Namespace( + "shape", [], ["squared"] + ), +] +VECTOR_SEARCH_NUMERIC_FILTER = [ + aiplatform.matching_engine.matching_engine_index_endpoint.NumericNamespace( + name="cost", value_int=5, op="GREATER" + ) +] +VECTOR_SEARCH_PER_CROWDING_ATTRIBUTE_NEIGHBOR_COUNT = 5 VECTOR_SEARCH_INDEX_DISPLAY_NAME = "my-vector-search-index" VECTOR_SEARCH_INDEX_DESCRIPTION = "test description" VECTOR_SEARCH_INDEX_LABELS = {"my_key": "my_value"} diff --git a/samples/model-builder/vector_search/vector_search_find_neighbors_sample_test.py b/samples/model-builder/vector_search/vector_search_find_neighbors_sample_test.py index 30f1f5711d..35c6dfe217 100644 --- a/samples/model-builder/vector_search/vector_search_find_neighbors_sample_test.py +++ b/samples/model-builder/vector_search/vector_search_find_neighbors_sample_test.py @@ -12,8 +12,6 @@ # See the License for the specific language governing permissions and # limitations under the License. -from unittest.mock import call - import test_constants as constants from vector_search import vector_search_find_neighbors_sample @@ -26,8 +24,8 @@ def test_vector_search_find_neighbors_sample( location=constants.LOCATION, index_endpoint_name=constants.VECTOR_SEARCH_INDEX_ENDPOINT, deployed_index_id=constants.VECTOR_SEARCH_DEPLOYED_INDEX_ID, - queries=constants.VECTOR_SERACH_INDEX_QUERIES, - num_neighbors=10 + queries=constants.VECTOR_SEARCH_INDEX_QUERIES, + num_neighbors=10, ) # Check client initialization @@ -37,23 +35,79 @@ def test_vector_search_find_neighbors_sample( # Check index endpoint initialization with right index endpoint name mock_index_endpoint_init.assert_called_with( - index_endpoint_name=constants.VECTOR_SEARCH_INDEX_ENDPOINT) + index_endpoint_name=constants.VECTOR_SEARCH_INDEX_ENDPOINT + ) # Check index_endpoint.find_neighbors is called with right params. - mock_index_endpoint_find_neighbors.assert_has_calls( - [ - call( - deployed_index_id=constants.VECTOR_SEARCH_DEPLOYED_INDEX_ID, - queries=constants.VECTOR_SERACH_INDEX_QUERIES, - num_neighbors=10, - ), - call( - deployed_index_id=constants.VECTOR_SEARCH_DEPLOYED_INDEX_ID, - queries=constants.VECTOR_SERACH_INDEX_HYBRID_QUERIES, - num_neighbors=10, - ), - ], - any_order=False, + mock_index_endpoint_find_neighbors.assert_called_with( + deployed_index_id=constants.VECTOR_SEARCH_DEPLOYED_INDEX_ID, + queries=constants.VECTOR_SEARCH_INDEX_QUERIES, + num_neighbors=10, + ) + + +def test_vector_search_find_neighbors_hybrid_sample( + mock_sdk_init, mock_index_endpoint_init, mock_index_endpoint_find_neighbors +): + vector_search_find_neighbors_sample.vector_search_find_neighbors_hybrid_queries( + project=constants.PROJECT, + location=constants.LOCATION, + index_endpoint_name=constants.VECTOR_SEARCH_INDEX_ENDPOINT, + deployed_index_id=constants.VECTOR_SEARCH_DEPLOYED_INDEX_ID, + num_neighbors=10, + ) + + # Check client initialization + mock_sdk_init.assert_called_with( + project=constants.PROJECT, location=constants.LOCATION + ) + + # Check index endpoint initialization with right index endpoint name + mock_index_endpoint_init.assert_called_with( + index_endpoint_name=constants.VECTOR_SEARCH_INDEX_ENDPOINT + ) + + # Check index_endpoint.find_neighbors is called with right params. + mock_index_endpoint_find_neighbors.assert_called_with( + deployed_index_id=constants.VECTOR_SEARCH_DEPLOYED_INDEX_ID, + queries=constants.VECTOR_SEARCH_INDEX_HYBRID_QUERIES, + num_neighbors=10, + ) + + +def test_vector_search_find_neighbors_filtering_crowding_sample( + mock_sdk_init, mock_index_endpoint_init, mock_index_endpoint_find_neighbors +): + vector_search_find_neighbors_sample.vector_search_find_neighbors_filtering_crowding( + project=constants.PROJECT, + location=constants.LOCATION, + index_endpoint_name=constants.VECTOR_SEARCH_INDEX_ENDPOINT, + deployed_index_id=constants.VECTOR_SEARCH_DEPLOYED_INDEX_ID, + queries=constants.VECTOR_SEARCH_INDEX_QUERIES, + num_neighbors=10, + filter=constants.VECTOR_SEARCH_FILTER, + numeric_filter=constants.VECTOR_SEARCH_NUMERIC_FILTER, + per_crowding_attribute_neighbor_count=constants.VECTOR_SEARCH_PER_CROWDING_ATTRIBUTE_NEIGHBOR_COUNT, + ) + + # Check client initialization + mock_sdk_init.assert_called_with( + project=constants.PROJECT, location=constants.LOCATION + ) + + # Check index endpoint initialization with right index endpoint name + mock_index_endpoint_init.assert_called_with( + index_endpoint_name=constants.VECTOR_SEARCH_INDEX_ENDPOINT + ) + + # Check index_endpoint.find_neighbors is called with right params. + mock_index_endpoint_find_neighbors.assert_called_with( + deployed_index_id=constants.VECTOR_SEARCH_DEPLOYED_INDEX_ID, + queries=constants.VECTOR_SEARCH_INDEX_QUERIES, + num_neighbors=10, + filter=constants.VECTOR_SEARCH_FILTER, + numeric_filter=constants.VECTOR_SEARCH_NUMERIC_FILTER, + per_crowding_attribute_neighbor_count=constants.VECTOR_SEARCH_PER_CROWDING_ATTRIBUTE_NEIGHBOR_COUNT, ) @@ -65,7 +119,7 @@ def test_vector_search_find_neighbors_jwt_sample( location=constants.LOCATION, index_endpoint_name=constants.VECTOR_SEARCH_INDEX_ENDPOINT, deployed_index_id=constants.VECTOR_SEARCH_DEPLOYED_INDEX_ID, - queries=constants.VECTOR_SERACH_INDEX_QUERIES, + queries=constants.VECTOR_SEARCH_INDEX_QUERIES, num_neighbors=10, signed_jwt=constants.VECTOR_SEARCH_PRIVATE_ENDPOINT_SIGNED_JWT, ) @@ -77,12 +131,13 @@ def test_vector_search_find_neighbors_jwt_sample( # Check index endpoint initialization with right index endpoint name mock_index_endpoint_init.assert_called_with( - index_endpoint_name=constants.VECTOR_SEARCH_INDEX_ENDPOINT) + index_endpoint_name=constants.VECTOR_SEARCH_INDEX_ENDPOINT + ) # Check index_endpoint.find_neighbors is called with right params. mock_index_endpoint_find_neighbors.assert_called_with( deployed_index_id=constants.VECTOR_SEARCH_DEPLOYED_INDEX_ID, - queries=constants.VECTOR_SERACH_INDEX_QUERIES, + queries=constants.VECTOR_SEARCH_INDEX_QUERIES, num_neighbors=10, signed_jwt=constants.VECTOR_SEARCH_PRIVATE_ENDPOINT_SIGNED_JWT, ) diff --git a/samples/model-builder/vector_search/vector_search_match_sample_test.py b/samples/model-builder/vector_search/vector_search_match_sample_test.py index 5d1c5faa64..081e334ef4 100644 --- a/samples/model-builder/vector_search/vector_search_match_sample_test.py +++ b/samples/model-builder/vector_search/vector_search_match_sample_test.py @@ -36,7 +36,8 @@ def test_vector_search_match_hybrid_queries_sample( # Check index endpoint initialization with right index endpoint name mock_index_endpoint_init.assert_called_with( - index_endpoint_name=constants.VECTOR_SEARCH_INDEX_ENDPOINT) + index_endpoint_name=constants.VECTOR_SEARCH_INDEX_ENDPOINT + ) # Check index_endpoint.match is called with right params. mock_index_endpoint_match.assert_called_with( @@ -54,7 +55,7 @@ def test_vector_search_match_jwt_sample( location=constants.LOCATION, index_endpoint_name=constants.VECTOR_SEARCH_INDEX_ENDPOINT, deployed_index_id=constants.VECTOR_SEARCH_DEPLOYED_INDEX_ID, - queries=constants.VECTOR_SERACH_INDEX_QUERIES, + queries=constants.VECTOR_SEARCH_INDEX_QUERIES, num_neighbors=10, signed_jwt=constants.VECTOR_SEARCH_PRIVATE_ENDPOINT_SIGNED_JWT, ) @@ -66,12 +67,13 @@ def test_vector_search_match_jwt_sample( # Check index endpoint initialization with right index endpoint name mock_index_endpoint_init.assert_called_with( - index_endpoint_name=constants.VECTOR_SEARCH_INDEX_ENDPOINT) + index_endpoint_name=constants.VECTOR_SEARCH_INDEX_ENDPOINT + ) # Check index_endpoint.match is called with right params. mock_index_endpoint_match.assert_called_with( deployed_index_id=constants.VECTOR_SEARCH_DEPLOYED_INDEX_ID, - queries=constants.VECTOR_SERACH_INDEX_QUERIES, + queries=constants.VECTOR_SEARCH_INDEX_QUERIES, num_neighbors=10, signed_jwt=constants.VECTOR_SEARCH_PRIVATE_ENDPOINT_SIGNED_JWT, ) @@ -81,14 +83,14 @@ def test_vector_search_match_psc_manual_sample( mock_sdk_init, mock_index_endpoint, mock_index_endpoint_init, - mock_index_endpoint_match + mock_index_endpoint_match, ): vector_search_match_sample.vector_search_match_psc_manual( project=constants.PROJECT, location=constants.LOCATION, index_endpoint_name=constants.VECTOR_SEARCH_INDEX_ENDPOINT, deployed_index_id=constants.VECTOR_SEARCH_DEPLOYED_INDEX_ID, - queries=constants.VECTOR_SERACH_INDEX_QUERIES, + queries=constants.VECTOR_SEARCH_INDEX_QUERIES, num_neighbors=10, ip_address=constants.VECTOR_SEARCH_PSC_MANUAL_IP_ADDRESS, ) @@ -100,7 +102,8 @@ def test_vector_search_match_psc_manual_sample( # Check index endpoint initialization with right index endpoint name mock_index_endpoint_init.assert_called_with( - index_endpoint_name=constants.VECTOR_SEARCH_INDEX_ENDPOINT) + index_endpoint_name=constants.VECTOR_SEARCH_INDEX_ENDPOINT + ) # Check index endpoint PSC IP address is set assert mock_index_endpoint.private_service_connect_ip_address == ( @@ -110,7 +113,7 @@ def test_vector_search_match_psc_manual_sample( # Check index_endpoint.match is called with right params. mock_index_endpoint_match.assert_called_with( deployed_index_id=constants.VECTOR_SEARCH_DEPLOYED_INDEX_ID, - queries=constants.VECTOR_SERACH_INDEX_QUERIES, + queries=constants.VECTOR_SEARCH_INDEX_QUERIES, num_neighbors=10, ) @@ -123,7 +126,7 @@ def test_vector_search_match_psc_automation_sample( location=constants.LOCATION, index_endpoint_name=constants.VECTOR_SEARCH_INDEX_ENDPOINT, deployed_index_id=constants.VECTOR_SEARCH_DEPLOYED_INDEX_ID, - queries=constants.VECTOR_SERACH_INDEX_QUERIES, + queries=constants.VECTOR_SEARCH_INDEX_QUERIES, num_neighbors=10, psc_network=constants.VECTOR_SEARCH_VPC_NETWORK, ) @@ -135,12 +138,13 @@ def test_vector_search_match_psc_automation_sample( # Check index endpoint initialization with right index endpoint name mock_index_endpoint_init.assert_called_with( - index_endpoint_name=constants.VECTOR_SEARCH_INDEX_ENDPOINT) + index_endpoint_name=constants.VECTOR_SEARCH_INDEX_ENDPOINT + ) # Check index_endpoint.match is called with right params. mock_index_endpoint_match.assert_called_with( deployed_index_id=constants.VECTOR_SEARCH_DEPLOYED_INDEX_ID, - queries=constants.VECTOR_SERACH_INDEX_QUERIES, + queries=constants.VECTOR_SEARCH_INDEX_QUERIES, num_neighbors=10, psc_network=constants.VECTOR_SEARCH_VPC_NETWORK, )
[ { "components": [ { "doc": "Query the vector search index using example hybrid queries.\n\nArgs:\n project (str): Required. Project ID\n location (str): Required. The region name\n index_endpoint_name (str): Required. Index endpoint to run the query\n against.\n deployed_index_id (str): Required. The ID of the DeployedIndex to run\n the queries against.\n num_neighbors (int): Required. The number of neighbors to return.\n\nReturns:\n List[List[aiplatform.matching_engine.matching_engine_index_endpoint.MatchNeighbor]] - A list of nearest neighbors for each query.", "lines": [ 67, 123 ], "name": "vector_search_find_neighbors_hybrid_queries", "signature": "def vector_search_find_neighbors_hybrid_queries( project: str, location: str, index_endpoint_name: str, deployed_index_id: str, num_neighbors: int, ) -> List[ List[aiplatform.matching_engine.matching_engine_index_endpoint.MatchNeighbor] ]:", "type": "function" }, { "doc": "Query the vector search index with filtering and crowding.\n\nArgs:\n project (str): Required. Project ID\n location (str): Required. The region name\n index_endpoint_name (str): Required. Index endpoint to run the query\n against.\n deployed_index_id (str): Required. The ID of the DeployedIndex to run\n the queries against.\n queries (List[List[float]]): Required. A list of queries. Each query is\n a list of floats, representing a single embedding.\n num_neighbors (int): Required. The number of neighbors to return.\n filter (List[Namespace]): Required. A list of Namespaces for filtering\n the matching results. For example,\n [Namespace(\"color\", [\"red\"], []), Namespace(\"shape\", [], [\"square\"])]\n will match datapoints that satisfy \"red color\" but not include\n datapoints with \"square shape\".\n numeric_filter (List[NumericNamespace]): Required. A list of\n NumericNamespaces for filtering the matching results. For example,\n [NumericNamespace(name=\"cost\", value_int=5, op=\"GREATER\")] will limit\n the matching results to datapoints with cost greater than 5.\n per_crowding_attribute_neighbor_count (int): Required. The maximum\n number of returned matches with the same crowding tag.\n\nReturns:\n List[List[aiplatform.matching_engine.matching_engine_index_endpoint.MatchNeighbor]] - A list of nearest neighbors for each query.", "lines": [ 131, 188 ], "name": "vector_search_find_neighbors_filtering_crowding", "signature": "def vector_search_find_neighbors_filtering_crowding( project: str, location: str, index_endpoint_name: str, deployed_index_id: str, queries: List[List[float]], num_neighbors: int, filter: List[aiplatform.matching_engine.matching_engine_index_endpoint.Namespace], numeric_filter: List[ aiplatform.matching_engine.matching_engine_index_endpoint.NumericNamespace ], per_crowding_attribute_neighbor_count: int, ) -> List[ List[aiplatform.matching_engine.matching_engine_index_endpoint.MatchNeighbor] ]:", "type": "function" } ], "file": "samples/model-builder/vector_search/vector_search_find_neighbors_sample.py" } ]
[ "samples/model-builder/vector_search/vector_search_find_neighbors_sample_test.py::test_vector_search_find_neighbors_sample", "samples/model-builder/vector_search/vector_search_find_neighbors_sample_test.py::test_vector_search_find_neighbors_hybrid_sample", "samples/model-builder/vector_search/vector_search_find_neighbors_sample_test.py::test_vector_search_find_neighbors_filtering_crowding_sample" ]
[ "samples/model-builder/vector_search/vector_search_find_neighbors_sample_test.py::test_vector_search_find_neighbors_jwt_sample", "samples/model-builder/vector_search/vector_search_match_sample_test.py::test_vector_search_match_hybrid_queries_sample", "samples/model-builder/vector_search/vector_search_match_sample_test.py::test_vector_search_match_jwt_sample", "samples/model-builder/vector_search/vector_search_match_sample_test.py::test_vector_search_match_psc_manual_sample", "samples/model-builder/vector_search/vector_search_match_sample_test.py::test_vector_search_match_psc_automation_sample" ]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> chore: Samples - Add vector search sample for filtering and crowding chore: Samples - Add vector search sample for filtering and crowding ---------- <!-- probot comment [11299897]--> Here is the summary of changes. <details> <summary>You are about to add 2 region tags.</summary> - [samples/model-builder/vector_search/vector_search_find_neighbors_sample.py:66](https://github.com/googleapis/python-aiplatform/blob/3ea43524f7961fdb29c4f75cf529852894bf1c86/samples/model-builder/vector_search/vector_search_find_neighbors_sample.py#L66), tag `aiplatform_sdk_vector_search_find_neighbors_hybrid_sample` - [samples/model-builder/vector_search/vector_search_find_neighbors_sample.py:130](https://github.com/googleapis/python-aiplatform/blob/3ea43524f7961fdb29c4f75cf529852894bf1c86/samples/model-builder/vector_search/vector_search_find_neighbors_sample.py#L130), tag `aiplatform_sdk_vector_search_find_neighbors_filtering_crowding_sample` </details> --- This comment is generated by [snippet-bot](https://github.com/apps/snippet-bot). If you find problems with this result, please file an issue at: https://github.com/googleapis/repo-automation-bots/issues. To update this comment, add `snippet-bot:force-run` label or use the checkbox below: - [ ] Refresh this comment </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in samples/model-builder/vector_search/vector_search_find_neighbors_sample.py] (definition of vector_search_find_neighbors_hybrid_queries:) def vector_search_find_neighbors_hybrid_queries( project: str, location: str, index_endpoint_name: str, deployed_index_id: str, num_neighbors: int, ) -> List[ List[aiplatform.matching_engine.matching_engine_index_endpoint.MatchNeighbor] ]: """Query the vector search index using example hybrid queries. Args: project (str): Required. Project ID location (str): Required. The region name index_endpoint_name (str): Required. Index endpoint to run the query against. deployed_index_id (str): Required. The ID of the DeployedIndex to run the queries against. num_neighbors (int): Required. The number of neighbors to return. Returns: List[List[aiplatform.matching_engine.matching_engine_index_endpoint.MatchNeighbor]] - A list of nearest neighbors for each query.""" (definition of vector_search_find_neighbors_filtering_crowding:) def vector_search_find_neighbors_filtering_crowding( project: str, location: str, index_endpoint_name: str, deployed_index_id: str, queries: List[List[float]], num_neighbors: int, filter: List[aiplatform.matching_engine.matching_engine_index_endpoint.Namespace], numeric_filter: List[ aiplatform.matching_engine.matching_engine_index_endpoint.NumericNamespace ], per_crowding_attribute_neighbor_count: int, ) -> List[ List[aiplatform.matching_engine.matching_engine_index_endpoint.MatchNeighbor] ]: """Query the vector search index with filtering and crowding. Args: project (str): Required. Project ID location (str): Required. The region name index_endpoint_name (str): Required. Index endpoint to run the query against. deployed_index_id (str): Required. The ID of the DeployedIndex to run the queries against. queries (List[List[float]]): Required. A list of queries. Each query is a list of floats, representing a single embedding. num_neighbors (int): Required. The number of neighbors to return. filter (List[Namespace]): Required. A list of Namespaces for filtering the matching results. For example, [Namespace("color", ["red"], []), Namespace("shape", [], ["square"])] will match datapoints that satisfy "red color" but not include datapoints with "square shape". numeric_filter (List[NumericNamespace]): Required. A list of NumericNamespaces for filtering the matching results. For example, [NumericNamespace(name="cost", value_int=5, op="GREATER")] will limit the matching results to datapoints with cost greater than 5. per_crowding_attribute_neighbor_count (int): Required. The maximum number of returned matches with the same crowding tag. Returns: List[List[aiplatform.matching_engine.matching_engine_index_endpoint.MatchNeighbor]] - A list of nearest neighbors for each query.""" [end of new definitions in samples/model-builder/vector_search/vector_search_find_neighbors_sample.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
67358fa6a830eb842f6b52d09061af4a41b54af6
tobymao__sqlglot-4433
4,433
tobymao/sqlglot
null
38e2e19ac3e20224dc07128994a47340aa56e635
2024-11-20T16:28:28Z
diff --git a/sqlglot/dialects/snowflake.py b/sqlglot/dialects/snowflake.py index 1d2b246e5d..35ac0509cf 100644 --- a/sqlglot/dialects/snowflake.py +++ b/sqlglot/dialects/snowflake.py @@ -198,43 +198,58 @@ def _flatten_structured_type(expression: exp.DataType) -> exp.DataType: return expression -def _unnest_generate_date_array(expression: exp.Expression) -> exp.Expression: - if isinstance(expression, exp.Select): - for unnest in expression.find_all(exp.Unnest): - if ( - isinstance(unnest.parent, (exp.From, exp.Join)) - and len(unnest.expressions) == 1 - and isinstance(unnest.expressions[0], exp.GenerateDateArray) - ): - generate_date_array = unnest.expressions[0] - start = generate_date_array.args.get("start") - end = generate_date_array.args.get("end") - step = generate_date_array.args.get("step") +def _unnest_generate_date_array(unnest: exp.Unnest) -> None: + generate_date_array = unnest.expressions[0] + start = generate_date_array.args.get("start") + end = generate_date_array.args.get("end") + step = generate_date_array.args.get("step") - if not start or not end or not isinstance(step, exp.Interval) or step.name != "1": - continue + if not start or not end or not isinstance(step, exp.Interval) or step.name != "1": + return - unit = step.args.get("unit") + unit = step.args.get("unit") - unnest_alias = unnest.args.get("alias") - if unnest_alias: - unnest_alias = unnest_alias.copy() - sequence_value_name = seq_get(unnest_alias.columns, 0) or "value" - else: - sequence_value_name = "value" + unnest_alias = unnest.args.get("alias") + if unnest_alias: + unnest_alias = unnest_alias.copy() + sequence_value_name = seq_get(unnest_alias.columns, 0) or "value" + else: + sequence_value_name = "value" + + # We'll add the next sequence value to the starting date and project the result + date_add = _build_date_time_add(exp.DateAdd)( + [unit, exp.cast(sequence_value_name, "int"), exp.cast(start, "date")] + ).as_(sequence_value_name) + + # We use DATEDIFF to compute the number of sequence values needed + number_sequence = Snowflake.Parser.FUNCTIONS["ARRAY_GENERATE_RANGE"]( + [exp.Literal.number(0), _build_datediff([unit, start, end]) + 1] + ) + + unnest.set("expressions", [number_sequence]) + unnest.replace(exp.select(date_add).from_(unnest.copy()).subquery(unnest_alias)) - # We'll add the next sequence value to the starting date and project the result - date_add = _build_date_time_add(exp.DateAdd)( - [unit, exp.cast(sequence_value_name, "int"), exp.cast(start, "date")] - ).as_(sequence_value_name) - # We use DATEDIFF to compute the number of sequence values needed - number_sequence = Snowflake.Parser.FUNCTIONS["ARRAY_GENERATE_RANGE"]( - [exp.Literal.number(0), _build_datediff([unit, start, end]) + 1] +def _transform_generate_date_array(expression: exp.Expression) -> exp.Expression: + if isinstance(expression, exp.Select): + for generate_date_array in expression.find_all(exp.GenerateDateArray): + parent = generate_date_array.parent + + # If GENERATE_DATE_ARRAY is used directly as an array (e.g passed into ARRAY_LENGTH), the transformed Snowflake + # query is the following (it'll be unnested properly on the next iteration due to copy): + # SELECT ref(GENERATE_DATE_ARRAY(...)) -> SELECT ref((SELECT ARRAY_AGG(*) FROM UNNEST(GENERATE_DATE_ARRAY(...)))) + if not isinstance(parent, exp.Unnest): + unnest = exp.Unnest(expressions=[generate_date_array.copy()]) + generate_date_array.replace( + exp.select(exp.ArrayAgg(this=exp.Star())).from_(unnest).subquery() ) - unnest.set("expressions", [number_sequence]) - unnest.replace(exp.select(date_add).from_(unnest.copy()).subquery(unnest_alias)) + if ( + isinstance(parent, exp.Unnest) + and isinstance(parent.parent, (exp.From, exp.Join)) + and len(parent.expressions) == 1 + ): + _unnest_generate_date_array(parent) return expression @@ -893,7 +908,7 @@ class Generator(generator.Generator): transforms.eliminate_distinct_on, transforms.explode_to_unnest(), transforms.eliminate_semi_and_anti_joins, - _unnest_generate_date_array, + _transform_generate_date_array, ] ), exp.SafeDivide: lambda self, e: no_safe_divide_sql(self, e, "IFF"),
diff --git a/tests/dialects/test_dialect.py b/tests/dialects/test_dialect.py index f0711fc585..c1aa054a0e 100644 --- a/tests/dialects/test_dialect.py +++ b/tests/dialects/test_dialect.py @@ -2854,6 +2854,13 @@ def test_generate_date_array(self): }, ) + self.validate_all( + "SELECT ARRAY_LENGTH(GENERATE_DATE_ARRAY(DATE '2020-01-01', DATE '2020-02-01', INTERVAL 1 WEEK))", + write={ + "snowflake": "SELECT ARRAY_SIZE((SELECT ARRAY_AGG(*) FROM (SELECT DATEADD(WEEK, CAST(value AS INT), CAST('2020-01-01' AS DATE)) AS value FROM TABLE(FLATTEN(INPUT => ARRAY_GENERATE_RANGE(0, (DATEDIFF(WEEK, CAST('2020-01-01' AS DATE), CAST('2020-02-01' AS DATE)) + 1 - 1) + 1))) AS _u(seq, key, path, index, value, this))))", + }, + ) + def test_set_operation_specifiers(self): self.validate_all( "SELECT 1 EXCEPT ALL SELECT 1",
[ { "components": [ { "doc": "", "lines": [ 233, 254 ], "name": "_transform_generate_date_array", "signature": "def _transform_generate_date_array(expression: exp.Expression) -> exp.Expression:", "type": "function" } ], "file": "sqlglot/dialects/snowflake.py" } ]
[ "tests/dialects/test_dialect.py::TestDialect::test_generate_date_array" ]
[ "tests/dialects/test_dialect.py::TestDialect::test_alias", "tests/dialects/test_dialect.py::TestDialect::test_array", "tests/dialects/test_dialect.py::TestDialect::test_array_any", "tests/dialects/test_dialect.py::TestDialect::test_cast", "tests/dialects/test_dialect.py::TestDialect::test_cast_to_user_defined_type", "tests/dialects/test_dialect.py::TestDialect::test_coalesce", "tests/dialects/test_dialect.py::TestDialect::test_compare_dialects", "tests/dialects/test_dialect.py::TestDialect::test_count_if", "tests/dialects/test_dialect.py::TestDialect::test_create_sequence", "tests/dialects/test_dialect.py::TestDialect::test_cross_join", "tests/dialects/test_dialect.py::TestDialect::test_ddl", "tests/dialects/test_dialect.py::TestDialect::test_decode", "tests/dialects/test_dialect.py::TestDialect::test_enum", "tests/dialects/test_dialect.py::TestDialect::test_escaped_identifier_delimiter", "tests/dialects/test_dialect.py::TestDialect::test_get_or_raise", "tests/dialects/test_dialect.py::TestDialect::test_hash_comments", "tests/dialects/test_dialect.py::TestDialect::test_heredoc_strings", "tests/dialects/test_dialect.py::TestDialect::test_if_null", "tests/dialects/test_dialect.py::TestDialect::test_json", "tests/dialects/test_dialect.py::TestDialect::test_lateral_subquery", "tests/dialects/test_dialect.py::TestDialect::test_limit", "tests/dialects/test_dialect.py::TestDialect::test_logarithm", "tests/dialects/test_dialect.py::TestDialect::test_median", "tests/dialects/test_dialect.py::TestDialect::test_merge", "tests/dialects/test_dialect.py::TestDialect::test_multiple_chained_unnest", "tests/dialects/test_dialect.py::TestDialect::test_nested_ctes", "tests/dialects/test_dialect.py::TestDialect::test_normalize", "tests/dialects/test_dialect.py::TestDialect::test_nullsafe_eq", "tests/dialects/test_dialect.py::TestDialect::test_nullsafe_neq", "tests/dialects/test_dialect.py::TestDialect::test_nvl2", "tests/dialects/test_dialect.py::TestDialect::test_operators", "tests/dialects/test_dialect.py::TestDialect::test_order_by", "tests/dialects/test_dialect.py::TestDialect::test_qualify", "tests/dialects/test_dialect.py::TestDialect::test_random", "tests/dialects/test_dialect.py::TestDialect::test_reserved_keywords", "tests/dialects/test_dialect.py::TestDialect::test_safediv", "tests/dialects/test_dialect.py::TestDialect::test_set_operation_specifiers", "tests/dialects/test_dialect.py::TestDialect::test_set_operators", "tests/dialects/test_dialect.py::TestDialect::test_string_functions", "tests/dialects/test_dialect.py::TestDialect::test_substring", "tests/dialects/test_dialect.py::TestDialect::test_time", "tests/dialects/test_dialect.py::TestDialect::test_transactions", "tests/dialects/test_dialect.py::TestDialect::test_trim", "tests/dialects/test_dialect.py::TestDialect::test_truncate", "tests/dialects/test_dialect.py::TestDialect::test_typeddiv", "tests/dialects/test_dialect.py::TestDialect::test_unsupported_null_ordering", "tests/dialects/test_dialect.py::TestDialect::test_uuid" ]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> feat(snowflake): Transpile non-UNNEST exp.GenerateDateArray refs Currently, transpilation of BQ's `GENERATE_DATE_ARRAY` to Snowflake is supported only if it's `UNNEST`ed (introduced by https://github.com/tobymao/sqlglot/pull/3899), e.g: 1. Supported: ```Python3 >>> import sqlglot >>> sqlglot.parse_one("SELECT * FROM UNNEST(GENERATE_DATE_ARRAY(DATE '2020-01-01', DATE '2020-02-01', INTERVAL 1 WEEK))", read="bigquery").sql("snowflake") "SELECT * FROM (SELECT DATEADD(WEEK, CAST(value AS INT), CAST('2020-01-01' AS DATE)) AS value FROM TABLE(FLATTEN(INPUT => ARRAY_GENERATE_RANGE(0, (DATEDIFF(WEEK, CAST('2020-01-01' AS DATE), CAST('2020-02-01' AS DATE)) + 1 - 1) + 1))) AS _u(seq, key, path, index, value, this))" bigquery> SELECT * FROM UNNEST(GENERATE_DATE_ARRAY(DATE '2020-01-01', DATE '2020-02-01', INTERVAL 1 WEEK)); f0_ 2020-01-01 2020-01-08 2020-01-15 2020-01-22 2020-01-29 snowflake> SELECT * FROM (SELECT DATEADD(WEEK, CAST(value AS INT), CAST('2020-01-01' AS DATE)) AS value FROM TABLE(FLATTEN(INPUT => ARRAY_GENERATE_RANGE(0, (DATEDIFF(WEEK, CAST('2020-01-01' AS DATE), CAST('2020-02-01' AS DATE)) + 1 - 1) + 1))) AS _u(seq, key, path, index, value, this)); -- 2020-01-01 2020-01-08 2020-01-15 2020-01-22 2020-01-29 ``` 2. Not supported: ```Python3 >>> sqlglot.parse_one("SELECT GENERATE_DATE_ARRAY(DATE '2020-01-01', DATE '2020-02-01', INTERVAL 1 WEEK)", read="bigquery").sql("snowflake") "SELECT GENERATE_DATE_ARRAY(CAST('2020-01-01' AS DATE), CAST('2020-02-01' AS DATE), INTERVAL '1 WEEK')" ``` This PR adds support for (2) by reusing (1) and aggregating it into an array, thus producing the following subquery: ```Python3 >>> sqlglot.parse_one("SELECT GENERATE_DATE_ARRAY(DATE '2020-01-01', DATE '2020-02-01', INTERVAL 1 WEEK)", read="bigquery").sql("snowflake") "SELECT (SELECT ARRAY_AGG(*) FROM (SELECT DATEADD(WEEK, CAST(value AS INT), CAST('2020-01-01' AS DATE)) AS value FROM TABLE(FLATTEN(INPUT => ARRAY_GENERATE_RANGE(0, (DATEDIFF(WEEK, CAST('2020-01-01' AS DATE), CAST('2020-02-01' AS DATE)) + 1 - 1) + 1))) AS _u(seq, key, path, index, value, this)))" bigquery> SELECT GENERATE_DATE_ARRAY(DATE '2020-01-01', DATE '2020-02-01', INTERVAL 1 WEEK); f0_ 2020-01-01 2020-01-08 2020-01-15 2020-01-22 2020-01-29 snowflake> SELECT (SELECT ARRAY_AGG(*) FROM (SELECT DATEADD(WEEK, CAST(value AS INT), CAST('2020-01-01' AS DATE)) AS value FROM TABLE(FLATTEN(INPUT => ARRAY_GENERATE_RANGE(0, (DATEDIFF(WEEK, CAST('2020-01-01' AS DATE), CAST('2020-02-01' AS DATE)) + 1 - 1) + 1))) AS _u(seq, key, path, index, value, this))); -- ["2020-01-01", "2020-01-08", "2020-01-15", "2020-01-22", "2020-01-29"] ``` ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in sqlglot/dialects/snowflake.py] (definition of _transform_generate_date_array:) def _transform_generate_date_array(expression: exp.Expression) -> exp.Expression: [end of new definitions in sqlglot/dialects/snowflake.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
ceb42fabad60312699e4b15936aeebac00e22e4d
aws-powertools__powertools-lambda-python-5588
5,588
aws-powertools/powertools-lambda-python
null
3ff5132bdf894fb49da11cfaa7cbff7412d5675c
2024-11-19T12:49:39Z
diff --git a/aws_lambda_powertools/event_handler/appsync.py b/aws_lambda_powertools/event_handler/appsync.py index 6f1cb72d067..3dbbf207859 100644 --- a/aws_lambda_powertools/event_handler/appsync.py +++ b/aws_lambda_powertools/event_handler/appsync.py @@ -53,6 +53,7 @@ def __init__(self): """ super().__init__() self.context = {} # early init as customers might add context before event resolution + self._exception_handlers: dict[type, Callable] = {} def __call__( self, @@ -142,12 +143,18 @@ def lambda_handler(event, context): self.lambda_context = context Router.lambda_context = context - if isinstance(event, list): - Router.current_batch_event = [data_model(e) for e in event] - response = self._call_batch_resolver(event=event, data_model=data_model) - else: - Router.current_event = data_model(event) - response = self._call_single_resolver(event=event, data_model=data_model) + try: + if isinstance(event, list): + Router.current_batch_event = [data_model(e) for e in event] + response = self._call_batch_resolver(event=event, data_model=data_model) + else: + Router.current_event = data_model(event) + response = self._call_single_resolver(event=event, data_model=data_model) + except Exception as exp: + response_builder = self._lookup_exception_handler(type(exp)) + if response_builder: + return response_builder(exp) + raise # We don't clear the context for coroutines because we don't have control over the event loop. # If we clean the context immediately, it might not be available when the coroutine is actually executed. @@ -470,3 +477,47 @@ def async_batch_resolver( raise_on_error=raise_on_error, aggregate=aggregate, ) + + def exception_handler(self, exc_class: type[Exception] | list[type[Exception]]): + """ + A decorator function that registers a handler for one or more exception types. + + Parameters + ---------- + exc_class (type[Exception] | list[type[Exception]]) + A single exception type or a list of exception types. + + Returns + ------- + Callable: + A decorator function that registers the exception handler. + """ + + def register_exception_handler(func: Callable): + if isinstance(exc_class, list): # pragma: no cover + for exp in exc_class: + self._exception_handlers[exp] = func + else: + self._exception_handlers[exc_class] = func + return func + + return register_exception_handler + + def _lookup_exception_handler(self, exp_type: type) -> Callable | None: + """ + Looks up the registered exception handler for the given exception type or its base classes. + + Parameters + ---------- + exp_type (type): + The exception type to look up the handler for. + + Returns + ------- + Callable | None: + The registered exception handler function if found, otherwise None. + """ + for cls in exp_type.__mro__: + if cls in self._exception_handlers: + return self._exception_handlers[cls] + return None diff --git a/aws_lambda_powertools/utilities/data_classes/code_pipeline_job_event.py b/aws_lambda_powertools/utilities/data_classes/code_pipeline_job_event.py index a52e5fbc7a2..3497227ed70 100644 --- a/aws_lambda_powertools/utilities/data_classes/code_pipeline_job_event.py +++ b/aws_lambda_powertools/utilities/data_classes/code_pipeline_job_event.py @@ -311,7 +311,7 @@ def put_artifact(self, artifact_name: str, body: Any, content_type: str) -> None key = artifact.location.s3_location.key # boto3 doesn't support None to omit the parameter when using ServerSideEncryption and SSEKMSKeyId - # So we are using if/else instead. + # So we are using if/else instead. if self.data.encryption_key: diff --git a/docs/core/event_handler/appsync.md b/docs/core/event_handler/appsync.md index a2f29e5dba5..0c556dedfbf 100644 --- a/docs/core/event_handler/appsync.md +++ b/docs/core/event_handler/appsync.md @@ -288,6 +288,19 @@ You can use `append_context` when you want to share data between your App and Ro --8<-- "examples/event_handler_graphql/src/split_operation_append_context_module.py" ``` +### Exception handling + +You can use **`exception_handler`** decorator with any Python exception. This allows you to handle a common exception outside your resolver, for example validation errors. + +The `exception_handler` function also supports passing a list of exception types you wish to handle with one handler. + +```python hl_lines="5-7 11" title="Exception handling" +--8<-- "examples/event_handler_graphql/src/exception_handling_graphql.py" +``` + +???+ warning + This is not supported when using async single resolvers. + ### Batch processing ```mermaid diff --git a/examples/event_handler_graphql/src/exception_handling_graphql.py b/examples/event_handler_graphql/src/exception_handling_graphql.py new file mode 100644 index 00000000000..b135f75112b --- /dev/null +++ b/examples/event_handler_graphql/src/exception_handling_graphql.py @@ -0,0 +1,17 @@ +from aws_lambda_powertools.event_handler import AppSyncResolver + +app = AppSyncResolver() + + +@app.exception_handler(ValueError) +def handle_value_error(ex: ValueError): + return {"message": "error"} + + +@app.resolver(field_name="createSomething") +def create_something(): + raise ValueError("Raising an exception") + + +def lambda_handler(event, context): + return app.resolve(event, context)
diff --git a/tests/functional/event_handler/required_dependencies/appsync/test_appsync_batch_resolvers.py b/tests/functional/event_handler/required_dependencies/appsync/test_appsync_batch_resolvers.py index c594be54a5b..59c5ec08a15 100644 --- a/tests/functional/event_handler/required_dependencies/appsync/test_appsync_batch_resolvers.py +++ b/tests/functional/event_handler/required_dependencies/appsync/test_appsync_batch_resolvers.py @@ -981,3 +981,125 @@ async def get_user(event: List) -> List: # THEN the resolver must be able to return a field in the batch_current_event assert app.context == {} assert ret[0] == "powertools" + + +def test_exception_handler_with_batch_resolver_and_raise_exception(): + + # GIVEN a AppSyncResolver instance + app = AppSyncResolver() + + event = [ + { + "typeName": "Query", + "info": { + "fieldName": "listLocations", + "parentTypeName": "Post", + }, + "fieldName": "listLocations", + "arguments": {}, + "source": { + "id": "1", + }, + }, + { + "typeName": "Query", + "info": { + "fieldName": "listLocations", + "parentTypeName": "Post", + }, + "fieldName": "listLocations", + "arguments": {}, + "source": { + "id": "2", + }, + }, + { + "typeName": "Query", + "info": { + "fieldName": "listLocations", + "parentTypeName": "Post", + }, + "fieldName": "listLocations", + "arguments": {}, + "source": { + "id": [3, 4], + }, + }, + ] + + # WHEN we configure exception handler for ValueError + @app.exception_handler(ValueError) + def handle_value_error(ex: ValueError): + return {"message": "error"} + + # WHEN the sync batch resolver for the 'listLocations' field is defined with raise_on_error=True + @app.batch_resolver(field_name="listLocations", raise_on_error=True, aggregate=False) + def create_something(event: AppSyncResolverEvent) -> Optional[list]: # noqa AA03 VNE003 + raise ValueError + + # Call the implicit handler + result = app(event, {}) + + # THEN the return must be the Exception Handler error message + assert result["message"] == "error" + + +def test_exception_handler_with_batch_resolver_and_no_raise_exception(): + + # GIVEN a AppSyncResolver instance + app = AppSyncResolver() + + event = [ + { + "typeName": "Query", + "info": { + "fieldName": "listLocations", + "parentTypeName": "Post", + }, + "fieldName": "listLocations", + "arguments": {}, + "source": { + "id": "1", + }, + }, + { + "typeName": "Query", + "info": { + "fieldName": "listLocations", + "parentTypeName": "Post", + }, + "fieldName": "listLocations", + "arguments": {}, + "source": { + "id": "2", + }, + }, + { + "typeName": "Query", + "info": { + "fieldName": "listLocations", + "parentTypeName": "Post", + }, + "fieldName": "listLocations", + "arguments": {}, + "source": { + "id": [3, 4], + }, + }, + ] + + # WHEN we configure exception handler for ValueError + @app.exception_handler(ValueError) + def handle_value_error(ex: ValueError): + return {"message": "error"} + + # WHEN the sync batch resolver for the 'listLocations' field is defined with raise_on_error=False + @app.batch_resolver(field_name="listLocations", raise_on_error=False, aggregate=False) + def create_something(event: AppSyncResolverEvent) -> Optional[list]: # noqa AA03 VNE003 + raise ValueError + + # Call the implicit handler + result = app(event, {}) + + # THEN the return must not trigger the Exception Handler, but instead return from the resolver + assert result == [None, None, None] diff --git a/tests/functional/event_handler/required_dependencies/appsync/test_appsync_single_resolvers.py b/tests/functional/event_handler/required_dependencies/appsync/test_appsync_single_resolvers.py index df44793f33b..d58c966e67b 100644 --- a/tests/functional/event_handler/required_dependencies/appsync/test_appsync_single_resolvers.py +++ b/tests/functional/event_handler/required_dependencies/appsync/test_appsync_single_resolvers.py @@ -329,3 +329,25 @@ async def get_async(): # THEN assert asyncio.run(result) == "value" assert app.context == {} + + +def test_exception_handler_with_single_resolver(): + # GIVEN a AppSyncResolver instance + mock_event = load_event("appSyncDirectResolver.json") + + app = AppSyncResolver() + + # WHEN we configure exception handler for ValueError + @app.exception_handler(ValueError) + def handle_value_error(ex: ValueError): + return {"message": "error"} + + @app.resolver(field_name="createSomething") + def create_something(id: str): # noqa AA03 VNE003 + raise ValueError("Error") + + # Call the implicit handler + result = app(mock_event, {}) + + # THEN the return must be the Exception Handler error message + assert result["message"] == "error"
diff --git a/docs/core/event_handler/appsync.md b/docs/core/event_handler/appsync.md index a2f29e5dba5..0c556dedfbf 100644 --- a/docs/core/event_handler/appsync.md +++ b/docs/core/event_handler/appsync.md @@ -288,6 +288,19 @@ You can use `append_context` when you want to share data between your App and Ro --8<-- "examples/event_handler_graphql/src/split_operation_append_context_module.py" ``` +### Exception handling + +You can use **`exception_handler`** decorator with any Python exception. This allows you to handle a common exception outside your resolver, for example validation errors. + +The `exception_handler` function also supports passing a list of exception types you wish to handle with one handler. + +```python hl_lines="5-7 11" title="Exception handling" +--8<-- "examples/event_handler_graphql/src/exception_handling_graphql.py" +``` + +???+ warning + This is not supported when using async single resolvers. + ### Batch processing ```mermaid
[ { "components": [ { "doc": "A decorator function that registers a handler for one or more exception types.\n\nParameters\n----------\nexc_class (type[Exception] | list[type[Exception]])\n A single exception type or a list of exception types.\n\nReturns\n-------\nCallable:\n A decorator function that registers the exception handler.", "lines": [ 481, 504 ], "name": "AppSyncResolver.exception_handler", "signature": "def exception_handler(self, exc_class: type[Exception] | list[type[Exception]]):", "type": "function" }, { "doc": "", "lines": [ 496, 502 ], "name": "AppSyncResolver.exception_handler.register_exception_handler", "signature": "def register_exception_handler(func: Callable):", "type": "function" }, { "doc": "Looks up the registered exception handler for the given exception type or its base classes.\n\nParameters\n----------\nexp_type (type):\n The exception type to look up the handler for.\n\nReturns\n-------\nCallable | None:\n The registered exception handler function if found, otherwise None.", "lines": [ 506, 523 ], "name": "AppSyncResolver._lookup_exception_handler", "signature": "def _lookup_exception_handler(self, exp_type: type) -> Callable | None:", "type": "function" } ], "file": "aws_lambda_powertools/event_handler/appsync.py" }, { "components": [ { "doc": "", "lines": [ 7, 8 ], "name": "handle_value_error", "signature": "def handle_value_error(ex: ValueError):", "type": "function" }, { "doc": "", "lines": [ 12, 13 ], "name": "create_something", "signature": "def create_something():", "type": "function" }, { "doc": "", "lines": [ 16, 17 ], "name": "lambda_handler", "signature": "def lambda_handler(event, context):", "type": "function" } ], "file": "examples/event_handler_graphql/src/exception_handling_graphql.py" } ]
[ "tests/functional/event_handler/required_dependencies/appsync/test_appsync_batch_resolvers.py::test_exception_handler_with_batch_resolver_and_raise_exception", "tests/functional/event_handler/required_dependencies/appsync/test_appsync_batch_resolvers.py::test_exception_handler_with_batch_resolver_and_no_raise_exception", "tests/functional/event_handler/required_dependencies/appsync/test_appsync_single_resolvers.py::test_exception_handler_with_single_resolver" ]
[ "tests/functional/event_handler/required_dependencies/appsync/test_appsync_batch_resolvers.py::test_resolve_batch_processing_with_related_events_one_at_time", "tests/functional/event_handler/required_dependencies/appsync/test_appsync_batch_resolvers.py::test_resolve_batch_processing_with_simple_queries_one_at_time", "tests/functional/event_handler/required_dependencies/appsync/test_appsync_batch_resolvers.py::test_resolve_batch_processing_with_raise_on_exception_one_at_time", "tests/functional/event_handler/required_dependencies/appsync/test_appsync_batch_resolvers.py::test_async_resolve_batch_processing_with_raise_on_exception_one_at_time", "tests/functional/event_handler/required_dependencies/appsync/test_appsync_batch_resolvers.py::test_resolve_batch_processing_without_exception_one_at_time", "tests/functional/event_handler/required_dependencies/appsync/test_appsync_batch_resolvers.py::test_resolve_async_batch_processing_without_exception_one_at_time", "tests/functional/event_handler/required_dependencies/appsync/test_appsync_batch_resolvers.py::test_resolver_batch_with_resolver_not_found_one_at_time", "tests/functional/event_handler/required_dependencies/appsync/test_appsync_batch_resolvers.py::test_resolver_batch_with_sync_and_async_resolver_at_same_time", "tests/functional/event_handler/required_dependencies/appsync/test_appsync_batch_resolvers.py::test_batch_resolver_with_router", "tests/functional/event_handler/required_dependencies/appsync/test_appsync_batch_resolvers.py::test_resolve_async_batch_processing", "tests/functional/event_handler/required_dependencies/appsync/test_appsync_batch_resolvers.py::test_resolve_async_batch_and_sync_singular_processing", "tests/functional/event_handler/required_dependencies/appsync/test_appsync_batch_resolvers.py::test_async_resolver_include_batch_resolver", "tests/functional/event_handler/required_dependencies/appsync/test_appsync_batch_resolvers.py::test_resolve_batch_processing_with_simple_queries_with_aggregate", "tests/functional/event_handler/required_dependencies/appsync/test_appsync_batch_resolvers.py::test_resolve_async_batch_processing_with_simple_queries_with_aggregate", "tests/functional/event_handler/required_dependencies/appsync/test_appsync_batch_resolvers.py::test_resolve_batch_processing_with_aggregate_and_returning_a_non_list", "tests/functional/event_handler/required_dependencies/appsync/test_appsync_batch_resolvers.py::test_resolve_async_batch_processing_with_aggregate_and_returning_a_non_list", "tests/functional/event_handler/required_dependencies/appsync/test_appsync_batch_resolvers.py::test_resolve_sync_batch_processing_with_aggregate_and_without_return", "tests/functional/event_handler/required_dependencies/appsync/test_appsync_batch_resolvers.py::test_resolve_async_batch_processing_with_aggregate_and_without_return", "tests/functional/event_handler/required_dependencies/appsync/test_appsync_batch_resolvers.py::test_include_router_access_batch_current_event", "tests/functional/event_handler/required_dependencies/appsync/test_appsync_batch_resolvers.py::test_app_access_batch_current_event", "tests/functional/event_handler/required_dependencies/appsync/test_appsync_batch_resolvers.py::test_context_is_accessible_in_sync_batch_resolver", "tests/functional/event_handler/required_dependencies/appsync/test_appsync_batch_resolvers.py::test_context_is_accessible_in_async_batch_resolver", "tests/functional/event_handler/required_dependencies/appsync/test_appsync_single_resolvers.py::test_direct_resolver", "tests/functional/event_handler/required_dependencies/appsync/test_appsync_single_resolvers.py::test_amplify_resolver", "tests/functional/event_handler/required_dependencies/appsync/test_appsync_single_resolvers.py::test_resolver_no_params", "tests/functional/event_handler/required_dependencies/appsync/test_appsync_single_resolvers.py::test_resolver_value_error", "tests/functional/event_handler/required_dependencies/appsync/test_appsync_single_resolvers.py::test_resolver_yield", "tests/functional/event_handler/required_dependencies/appsync/test_appsync_single_resolvers.py::test_resolver_multiple_mappings", "tests/functional/event_handler/required_dependencies/appsync/test_appsync_single_resolvers.py::test_resolver_async", "tests/functional/event_handler/required_dependencies/appsync/test_appsync_single_resolvers.py::test_resolve_custom_data_model", "tests/functional/event_handler/required_dependencies/appsync/test_appsync_single_resolvers.py::test_resolver_include_resolver", "tests/functional/event_handler/required_dependencies/appsync/test_appsync_single_resolvers.py::test_append_context", "tests/functional/event_handler/required_dependencies/appsync/test_appsync_single_resolvers.py::test_router_append_context", "tests/functional/event_handler/required_dependencies/appsync/test_appsync_single_resolvers.py::test_route_context_is_cleared_after_resolve", "tests/functional/event_handler/required_dependencies/appsync/test_appsync_single_resolvers.py::test_router_has_access_to_app_context", "tests/functional/event_handler/required_dependencies/appsync/test_appsync_single_resolvers.py::test_include_router_merges_context", "tests/functional/event_handler/required_dependencies/appsync/test_appsync_single_resolvers.py::test_include_router_access_current_event", "tests/functional/event_handler/required_dependencies/appsync/test_appsync_single_resolvers.py::test_app_access_current_event", "tests/functional/event_handler/required_dependencies/appsync/test_appsync_single_resolvers.py::test_route_context_is_not_cleared_after_resolve_async", "tests/functional/event_handler/required_dependencies/appsync/test_appsync_single_resolvers.py::test_route_context_is_manually_cleared_after_resolve_async" ]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> feat(event_handler): add exception handling mechanism for AppSyncResolver <!-- markdownlint-disable MD041 MD043 --> **Issue number:** #2184 ## Summary ### Changes This PR introduces a new feature to handle exceptions in `AppSyncResolver` using a standard error handling mechanism, similar to the one used for HTTP Resolvers. Currently, there is no built-in support for exception handling in `AppSyncResolver`, and this PR aims to address that gap. **Changes** 1. **Added exception catching function**: A new decorator `@app.exception_handler` has been implemented to catch and handle exceptions raised during the execution of AppSync resolvers. This decorator allows developers to define custom error handling logic based on the type of exception raised. 2. **Added tests**: Test cases have been added to ensure the proper functioning of the exception handling mechanism and to maintain code quality. 3. **Added documentation**: The usage and implementation details of the `@app.exception_handler` decorator have been documented to provide guidance for developers who wish to utilize this new feature. **Note** It's important to note that this exception handling mechanism is not supported when using single async resolvers. ### User experience ```python from aws_lambda_powertools.event_handler import AppSyncResolver app = AppSyncResolver() @app.exception_handler(ValueError) def handle_value_error(ex: ValueError): return {"message": "error"} @app.resolver(field_name="createSomething") def create_something(id: str): raise ValueError("Error") def lambda_handler(event, context): return app.resolve(event, context) ``` ## Checklist If your change doesn't seem to apply, please leave them unchecked. * [x] [Meet tenets criteria](https://docs.powertools.aws.dev/lambda/python/#tenets) * [x] I have performed a self-review of this change * [x] Changes have been tested * [x] Changes are documented * [x] PR title follows [conventional commit semantics](https://github.com/aws-powertools/powertools-lambda-python/blob/develop/.github/semantic.yml) <details> <summary>Is this a breaking change?</summary> **RFC issue number**: Checklist: * [ ] Migration process documented * [ ] Implement warnings (if it can live side by side) </details> ## Acknowledgment By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice. **Disclaimer**: We value your time and bandwidth. As such, any pull requests created on non-triaged issues might not be successful. ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in aws_lambda_powertools/event_handler/appsync.py] (definition of AppSyncResolver.exception_handler:) def exception_handler(self, exc_class: type[Exception] | list[type[Exception]]): """A decorator function that registers a handler for one or more exception types. Parameters ---------- exc_class (type[Exception] | list[type[Exception]]) A single exception type or a list of exception types. Returns ------- Callable: A decorator function that registers the exception handler.""" (definition of AppSyncResolver.exception_handler.register_exception_handler:) def register_exception_handler(func: Callable): (definition of AppSyncResolver._lookup_exception_handler:) def _lookup_exception_handler(self, exp_type: type) -> Callable | None: """Looks up the registered exception handler for the given exception type or its base classes. Parameters ---------- exp_type (type): The exception type to look up the handler for. Returns ------- Callable | None: The registered exception handler function if found, otherwise None.""" [end of new definitions in aws_lambda_powertools/event_handler/appsync.py] [start of new definitions in examples/event_handler_graphql/src/exception_handling_graphql.py] (definition of handle_value_error:) def handle_value_error(ex: ValueError): (definition of create_something:) def create_something(): (definition of lambda_handler:) def lambda_handler(event, context): [end of new definitions in examples/event_handler_graphql/src/exception_handling_graphql.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
d1a58cdd12dfcac1e9ce022fe8a29f69ea6007b4
fairlearn__fairlearn-1436
1,436
fairlearn/fairlearn
null
403da1fec74bdf2da28dc49487ccd72caa6f6976
2024-11-10T17:43:48Z
diff --git a/fairlearn/metrics/_disaggregated_result.py b/fairlearn/metrics/_disaggregated_result.py index cab28bf04..b78f0ca51 100644 --- a/fairlearn/metrics/_disaggregated_result.py +++ b/fairlearn/metrics/_disaggregated_result.py @@ -2,6 +2,8 @@ # Licensed under the MIT License. from __future__ import annotations +from __future__ import annotations + import logging from typing import Literal @@ -27,14 +29,6 @@ ) -def extract_unique_classes(data: pd.DataFrame, feature_list: list[str]) -> dict[str, np.ndarray]: - """Compute unique values in a given set of columns.""" - result = dict() - for feature in feature_list: - result[feature] = np.unique(data[feature]) - return result - - def apply_to_dataframe( data: pd.DataFrame, metric_functions: dict[str, AnnotatedMetricFunction], @@ -134,48 +128,31 @@ def apply_grouping( if not control_feature_names: if errors == "raise": try: - mf = self.by_group - if grouping_function == "min": - vals = [mf[m].min() for m in mf.columns] - else: - vals = [mf[m].max() for m in mf.columns] - - result = pd.Series(vals, index=self.by_group.columns) + result = self.by_group.agg(grouping_function, axis=0) except ValueError as ve: raise ValueError(_MF_CONTAINS_NON_SCALAR_ERROR_MESSAGE) from ve + elif errors == "coerce": - if not control_feature_names: - mf = self.by_group - # Fill in the possible min/max values, else np.nan - if grouping_function == "min": - vals = [ - mf[m].min() if np.isscalar(mf[m].values[0]) else np.nan - for m in mf.columns - ] - else: - vals = [ - mf[m].max() if np.isscalar(mf[m].values[0]) else np.nan - for m in mf.columns - ] - - result = pd.Series(vals, index=mf.columns) + # Fill in the possible min/max values, else np.nan + mf = self.by_group.apply( + lambda x: x.apply(lambda y: y if np.isscalar(y) else np.nan) + ) + result = mf.agg(grouping_function, axis=0) else: if errors == "raise": try: - if grouping_function == "min": - result = self.by_group.groupby(level=control_feature_names).min() - else: - result = self.by_group.groupby(level=control_feature_names).max() + result = self.by_group.groupby(level=control_feature_names).agg( + grouping_function + ) + except ValueError as ve: raise ValueError(_MF_CONTAINS_NON_SCALAR_ERROR_MESSAGE) from ve elif errors == "coerce": # Fill all impossible columns with NaN before grouping metric frame - mf = self.by_group.copy() - mf = mf.apply(lambda x: x.apply(lambda y: y if np.isscalar(y) else np.nan)) - if grouping_function == "min": - result = mf.groupby(level=control_feature_names).min() - else: - result = mf.groupby(level=control_feature_names).max() + mf = self.by_group.apply( + lambda x: x.apply(lambda y: y if np.isscalar(y) else np.nan) + ) + result = mf.groupby(level=control_feature_names).agg(grouping_function) assert isinstance(result, pd.Series) or isinstance(result, pd.DataFrame) @@ -227,10 +204,9 @@ def difference( else: raise ValueError("Unrecognised method '{0}' in difference() call".format(method)) - mf = self.by_group.copy() # Can assume errors='coerce', else error would already have been raised in .group_min # Fill all non-scalar values with NaN - mf = mf.apply(lambda x: x.apply(lambda y: y if np.isscalar(y) else np.nan)) + mf = self.by_group.apply(lambda x: x.apply(lambda y: y if np.isscalar(y) else np.nan)) if control_feature_names is None: result = (mf - subtrahend).abs().max() @@ -289,7 +265,6 @@ def ratio_sub_one(x): if errors not in _VALID_ERROR_STRING: raise ValueError(_INVALID_ERRORS_VALUE_ERROR_MESSAGE) - result = None if method == "between_groups": result = self.apply_grouping( "min", control_feature_names, errors=errors @@ -357,49 +332,61 @@ def create( DisaggregatedResult Freshly constructed instance of this class """ - # Calculate the 'overall' values - if control_feature_names is None: - overall = apply_to_dataframe(data, metric_functions=annotated_functions) - else: - temp = data.groupby(by=control_feature_names).apply( - apply_to_dataframe, - metric_functions=annotated_functions, - # See note in apply_to_dataframe about include_groups - include_groups=False, - ) - # If there are multiple control features, might have missing combinations - if len(control_feature_names) > 1: - cf_classes = extract_unique_classes(data, control_feature_names) - all_indices = pd.MultiIndex.from_product( - cf_classes.values(), names=cf_classes.keys() - ) + overall = DisaggregatedResult._apply_functions( + data=data, + annotated_functions=annotated_functions, + grouping_names=control_feature_names, + ) - overall = temp.reindex(index=all_indices) - else: - overall = temp + by_group = DisaggregatedResult._apply_functions( + data=data, + annotated_functions=annotated_functions, + grouping_names=(control_feature_names or []) + sensitive_feature_names, + ) + + return DisaggregatedResult(overall, by_group) + + @staticmethod + def _apply_functions( + *, + data: pd.DataFrame, + annotated_functions: dict[str, AnnotatedMetricFunction], + grouping_names: list[str] | None, + ) -> pd.Series | pd.DataFrame: + """ + Apply annotated metric functions to a DataFrame, optionally grouping by specified columns. + + Parameters + ---------- + data : pd.DataFrame + The input data on which the metric functions will be applied. + annotated_functions : dict[str, AnnotatedMetricFunction] + A dictionary where keys are metric names and values are the corresponding annotated metric + functions. + grouping_names : list[str] | None + A list of column names to group by before applying the metric functions. If None, the + functions are applied to the entire DataFrame. - # Calculate the 'by_group' values - all_grouping_names = [x for x in sensitive_feature_names] - if control_feature_names is not None: - # Note that we prepend the control feature names - all_grouping_names = control_feature_names + all_grouping_names + Returns + ------- + Series or DataFrame + A Series or DataFrame with the results of the metric functions applied. If grouping_names is provided, + the results are grouped accordingly. + """ + if grouping_names is None or len(grouping_names) == 0: + return apply_to_dataframe(data, metric_functions=annotated_functions) - temp = data.groupby(all_grouping_names).apply( + temp = data.groupby(grouping_names).apply( apply_to_dataframe, metric_functions=annotated_functions, - # See note in apply_to_dataframe about include_groups include_groups=False, ) - if len(all_grouping_names) > 1: - # We might have missing combinations in the input, so expand to fill - all_classes = extract_unique_classes(data, all_grouping_names) + + if len(grouping_names) > 1: all_indices = pd.MultiIndex.from_product( - all_classes.values(), - names=all_classes.keys(), + [np.unique(data[col]) for col in grouping_names], names=grouping_names ) - by_group = temp.reindex(index=all_indices) - else: - by_group = temp + return temp.reindex(index=all_indices) - return DisaggregatedResult(overall, by_group) + return temp
diff --git a/test/unit/metrics/test_disaggregated_result.py b/test/unit/metrics/test_disaggregated_result.py index 7c1486f72..1969f95cb 100644 --- a/test/unit/metrics/test_disaggregated_result.py +++ b/test/unit/metrics/test_disaggregated_result.py @@ -1,11 +1,13 @@ # Copyright (c) Microsoft Corporation and Fairlearn contributors. # Licensed under the MIT License. + import pandas as pd import pytest import sklearn.metrics as skm from fairlearn.metrics._annotated_metric_function import AnnotatedMetricFunction +from fairlearn.metrics._base_metrics import selection_rate from fairlearn.metrics._disaggregated_result import DisaggregatedResult from .data_for_test import g_1, y_p, y_t @@ -89,3 +91,77 @@ def test_bad_ratio_errors(self): assert ( str(e0.value) == "Invalid error value specified. Valid values are ['raise', 'coerce']" ) + + +@pytest.mark.parametrize( + ["grouping_names", "expected"], + [(None, pd.Series({"selection_rate": 0.5})), ([], pd.Series({"selection_rate": 0.5}))], +) +def test_apply_functions_with_no_grouping(grouping_names, expected): + data = pd.DataFrame( + { + "y_pred": [1, 0, 1, 0, 0, 1], + "y_true": [1, 1, 0, 1, 0, 0], + "sensitive_feature": ["A", "A", "A", "B", "B", "B"], + } + ) + + annotated_functions = { + "selection_rate": AnnotatedMetricFunction(func=selection_rate, name="selection_rate") + } + + result = DisaggregatedResult._apply_functions( + data=data, annotated_functions=annotated_functions, grouping_names=grouping_names + ) + + pd.testing.assert_series_equal(result, expected) + + +@pytest.mark.parametrize( + ["grouping_names", "expected"], + [ + ( + ["sensitive_feature"], + pd.DataFrame( + {"selection_rate": [2 / 3, 1 / 3]}, + index=pd.Index(["A", "B"], name="sensitive_feature"), + ), + ), + ( + ["control_feature_1"], + pd.DataFrame( + {"selection_rate": [1 / 3, 2 / 3]}, + index=pd.Index(["X", "Y"], name="control_feature_1"), + ), + ), + ( + ["control_feature_2", "sensitive_feature"], + pd.DataFrame( + {"selection_rate": [1.0, None, 0.5, 1 / 3]}, + index=pd.MultiIndex.from_product( + [("W", "Z"), ("A", "B")], names=["control_feature_2", "sensitive_feature"] + ), + ), + ), + ], +) +def test_apply_functions_with_grouping(grouping_names, expected): + data = pd.DataFrame( + { + "y_pred": [1, 0, 1, 0, 0, 1], + "y_true": [1, 1, 0, 1, 0, 0], + "sensitive_feature": ["A", "A", "A", "B", "B", "B"], + "control_feature_1": ["X", "X", "Y", "Y", "X", "Y"], + "control_feature_2": ["Z", "Z", "W", "Z", "Z", "Z"], + } + ) + + annotated_functions = { + "selection_rate": AnnotatedMetricFunction(func=selection_rate, name="selection_rate") + } + + result = DisaggregatedResult._apply_functions( + data=data, annotated_functions=annotated_functions, grouping_names=grouping_names + ) + + pd.testing.assert_frame_equal(result, expected)
[ { "components": [ { "doc": "Apply annotated metric functions to a DataFrame, optionally grouping by specified columns.\n\nParameters\n----------\ndata : pd.DataFrame\n The input data on which the metric functions will be applied.\nannotated_functions : dict[str, AnnotatedMetricFunction]\n A dictionary where keys are metric names and values are the corresponding annotated metric\n functions.\ngrouping_names : list[str] | None\n A list of column names to group by before applying the metric functions. If None, the\n functions are applied to the entire DataFrame.\n\nReturns\n-------\nSeries or DataFrame\n A Series or DataFrame with the results of the metric functions applied. If grouping_names is provided,\n the results are grouped accordingly.", "lines": [ 350, 392 ], "name": "DisaggregatedResult._apply_functions", "signature": "def _apply_functions( *, data: pd.DataFrame, annotated_functions: dict[str, AnnotatedMetricFunction], grouping_names: list[str] | None, ) -> pd.Series | pd.DataFrame:", "type": "function" } ], "file": "fairlearn/metrics/_disaggregated_result.py" } ]
[ "test/unit/metrics/test_disaggregated_result.py::test_apply_functions_with_no_grouping[None-expected0]", "test/unit/metrics/test_disaggregated_result.py::test_apply_functions_with_no_grouping[grouping_names1-expected1]", "test/unit/metrics/test_disaggregated_result.py::test_apply_functions_with_grouping[grouping_names0-expected0]", "test/unit/metrics/test_disaggregated_result.py::test_apply_functions_with_grouping[grouping_names1-expected1]", "test/unit/metrics/test_disaggregated_result.py::test_apply_functions_with_grouping[grouping_names2-expected2]" ]
[ "test/unit/metrics/test_disaggregated_result.py::TestErrorMessages::test_bad_grouping", "test/unit/metrics/test_disaggregated_result.py::TestErrorMessages::test_bad_difference_method", "test/unit/metrics/test_disaggregated_result.py::TestErrorMessages::test_bad_difference_errors", "test/unit/metrics/test_disaggregated_result.py::TestErrorMessages::test_bad_ratio_method", "test/unit/metrics/test_disaggregated_result.py::TestErrorMessages::test_bad_ratio_errors" ]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> refactor: simplify disaggregated result ## Description - Simplified code complexity by using pandas built-in methods. - Refactored the common logic in initializing the `overall` and `by_group` inside `.create`. - Added unit tests to cover the latter. There are some linting changes to the doc that could be merged as part of this [other PR](https://github.com/fairlearn/fairlearn/pull/1434) ## Tests <!--- Select all that apply by putting an x between the brackets: [x] --> - [ ] no new tests required - [x] new tests added - [ ] existing tests adjusted ## Documentation <!--- Select all that apply. --> - [ ] no documentation changes needed - [x] user guide added or updated - [x] API docs added or updated - [ ] example notebook added or updated ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in fairlearn/metrics/_disaggregated_result.py] (definition of DisaggregatedResult._apply_functions:) def _apply_functions( *, data: pd.DataFrame, annotated_functions: dict[str, AnnotatedMetricFunction], grouping_names: list[str] | None, ) -> pd.Series | pd.DataFrame: """Apply annotated metric functions to a DataFrame, optionally grouping by specified columns. Parameters ---------- data : pd.DataFrame The input data on which the metric functions will be applied. annotated_functions : dict[str, AnnotatedMetricFunction] A dictionary where keys are metric names and values are the corresponding annotated metric functions. grouping_names : list[str] | None A list of column names to group by before applying the metric functions. If None, the functions are applied to the entire DataFrame. Returns ------- Series or DataFrame A Series or DataFrame with the results of the metric functions applied. If grouping_names is provided, the results are grouped accordingly.""" [end of new definitions in fairlearn/metrics/_disaggregated_result.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
403da1fec74bdf2da28dc49487ccd72caa6f6976
rytilahti__python-miio-1984
1,984
rytilahti/python-miio
null
62427d2f796e603520acca3b57b29ec3e6489bca
2024-11-09T21:09:56Z
diff --git a/miio/miot_models.py b/miio/miot_models.py index 1269946d5..6f4abfe59 100644 --- a/miio/miot_models.py +++ b/miio/miot_models.py @@ -1,4 +1,5 @@ import logging +from abc import abstractmethod from datetime import timedelta from enum import Enum from typing import Any, Optional @@ -150,6 +151,11 @@ def normalized_name(self) -> str: """ return self.name.replace(":", "_").replace("-", "_") + @property + @abstractmethod + def unique_identifier(self) -> str: + """Return unique identifier.""" + class MiotAction(MiotBaseModel): """Action presentation for miot.""" @@ -176,8 +182,6 @@ def fill_from_parent(self, service: "MiotService"): def get_descriptor(self): """Create a descriptor based on the property information.""" - id_ = self.name - extras = self.extras extras["urn"] = self.urn extras["siid"] = self.siid @@ -190,12 +194,17 @@ def get_descriptor(self): inputs = [prop.get_descriptor() for prop in self.inputs] return ActionDescriptor( - id=id_, + id=self.unique_identifier, name=self.description, inputs=inputs, extras=extras, ) + @property + def unique_identifier(self) -> str: + """Return unique identifier.""" + return f"{self.normalized_name}_{self.siid}_{self.aiid}" + class Config: extra = "forbid" @@ -327,7 +336,7 @@ def _create_enum_descriptor(self) -> EnumDescriptor: raise desc = EnumDescriptor( - id=self.name, + id=self.unique_identifier, name=self.description, status_attribute=self.normalized_name, unit=self.unit, @@ -346,7 +355,7 @@ def _create_range_descriptor( if self.range is None: raise ValueError("Range is None") desc = RangeDescriptor( - id=self.name, + id=self.unique_identifier, name=self.description, status_attribute=self.normalized_name, min_value=self.range[0], @@ -363,7 +372,7 @@ def _create_range_descriptor( def _create_regular_descriptor(self) -> PropertyDescriptor: """Create boolean setting descriptor.""" return PropertyDescriptor( - id=self.name, + id=self.unique_identifier, name=self.description, status_attribute=self.normalized_name, type=self.format, @@ -371,6 +380,11 @@ def _create_regular_descriptor(self) -> PropertyDescriptor: access=self._miot_access_list_to_access(self.access), ) + @property + def unique_identifier(self) -> str: + """Return unique identifier.""" + return f"{self.normalized_name}_{self.siid}_{self.piid}" + class Config: extra = "forbid" @@ -381,6 +395,11 @@ class MiotEvent(MiotBaseModel): eiid: int = Field(alias="iid") arguments: Any + @property + def unique_identifier(self) -> str: + """Return unique identifier.""" + return f"{self.normalized_name}_{self.siid}_{self.eiid}" + class Config: extra = "forbid"
diff --git a/miio/tests/test_miot_models.py b/miio/tests/test_miot_models.py index 32afb76aa..046ad2a08 100644 --- a/miio/tests/test_miot_models.py +++ b/miio/tests/test_miot_models.py @@ -21,6 +21,7 @@ URN, MiotAccess, MiotAction, + MiotBaseModel, MiotEnumValue, MiotEvent, MiotFormat, @@ -349,3 +350,18 @@ def test_get_descriptor_enum_property(read_only, expected): def test_property_pretty_value(): """Test the pretty value conversions.""" raise NotImplementedError() + + +@pytest.mark.parametrize( + ("collection", "id_var"), + [("actions", "aiid"), ("properties", "piid"), ("events", "eiid")], +) +def test_unique_identifier(collection, id_var): + """Test unique identifier for properties, actions, and events.""" + serv = MiotService.parse_raw(DUMMY_SERVICE) + elem: MiotBaseModel = getattr(serv, collection) + first = elem[0] + assert ( + first.unique_identifier + == f"{first.normalized_name}_{serv.siid}_{getattr(first, id_var)}" + )
[ { "components": [ { "doc": "Return unique identifier.", "lines": [ 156, 157 ], "name": "MiotBaseModel.unique_identifier", "signature": "def unique_identifier(self) -> str:", "type": "function" }, { "doc": "Return unique identifier.", "lines": [ 204, 206 ], "name": "MiotAction.unique_identifier", "signature": "def unique_identifier(self) -> str:", "type": "function" }, { "doc": "Return unique identifier.", "lines": [ 384, 386 ], "name": "MiotProperty.unique_identifier", "signature": "def unique_identifier(self) -> str:", "type": "function" }, { "doc": "Return unique identifier.", "lines": [ 399, 401 ], "name": "MiotEvent.unique_identifier", "signature": "def unique_identifier(self) -> str:", "type": "function" } ], "file": "miio/miot_models.py" } ]
[ "miio/tests/test_miot_models.py::test_unique_identifier[actions-aiid]", "miio/tests/test_miot_models.py::test_unique_identifier[properties-piid]", "miio/tests/test_miot_models.py::test_unique_identifier[events-eiid]" ]
[ "miio/tests/test_miot_models.py::test_enum", "miio/tests/test_miot_models.py::test_enum_missing_description", "miio/tests/test_miot_models.py::test_format[bool-bool]", "miio/tests/test_miot_models.py::test_format[string-str]", "miio/tests/test_miot_models.py::test_format[float-float]", "miio/tests/test_miot_models.py::test_format[uint8-int]", "miio/tests/test_miot_models.py::test_format[uint16-int]", "miio/tests/test_miot_models.py::test_format[uint32-int]", "miio/tests/test_miot_models.py::test_format[int8-int]", "miio/tests/test_miot_models.py::test_format[int16-int]", "miio/tests/test_miot_models.py::test_format[int32-int]", "miio/tests/test_miot_models.py::test_action", "miio/tests/test_miot_models.py::test_action_with_nulls", "miio/tests/test_miot_models.py::test_urn[regular_urn]", "miio/tests/test_miot_models.py::test_urn[unexpected_component]", "miio/tests/test_miot_models.py::test_urn[multiple_unexpected_components]", "miio/tests/test_miot_models.py::test_service", "miio/tests/test_miot_models.py::test_service_back_references[actions]", "miio/tests/test_miot_models.py::test_service_back_references[properties]", "miio/tests/test_miot_models.py::test_service_back_references[events]", "miio/tests/test_miot_models.py::test_entity_names[actions]", "miio/tests/test_miot_models.py::test_entity_names[properties]", "miio/tests/test_miot_models.py::test_entity_names[events]", "miio/tests/test_miot_models.py::test_event", "miio/tests/test_miot_models.py::test_property", "miio/tests/test_miot_models.py::test_get_descriptor_bool_property[True-r--]", "miio/tests/test_miot_models.py::test_get_descriptor_bool_property[False-rw-]", "miio/tests/test_miot_models.py::test_get_descriptor_ranged_property[True-PropertyDescriptor]", "miio/tests/test_miot_models.py::test_get_descriptor_ranged_property[False-RangeDescriptor]", "miio/tests/test_miot_models.py::test_get_descriptor_enum_property[True-PropertyDescriptor]", "miio/tests/test_miot_models.py::test_get_descriptor_enum_property[False-EnumDescriptor]" ]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> Add unique_identifier property to miot properties, actions, and events This allows descriptors to have device-unique identifiers, the format is '<normalized_name>_<siid>_<id>'. This also changes 'id' of the descriptors to use this identifier in-place of a plain name from the description. ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in miio/miot_models.py] (definition of MiotBaseModel.unique_identifier:) def unique_identifier(self) -> str: """Return unique identifier.""" (definition of MiotAction.unique_identifier:) def unique_identifier(self) -> str: """Return unique identifier.""" (definition of MiotProperty.unique_identifier:) def unique_identifier(self) -> str: """Return unique identifier.""" (definition of MiotEvent.unique_identifier:) def unique_identifier(self) -> str: """Return unique identifier.""" [end of new definitions in miio/miot_models.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
62427d2f796e603520acca3b57b29ec3e6489bca
tobymao__sqlglot-4249
4,249
tobymao/sqlglot
null
fcc05c9daa31c7a51474ec9c72ceafd682359f90
2024-10-15T19:16:53Z
diff --git a/sqlglot/dialects/oracle.py b/sqlglot/dialects/oracle.py index 81c2a4a5c3..0845258f36 100644 --- a/sqlglot/dialects/oracle.py +++ b/sqlglot/dialects/oracle.py @@ -15,6 +15,7 @@ from sqlglot.helper import seq_get from sqlglot.parser import OPTIONS_TYPE, build_coalesce from sqlglot.tokens import TokenType +from sqlglot.errors import ParseError if t.TYPE_CHECKING: from sqlglot._typing import E @@ -205,6 +206,57 @@ def _parse_json_array(self, expr_type: t.Type[E], **kwargs) -> E: ) def _parse_hint(self) -> t.Optional[exp.Hint]: + start_index = self._index + should_fallback_to_string = False + + if not self._match(TokenType.HINT): + return None + + hints = [] + + try: + for hint in iter( + lambda: self._parse_csv( + lambda: self._parse_hint_function_call() or self._parse_var(upper=True), + ), + [], + ): + hints.extend(hint) + except ParseError: + should_fallback_to_string = True + + if not self._match_pair(TokenType.STAR, TokenType.SLASH): + should_fallback_to_string = True + + if should_fallback_to_string: + self._retreat(start_index) + return self._parse_hint_fallback_to_string() + + return self.expression(exp.Hint, expressions=hints) + + def _parse_hint_function_call(self) -> t.Optional[exp.Expression]: + if not self._curr or not self._next or self._next.token_type != TokenType.L_PAREN: + return None + + this = self._curr.text + + self._advance(2) + args = self._parse_hint_args() + this = self.expression(exp.Anonymous, this=this, expressions=args) + self._match_r_paren(this) + return this + + def _parse_hint_args(self): + args = [] + result = self._parse_var() + + while result: + args.append(result) + result = self._parse_var() + + return args + + def _parse_hint_fallback_to_string(self) -> t.Optional[exp.Hint]: if self._match(TokenType.HINT): start = self._curr while self._curr and not self._match_pair(TokenType.STAR, TokenType.SLASH): @@ -271,6 +323,7 @@ class Generator(generator.Generator): LAST_DAY_SUPPORTS_DATE_PART = False SUPPORTS_SELECT_INTO = True TZ_TO_WITH_TIME_ZONE = True + QUERY_HINT_SEP = " " TYPE_MAPPING = { **generator.Generator.TYPE_MAPPING, @@ -370,3 +423,23 @@ def into_sql(self, expression: exp.Into) -> str: return f"{self.seg(into)} {self.sql(expression, 'this')}" return f"{self.seg(into)} {self.expressions(expression)}" + + def hint_sql(self, expression: exp.Hint) -> str: + expressions = [] + + for expression in expression.expressions: + if isinstance(expression, exp.Anonymous): + formatted_args = self._format_hint_function_args(*expression.expressions) + expressions.append(f"{self.sql(expression, 'this')}({formatted_args})") + else: + expressions.append(self.sql(expression)) + + return f" /*+ {self.expressions(sqls=expressions, sep=self.QUERY_HINT_SEP).strip()} */" + + def _format_hint_function_args(self, *args: t.Optional[str | exp.Expression]) -> str: + arg_sqls = tuple(self.sql(arg) for arg in args) + if self.pretty and self.too_wide(arg_sqls): + return self.indent( + "\n" + "\n".join(arg_sqls) + "\n", skip_first=True, skip_last=True + ) + return " ".join(arg_sqls)
diff --git a/tests/dialects/test_oracle.py b/tests/dialects/test_oracle.py index d2bbedcde5..36ce5d02e6 100644 --- a/tests/dialects/test_oracle.py +++ b/tests/dialects/test_oracle.py @@ -329,6 +329,57 @@ def test_hints(self): ) self.validate_identity("INSERT /*+ APPEND */ INTO IAP_TBL (id, col1) VALUES (2, 'test2')") self.validate_identity("INSERT /*+ APPEND_VALUES */ INTO dest_table VALUES (i, 'Value')") + self.validate_identity( + "SELECT /*+ LEADING(departments employees) USE_NL(employees) */ * FROM employees JOIN departments ON employees.department_id = departments.department_id", + """SELECT /*+ LEADING(departments employees) + USE_NL(employees) */ + * +FROM employees +JOIN departments + ON employees.department_id = departments.department_id""", + pretty=True, + ) + self.validate_identity( + "SELECT /*+ USE_NL(bbbbbbbbbbbbbbbbbbbbbbbb) LEADING(aaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbb cccccccccccccccccccccccc dddddddddddddddddddddddd) INDEX(cccccccccccccccccccccccc) */ * FROM aaaaaaaaaaaaaaaaaaaaaaaa JOIN bbbbbbbbbbbbbbbbbbbbbbbb ON aaaaaaaaaaaaaaaaaaaaaaaa.id = bbbbbbbbbbbbbbbbbbbbbbbb.a_id JOIN cccccccccccccccccccccccc ON bbbbbbbbbbbbbbbbbbbbbbbb.id = cccccccccccccccccccccccc.b_id JOIN dddddddddddddddddddddddd ON cccccccccccccccccccccccc.id = dddddddddddddddddddddddd.c_id", + ) + self.validate_identity( + "SELECT /*+ USE_NL(bbbbbbbbbbbbbbbbbbbbbbbb) LEADING(aaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbb cccccccccccccccccccccccc dddddddddddddddddddddddd) INDEX(cccccccccccccccccccccccc) */ * FROM aaaaaaaaaaaaaaaaaaaaaaaa JOIN bbbbbbbbbbbbbbbbbbbbbbbb ON aaaaaaaaaaaaaaaaaaaaaaaa.id = bbbbbbbbbbbbbbbbbbbbbbbb.a_id JOIN cccccccccccccccccccccccc ON bbbbbbbbbbbbbbbbbbbbbbbb.id = cccccccccccccccccccccccc.b_id JOIN dddddddddddddddddddddddd ON cccccccccccccccccccccccc.id = dddddddddddddddddddddddd.c_id", + """SELECT /*+ USE_NL(bbbbbbbbbbbbbbbbbbbbbbbb) + LEADING( + aaaaaaaaaaaaaaaaaaaaaaaa + bbbbbbbbbbbbbbbbbbbbbbbb + cccccccccccccccccccccccc + dddddddddddddddddddddddd + ) + INDEX(cccccccccccccccccccccccc) */ + * +FROM aaaaaaaaaaaaaaaaaaaaaaaa +JOIN bbbbbbbbbbbbbbbbbbbbbbbb + ON aaaaaaaaaaaaaaaaaaaaaaaa.id = bbbbbbbbbbbbbbbbbbbbbbbb.a_id +JOIN cccccccccccccccccccccccc + ON bbbbbbbbbbbbbbbbbbbbbbbb.id = cccccccccccccccccccccccc.b_id +JOIN dddddddddddddddddddddddd + ON cccccccccccccccccccccccc.id = dddddddddddddddddddddddd.c_id""", + pretty=True, + ) + # Test that parsing error with keywords like select where etc falls back + self.validate_identity( + "SELECT /*+ LEADING(departments employees) USE_NL(employees) select where group by is order by */ * FROM employees JOIN departments ON employees.department_id = departments.department_id", + """SELECT /*+ LEADING(departments employees) USE_NL(employees) select where group by is order by */ + * +FROM employees +JOIN departments + ON employees.department_id = departments.department_id""", + pretty=True, + ) + # Test that parsing error with , inside hint function falls back + self.validate_identity( + "SELECT /*+ LEADING(departments, employees) */ * FROM employees JOIN departments ON employees.department_id = departments.department_id" + ) + # Test that parsing error with keyword inside hint function falls back + self.validate_identity( + "SELECT /*+ LEADING(departments select) */ * FROM employees JOIN departments ON employees.department_id = departments.department_id" + ) def test_xml_table(self): self.validate_identity("XMLTABLE('x')")
[ { "components": [ { "doc": "", "lines": [ 237, 247 ], "name": "Oracle.Parser._parse_hint_function_call", "signature": "def _parse_hint_function_call(self) -> t.Optional[exp.Expression]:", "type": "function" }, { "doc": "", "lines": [ 249, 257 ], "name": "Oracle.Parser._parse_hint_args", "signature": "def _parse_hint_args(self):", "type": "function" }, { "doc": "", "lines": [ 259, 271 ], "name": "Oracle.Parser._parse_hint_fallback_to_string", "signature": "def _parse_hint_fallback_to_string(self) -> t.Optional[exp.Hint]:", "type": "function" }, { "doc": "", "lines": [ 427, 437 ], "name": "Oracle.Generator.hint_sql", "signature": "def hint_sql(self, expression: exp.Hint) -> str:", "type": "function" }, { "doc": "", "lines": [ 439, 445 ], "name": "Oracle.Generator._format_hint_function_args", "signature": "def _format_hint_function_args(self, *args: t.Optional[str | exp.Expression]) -> str:", "type": "function" } ], "file": "sqlglot/dialects/oracle.py" } ]
[ "tests/dialects/test_oracle.py::TestOracle::test_hints" ]
[ "tests/dialects/test_oracle.py::TestOracle::test_connect_by", "tests/dialects/test_oracle.py::TestOracle::test_grant", "tests/dialects/test_oracle.py::TestOracle::test_join_marker", "tests/dialects/test_oracle.py::TestOracle::test_json_functions", "tests/dialects/test_oracle.py::TestOracle::test_json_table", "tests/dialects/test_oracle.py::TestOracle::test_match_recognize", "tests/dialects/test_oracle.py::TestOracle::test_multitable_inserts", "tests/dialects/test_oracle.py::TestOracle::test_oracle", "tests/dialects/test_oracle.py::TestOracle::test_query_restrictions", "tests/dialects/test_oracle.py::TestOracle::test_xml_table" ]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> Feature/oracle hints Hi @georgesittas Please review this PR we discussed over on [Slack](https://tobiko-data.slack.com/archives/C0448SFS3PF/p1728489927717069), which adds better support for Oracle Hints. ---- The current sqlglot implementation is to parse oracle hints as one big string, instead of breaking them up into Anonymous and Var expressions. This PR attempts to parse Oralce hints into Anonymous and Var expressions. In the event the user has some kind of spelling error, or uses keywords like `select`, this will fall back to the original implementation, instead of throwing an error or instead of parsing into Anonymous/Var. Oracle hints differ from other dialects in that arguments to hint functions are separated by space, not comma. Oracle does not, as far as I am aware from experience and the documentation, support nested hint functions. In the event that nested hints are supported or will by supported in the future, this implementation will simply fall back and parse it as a string. This PR also handles the pretty printing in a way that is identical with how sqlglot does it for mysql. Please see the tests for a few examples. ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in sqlglot/dialects/oracle.py] (definition of Oracle.Parser._parse_hint_function_call:) def _parse_hint_function_call(self) -> t.Optional[exp.Expression]: (definition of Oracle.Parser._parse_hint_args:) def _parse_hint_args(self): (definition of Oracle.Parser._parse_hint_fallback_to_string:) def _parse_hint_fallback_to_string(self) -> t.Optional[exp.Hint]: (definition of Oracle.Generator.hint_sql:) def hint_sql(self, expression: exp.Hint) -> str: (definition of Oracle.Generator._format_hint_function_args:) def _format_hint_function_args(self, *args: t.Optional[str | exp.Expression]) -> str: [end of new definitions in sqlglot/dialects/oracle.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
ceb42fabad60312699e4b15936aeebac00e22e4d
tobymao__sqlglot-4217
4,217
tobymao/sqlglot
null
22a16848d80a2fa6d310f99d21f7d81f90eb9440
2024-10-07T08:22:14Z
diff --git a/sqlglot/expressions.py b/sqlglot/expressions.py index c5e40bed04..064805d5ca 100644 --- a/sqlglot/expressions.py +++ b/sqlglot/expressions.py @@ -3284,6 +3284,200 @@ class Update(Expression): "limit": False, } + def table( + self, expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts + ) -> Update: + """ + Set the table to update. + + Example: + >>> Update().table("my_table").set_("x = 1").sql() + 'UPDATE my_table SET x = 1' + + Args: + expression : the SQL code strings to parse. + If a `Table` instance is passed, this is used as-is. + If another `Expression` instance is passed, it will be wrapped in a `Table`. + dialect: the dialect used to parse the input expression. + copy: if `False`, modify this expression instance in-place. + opts: other options to use to parse the input expressions. + + Returns: + The modified Update expression. + """ + return _apply_builder( + expression=expression, + instance=self, + arg="this", + into=Table, + prefix=None, + dialect=dialect, + copy=copy, + **opts, + ) + + def set_( + self, + *expressions: ExpOrStr, + append: bool = True, + dialect: DialectType = None, + copy: bool = True, + **opts, + ) -> Update: + """ + Append to or set the SET expressions. + + Example: + >>> Update().table("my_table").set_("x = 1").sql() + 'UPDATE my_table SET x = 1' + + Args: + *expressions: the SQL code strings to parse. + If `Expression` instance(s) are passed, they will be used as-is. + Multiple expressions are combined with a comma. + append: if `True`, add the new expressions to any existing SET expressions. + Otherwise, this resets the expressions. + dialect: the dialect used to parse the input expressions. + copy: if `False`, modify this expression instance in-place. + opts: other options to use to parse the input expressions. + """ + return _apply_list_builder( + *expressions, + instance=self, + arg="expressions", + append=append, + into=Expression, + prefix=None, + dialect=dialect, + copy=copy, + **opts, + ) + + def where( + self, + *expressions: t.Optional[ExpOrStr], + append: bool = True, + dialect: DialectType = None, + copy: bool = True, + **opts, + ) -> Select: + """ + Append to or set the WHERE expressions. + + Example: + >>> Update().table("tbl").set_("x = 1").where("x = 'a' OR x < 'b'").sql() + "UPDATE tbl SET x = 1 WHERE x = 'a' OR x < 'b'" + + Args: + *expressions: the SQL code strings to parse. + If an `Expression` instance is passed, it will be used as-is. + Multiple expressions are combined with an AND operator. + append: if `True`, AND the new expressions to any existing expression. + Otherwise, this resets the expression. + dialect: the dialect used to parse the input expressions. + copy: if `False`, modify this expression instance in-place. + opts: other options to use to parse the input expressions. + + Returns: + Select: the modified expression. + """ + return _apply_conjunction_builder( + *expressions, + instance=self, + arg="where", + append=append, + into=Where, + dialect=dialect, + copy=copy, + **opts, + ) + + def from_( + self, + expression: t.Optional[ExpOrStr] = None, + dialect: DialectType = None, + copy: bool = True, + **opts, + ) -> Update: + """ + Set the FROM expression. + + Example: + >>> Update().table("my_table").set_("x = 1").from_("baz").sql() + 'UPDATE my_table SET x = 1 FROM baz' + + Args: + expression : the SQL code strings to parse. + If a `From` instance is passed, this is used as-is. + If another `Expression` instance is passed, it will be wrapped in a `From`. + If nothing is passed in then a from is not applied to the expression + dialect: the dialect used to parse the input expression. + copy: if `False`, modify this expression instance in-place. + opts: other options to use to parse the input expressions. + + Returns: + The modified Update expression. + """ + if not expression: + return maybe_copy(self, copy) + + return _apply_builder( + expression=expression, + instance=self, + arg="from", + into=From, + prefix="FROM", + dialect=dialect, + copy=copy, + **opts, + ) + + def with_( + self, + alias: ExpOrStr, + as_: ExpOrStr, + recursive: t.Optional[bool] = None, + materialized: t.Optional[bool] = None, + append: bool = True, + dialect: DialectType = None, + copy: bool = True, + **opts, + ) -> Update: + """ + Append to or set the common table expressions. + + Example: + >>> Update().table("my_table").set_("x = 1").from_("baz").with_("baz", "SELECT id FROM foo").sql() + 'WITH baz AS (SELECT id FROM foo) UPDATE my_table SET x = 1 FROM baz' + + Args: + alias: the SQL code string to parse as the table name. + If an `Expression` instance is passed, this is used as-is. + as_: the SQL code string to parse as the table expression. + If an `Expression` instance is passed, it will be used as-is. + recursive: set the RECURSIVE part of the expression. Defaults to `False`. + materialized: set the MATERIALIZED part of the expression. + append: if `True`, add to any existing expressions. + Otherwise, this resets the expressions. + dialect: the dialect used to parse the input expression. + copy: if `False`, modify this expression instance in-place. + opts: other options to use to parse the input expressions. + + Returns: + The modified expression. + """ + return _apply_cte_builder( + self, + alias, + as_, + recursive=recursive, + materialized=materialized, + append=append, + dialect=dialect, + copy=copy, + **opts, + ) + class Values(UDTF): arg_types = {"expressions": True, "alias": False} @@ -6803,9 +6997,10 @@ def from_(expression: ExpOrStr, dialect: DialectType = None, **opts) -> Select: def update( table: str | Table, - properties: dict, + properties: t.Optional[dict] = None, where: t.Optional[ExpOrStr] = None, from_: t.Optional[ExpOrStr] = None, + with_: t.Optional[t.Dict[str, ExpOrStr]] = None, dialect: DialectType = None, **opts, ) -> Update: @@ -6813,14 +7008,15 @@ def update( Creates an update statement. Example: - >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql() - "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1" + >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz_cte", where="baz_cte.id > 1 and my_table.id = baz_cte.id", with_={"baz_cte": "SELECT id FROM foo"}).sql() + "WITH baz_cte AS (SELECT id FROM foo) UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz_cte WHERE baz_cte.id > 1 AND my_table.id = baz_cte.id" Args: - *properties: dictionary of properties to set which are + properties: dictionary of properties to SET which are auto converted to sql objects eg None -> NULL where: sql conditional parsed into a WHERE statement from_: sql statement parsed into a FROM statement + with_: dictionary of CTE aliases / select statements to include in a WITH clause. dialect: the dialect used to parse the input expressions. **opts: other options to use to parse the input expressions. @@ -6828,13 +7024,14 @@ def update( Update: the syntax tree for the UPDATE statement. """ update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect)) - update_expr.set( - "expressions", - [ - EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v)) - for k, v in properties.items() - ], - ) + if properties: + update_expr.set( + "expressions", + [ + EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v)) + for k, v in properties.items() + ], + ) if from_: update_expr.set( "from", @@ -6847,6 +7044,15 @@ def update( "where", maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts), ) + if with_: + cte_list = [ + CTE(this=maybe_parse(qry, dialect=dialect, **opts), alias=alias) + for alias, qry in with_.items() + ] + update_expr.set( + "with", + With(expressions=cte_list), + ) return update_expr
diff --git a/tests/test_build.py b/tests/test_build.py index 7518b72a2a..5d383ad00b 100644 --- a/tests/test_build.py +++ b/tests/test_build.py @@ -577,6 +577,36 @@ def test_build(self): lambda: exp.update("tbl", {"x": 1}, from_="tbl2 cross join tbl3"), "UPDATE tbl SET x = 1 FROM tbl2 CROSS JOIN tbl3", ), + ( + lambda: exp.update( + "my_table", + {"x": 1}, + from_="baz", + where="my_table.id = baz.id", + with_={"baz": "SELECT id FROM foo UNION SELECT id FROM bar"}, + ), + "WITH baz AS (SELECT id FROM foo UNION SELECT id FROM bar) UPDATE my_table SET x = 1 FROM baz WHERE my_table.id = baz.id", + ), + ( + lambda: exp.update("my_table").set_("x = 1"), + "UPDATE my_table SET x = 1", + ), + ( + lambda: exp.update("my_table").set_("x = 1").where("y = 2"), + "UPDATE my_table SET x = 1 WHERE y = 2", + ), + ( + lambda: exp.update("my_table").set_("a = 1").set_("b = 2"), + "UPDATE my_table SET a = 1, b = 2", + ), + ( + lambda: exp.update("my_table") + .set_("x = 1") + .where("my_table.id = baz.id") + .from_("baz") + .with_("baz", "SELECT id FROM foo"), + "WITH baz AS (SELECT id FROM foo) UPDATE my_table SET x = 1 FROM baz WHERE my_table.id = baz.id", + ), ( lambda: union("SELECT * FROM foo", "SELECT * FROM bla"), "SELECT * FROM foo UNION SELECT * FROM bla",
[ { "components": [ { "doc": "Set the table to update.\n\nExample:\n >>> Update().table(\"my_table\").set_(\"x = 1\").sql()\n 'UPDATE my_table SET x = 1'\n\nArgs:\n expression : the SQL code strings to parse.\n If a `Table` instance is passed, this is used as-is.\n If another `Expression` instance is passed, it will be wrapped in a `Table`.\n dialect: the dialect used to parse the input expression.\n copy: if `False`, modify this expression instance in-place.\n opts: other options to use to parse the input expressions.\n\nReturns:\n The modified Update expression.", "lines": [ 3293, 3322 ], "name": "Update.table", "signature": "def table( self, expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts ) -> Update:", "type": "function" }, { "doc": "Append to or set the SET expressions.\n\nExample:\n >>> Update().table(\"my_table\").set_(\"x = 1\").sql()\n 'UPDATE my_table SET x = 1'\n\nArgs:\n *expressions: the SQL code strings to parse.\n If `Expression` instance(s) are passed, they will be used as-is.\n Multiple expressions are combined with a comma.\n append: if `True`, add the new expressions to any existing SET expressions.\n Otherwise, this resets the expressions.\n dialect: the dialect used to parse the input expressions.\n copy: if `False`, modify this expression instance in-place.\n opts: other options to use to parse the input expressions.", "lines": [ 3325, 3359 ], "name": "Update.set_", "signature": "def set_( self, *expressions: ExpOrStr, append: bool = True, dialect: DialectType = None, copy: bool = True, **opts, ) -> Update:", "type": "function" }, { "doc": "Append to or set the WHERE expressions.\n\nExample:\n >>> Update().table(\"tbl\").set_(\"x = 1\").where(\"x = 'a' OR x < 'b'\").sql()\n \"UPDATE tbl SET x = 1 WHERE x = 'a' OR x < 'b'\"\n\nArgs:\n *expressions: the SQL code strings to parse.\n If an `Expression` instance is passed, it will be used as-is.\n Multiple expressions are combined with an AND operator.\n append: if `True`, AND the new expressions to any existing expression.\n Otherwise, this resets the expression.\n dialect: the dialect used to parse the input expressions.\n copy: if `False`, modify this expression instance in-place.\n opts: other options to use to parse the input expressions.\n\nReturns:\n Select: the modified expression.", "lines": [ 3362, 3398 ], "name": "Update.where", "signature": "def where( self, *expressions: t.Optional[ExpOrStr], append: bool = True, dialect: DialectType = None, copy: bool = True, **opts, ) -> Select:", "type": "function" }, { "doc": "Set the FROM expression.\n\nExample:\n >>> Update().table(\"my_table\").set_(\"x = 1\").from_(\"baz\").sql()\n 'UPDATE my_table SET x = 1 FROM baz'\n\nArgs:\n expression : the SQL code strings to parse.\n If a `From` instance is passed, this is used as-is.\n If another `Expression` instance is passed, it will be wrapped in a `From`.\n If nothing is passed in then a from is not applied to the expression\n dialect: the dialect used to parse the input expression.\n copy: if `False`, modify this expression instance in-place.\n opts: other options to use to parse the input expressions.\n\nReturns:\n The modified Update expression.", "lines": [ 3401, 3438 ], "name": "Update.from_", "signature": "def from_( self, expression: t.Optional[ExpOrStr] = None, dialect: DialectType = None, copy: bool = True, **opts, ) -> Update:", "type": "function" }, { "doc": "Append to or set the common table expressions.\n\nExample:\n >>> Update().table(\"my_table\").set_(\"x = 1\").from_(\"baz\").with_(\"baz\", \"SELECT id FROM foo\").sql()\n 'WITH baz AS (SELECT id FROM foo) UPDATE my_table SET x = 1 FROM baz'\n\nArgs:\n alias: the SQL code string to parse as the table name.\n If an `Expression` instance is passed, this is used as-is.\n as_: the SQL code string to parse as the table expression.\n If an `Expression` instance is passed, it will be used as-is.\n recursive: set the RECURSIVE part of the expression. Defaults to `False`.\n materialized: set the MATERIALIZED part of the expression.\n append: if `True`, add to any existing expressions.\n Otherwise, this resets the expressions.\n dialect: the dialect used to parse the input expression.\n copy: if `False`, modify this expression instance in-place.\n opts: other options to use to parse the input expressions.\n\nReturns:\n The modified expression.", "lines": [ 3441, 3484 ], "name": "Update.with_", "signature": "def with_( self, alias: ExpOrStr, as_: ExpOrStr, recursive: t.Optional[bool] = None, materialized: t.Optional[bool] = None, append: bool = True, dialect: DialectType = None, copy: bool = True, **opts, ) -> Update:", "type": "function" } ], "file": "sqlglot/expressions.py" } ]
[ "tests/test_build.py::TestBuild::test_build" ]
[]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> Feat: add builder methods to exp.Update and add with_ arg to exp.update Improve ergonomics of UPDATEs: - Add builder methods to Update class so it can be constructed incrementally in the same way a Select - `exp.update` changes: - Add a `with_` arg so updates with CTEs can be created in one-shot without subsequent need to `.set(...)` the With clause - Make the `properties` arg optional, so `set_` builder method can be used with an AST (`exp.update("tbl").set_(set_expr)` ) instead of forcing specification as a `dict` ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in sqlglot/expressions.py] (definition of Update.table:) def table( self, expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts ) -> Update: """Set the table to update. Example: >>> Update().table("my_table").set_("x = 1").sql() 'UPDATE my_table SET x = 1' Args: expression : the SQL code strings to parse. If a `Table` instance is passed, this is used as-is. If another `Expression` instance is passed, it will be wrapped in a `Table`. dialect: the dialect used to parse the input expression. copy: if `False`, modify this expression instance in-place. opts: other options to use to parse the input expressions. Returns: The modified Update expression.""" (definition of Update.set_:) def set_( self, *expressions: ExpOrStr, append: bool = True, dialect: DialectType = None, copy: bool = True, **opts, ) -> Update: """Append to or set the SET expressions. Example: >>> Update().table("my_table").set_("x = 1").sql() 'UPDATE my_table SET x = 1' Args: *expressions: the SQL code strings to parse. If `Expression` instance(s) are passed, they will be used as-is. Multiple expressions are combined with a comma. append: if `True`, add the new expressions to any existing SET expressions. Otherwise, this resets the expressions. dialect: the dialect used to parse the input expressions. copy: if `False`, modify this expression instance in-place. opts: other options to use to parse the input expressions.""" (definition of Update.where:) def where( self, *expressions: t.Optional[ExpOrStr], append: bool = True, dialect: DialectType = None, copy: bool = True, **opts, ) -> Select: """Append to or set the WHERE expressions. Example: >>> Update().table("tbl").set_("x = 1").where("x = 'a' OR x < 'b'").sql() "UPDATE tbl SET x = 1 WHERE x = 'a' OR x < 'b'" Args: *expressions: the SQL code strings to parse. If an `Expression` instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator. append: if `True`, AND the new expressions to any existing expression. Otherwise, this resets the expression. dialect: the dialect used to parse the input expressions. copy: if `False`, modify this expression instance in-place. opts: other options to use to parse the input expressions. Returns: Select: the modified expression.""" (definition of Update.from_:) def from_( self, expression: t.Optional[ExpOrStr] = None, dialect: DialectType = None, copy: bool = True, **opts, ) -> Update: """Set the FROM expression. Example: >>> Update().table("my_table").set_("x = 1").from_("baz").sql() 'UPDATE my_table SET x = 1 FROM baz' Args: expression : the SQL code strings to parse. If a `From` instance is passed, this is used as-is. If another `Expression` instance is passed, it will be wrapped in a `From`. If nothing is passed in then a from is not applied to the expression dialect: the dialect used to parse the input expression. copy: if `False`, modify this expression instance in-place. opts: other options to use to parse the input expressions. Returns: The modified Update expression.""" (definition of Update.with_:) def with_( self, alias: ExpOrStr, as_: ExpOrStr, recursive: t.Optional[bool] = None, materialized: t.Optional[bool] = None, append: bool = True, dialect: DialectType = None, copy: bool = True, **opts, ) -> Update: """Append to or set the common table expressions. Example: >>> Update().table("my_table").set_("x = 1").from_("baz").with_("baz", "SELECT id FROM foo").sql() 'WITH baz AS (SELECT id FROM foo) UPDATE my_table SET x = 1 FROM baz' Args: alias: the SQL code string to parse as the table name. If an `Expression` instance is passed, this is used as-is. as_: the SQL code string to parse as the table expression. If an `Expression` instance is passed, it will be used as-is. recursive: set the RECURSIVE part of the expression. Defaults to `False`. materialized: set the MATERIALIZED part of the expression. append: if `True`, add to any existing expressions. Otherwise, this resets the expressions. dialect: the dialect used to parse the input expression. copy: if `False`, modify this expression instance in-place. opts: other options to use to parse the input expressions. Returns: The modified expression.""" [end of new definitions in sqlglot/expressions.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
ceb42fabad60312699e4b15936aeebac00e22e4d
embeddings-benchmark__mteb-1256
1,256
embeddings-benchmark/mteb
null
f04279d5975f4a5c7fd5f5f284bfe14303b8f2a0
2024-09-29T12:28:20Z
diff --git a/README.md b/README.md index e35ad3bdbc..a7eb03e4f2 100644 --- a/README.md +++ b/README.md @@ -378,6 +378,7 @@ df = results_to_dataframe(results) | Documentation | | | ------------------------------ | ---------------------- | | 📋 [Tasks] | Overview of available tasks | +| 📐 [Benchmarks] | Overview of available benchmarks | | 📈 [Leaderboard] | The interactive leaderboard of the benchmark | | 🤖 [Adding a model] | Information related to how to submit a model to the leaderboard | | 👩‍🔬 [Reproducible workflows] | Information related to how to reproduce and create reproducible workflows with MTEB | @@ -387,6 +388,7 @@ df = results_to_dataframe(results) | 🌐 [MMTEB] | An open-source effort to extend MTEB to cover a broad set of languages |   [Tasks]: docs/tasks.md +[Benchmarks]: docs/benchmarks.md [Contributing]: CONTRIBUTING.md [Adding a model]: docs/adding_a_model.md [Adding a dataset]: docs/adding_a_dataset.md diff --git a/docs/benchmarks.md b/docs/benchmarks.md index 9eb471d187..a5abe50215 100644 --- a/docs/benchmarks.md +++ b/docs/benchmarks.md @@ -1,5 +1,5 @@ ## Available benchmarks -The following tables give you an overview of the benchmarks in MTEB. +The following table gives you an overview of the benchmarks in MTEB. <details> diff --git a/mteb/cli.py b/mteb/cli.py index 24e99bd241..b891d381f4 100644 --- a/mteb/cli.py +++ b/mteb/cli.py @@ -30,6 +30,14 @@ mteb available_tasks --task_types Clustering # list tasks of type Clustering ``` +## Listing Available Benchmarks + +To list the available benchmarks within MTEB, use the `mteb available_benchmarks` command. For example: + +```bash +mteb available_benchmarks # list all available benchmarks +``` + ## Creating Model Metadata @@ -144,6 +152,12 @@ def run(args: argparse.Namespace) -> None: _save_model_metadata(model, Path(args.output_folder)) +def available_benchmarks(args: argparse.Namespace) -> None: + benchmarks = mteb.get_benchmarks() + eval = mteb.MTEB(tasks=benchmarks) + eval.mteb_benchmarks() + + def available_tasks(args: argparse.Namespace) -> None: tasks = mteb.get_tasks( categories=args.categories, @@ -198,6 +212,15 @@ def add_available_tasks_parser(subparsers) -> None: parser.set_defaults(func=available_tasks) +def add_available_benchmarks_parser(subparsers) -> None: + parser = subparsers.add_parser( + "available_benchmarks", help="List the available benchmarks within MTEB" + ) + add_task_selection_args(parser) + + parser.set_defaults(func=available_benchmarks) + + def add_run_parser(subparsers) -> None: parser = subparsers.add_parser("run", help="Run a model on a set of tasks") @@ -321,6 +344,7 @@ def main(): ) add_run_parser(subparsers) add_available_tasks_parser(subparsers) + add_available_benchmarks_parser(subparsers) add_create_meta_parser(subparsers) args = parser.parse_args() diff --git a/mteb/evaluation/MTEB.py b/mteb/evaluation/MTEB.py index ab25169364..70f3e21ca8 100644 --- a/mteb/evaluation/MTEB.py +++ b/mteb/evaluation/MTEB.py @@ -168,6 +168,12 @@ def _display_tasks(self, task_list, name=None): console.print(f"{prefix}{name}{category}{multilingual}") console.print("\n") + def mteb_benchmarks(self): + """Get all benchmarks available in the MTEB.""" + for benchmark in self._tasks: + name = benchmark.name + self._display_tasks(benchmark.tasks, name=name) + @classmethod def mteb_tasks(cls): """Get all tasks available in the MTEB."""
diff --git a/tests/test_cli.py b/tests/test_cli.py index fdcd1b014a..1d0400e985 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -22,6 +22,15 @@ def test_available_tasks(): ), "Sample task Banking77Classification task not found in available tasks" +def test_available_benchmarks(): + command = f"{sys.executable} -m mteb available_benchmarks" + result = subprocess.run(command, shell=True, capture_output=True, text=True) + assert result.returncode == 0, "Command failed" + assert ( + "MTEB(eng)" in result.stdout + ), "Sample benchmark MTEB(eng) task not found in available bencmarks" + + run_task_fixures = [ ( "average_word_embeddings_komninos",
diff --git a/README.md b/README.md index e35ad3bdbc..a7eb03e4f2 100644 --- a/README.md +++ b/README.md @@ -378,6 +378,7 @@ df = results_to_dataframe(results) | Documentation | | | ------------------------------ | ---------------------- | | 📋 [Tasks] | Overview of available tasks | +| 📐 [Benchmarks] | Overview of available benchmarks | | 📈 [Leaderboard] | The interactive leaderboard of the benchmark | | 🤖 [Adding a model] | Information related to how to submit a model to the leaderboard | | 👩‍🔬 [Reproducible workflows] | Information related to how to reproduce and create reproducible workflows with MTEB | @@ -387,6 +388,7 @@ df = results_to_dataframe(results) | 🌐 [MMTEB] | An open-source effort to extend MTEB to cover a broad set of languages |   [Tasks]: docs/tasks.md +[Benchmarks]: docs/benchmarks.md [Contributing]: CONTRIBUTING.md [Adding a model]: docs/adding_a_model.md [Adding a dataset]: docs/adding_a_dataset.md diff --git a/docs/benchmarks.md b/docs/benchmarks.md index 9eb471d187..a5abe50215 100644 --- a/docs/benchmarks.md +++ b/docs/benchmarks.md @@ -1,5 +1,5 @@ ## Available benchmarks -The following tables give you an overview of the benchmarks in MTEB. +The following table gives you an overview of the benchmarks in MTEB. <details>
[ { "components": [ { "doc": "", "lines": [ 155, 158 ], "name": "available_benchmarks", "signature": "def available_benchmarks(args: argparse.Namespace) -> None:", "type": "function" }, { "doc": "", "lines": [ 215, 221 ], "name": "add_available_benchmarks_parser", "signature": "def add_available_benchmarks_parser(subparsers) -> None:", "type": "function" } ], "file": "mteb/cli.py" }, { "components": [ { "doc": "Get all benchmarks available in the MTEB.", "lines": [ 171, 175 ], "name": "MTEB.mteb_benchmarks", "signature": "def mteb_benchmarks(self):", "type": "function" } ], "file": "mteb/evaluation/MTEB.py" } ]
[ "tests/test_cli.py::test_available_benchmarks" ]
[ "tests/test_cli.py::test_available_tasks", "tests/test_cli.py::test_run_task[average_word_embeddings_komninos-BornholmBitextMining-21eec43590414cb8e3a6f654857abed0483ae36e]", "tests/test_cli.py::test_run_task[intfloat/multilingual-e5-small-BornholmBitextMining-e4ce9877abf3edfe10b0d82785e83bdcb973e22e]", "tests/test_cli.py::test_create_meta", "tests/test_cli.py::test_create_meta_from_existing[existing_readme.md-model_card_gold_existing.md]", "tests/test_cli.py::test_create_meta_from_existing[model_card_without_frontmatter.md-model_card_gold_without_frontmatter.md]", "tests/test_cli.py::test_save_predictions" ]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> fix: Add listing all available benchmarks CLI option <!-- If you are submitting a dataset or a model for the model registry please use the corresponding checklists below otherwise feel free to remove them. --> <!-- add additional description, question etc. related to the new dataset --> Addresses #1250 point 1. - Add benchmarks under the "Docs" section of README - Add CLI option to list all available benchmarks - Headers will print the benchmark name - The tasks will be printed the same way as it is now - Add test case for the added CLI option ## Example This command should yield something like the following, starting with MTEB(eng): ``` mteb available_benchmarks ``` <details> <summary>Full printout</summary> ```bash >> mteb available_benchmarks ─────────────────────────────────────────────────────────────── MTEB(eng) ──────────────────────────────────────────────────────────────── Summarization - SummEval, p2p PairClassification - SprintDuplicateQuestions, s2s - TwitterSemEval2015, s2s - TwitterURLCorpus, s2s Classification - AmazonCounterfactualClassification, s2s, multilingual 2 / 4 Subsets - AmazonPolarityClassification, p2p - AmazonReviewsClassification, s2s, multilingual 1 / 6 Subsets - Banking77Classification, s2s - EmotionClassification, s2s - ImdbClassification, p2p - MTOPDomainClassification, s2s, multilingual 1 / 6 Subsets - MTOPIntentClassification, s2s, multilingual 1 / 6 Subsets - MassiveIntentClassification, s2s, multilingual 1 / 51 Subsets - MassiveScenarioClassification, s2s, multilingual 1 / 51 Subsets - ToxicConversationsClassification, s2s - TweetSentimentExtractionClassification, s2s Retrieval - ArguAna, s2p - CQADupstackAndroidRetrieval, s2p - CQADupstackEnglishRetrieval, s2p - CQADupstackGamingRetrieval, s2p - CQADupstackGisRetrieval, s2p - CQADupstackMathematicaRetrieval, s2p - CQADupstackPhysicsRetrieval, s2p - CQADupstackProgrammersRetrieval, s2p - CQADupstackStatsRetrieval, s2p - CQADupstackTexRetrieval, s2p - CQADupstackUnixRetrieval, s2p - CQADupstackWebmastersRetrieval, s2p - CQADupstackWordpressRetrieval, s2p - ClimateFEVER, s2p - DBPedia, s2p - FEVER, s2p - FiQA2018, s2p - HotpotQA, s2p - MSMARCO, s2p - NFCorpus, s2p - NQ, s2p - QuoraRetrieval, s2s - SCIDOCS, s2p - SciFact, s2p - TRECCOVID, s2p - Touche2020, s2p STS - BIOSSES, s2s - SICK-R, s2s - STS12, s2s - STS13, s2s - STS14, s2s - STS15, s2s - STS16, s2s - STS17, s2s, multilingual 8 / 11 Subsets - STS22, p2p, multilingual 5 / 18 Subsets - STSBenchmark, s2s Clustering - ArxivClusteringP2P, p2p - ArxivClusteringS2S, s2s - BiorxivClusteringP2P, p2p - BiorxivClusteringS2S, s2s - MedrxivClusteringP2P, p2p - MedrxivClusteringS2S, s2s - RedditClustering, s2s - RedditClusteringP2P, p2p - StackExchangeClustering, s2s - StackExchangeClusteringP2P, p2p - TwentyNewsgroupsClustering, s2s Reranking - AskUbuntuDupQuestions, s2s - MindSmallReranking, s2s - SciDocsRR, s2s - StackOverflowDupQuestions, s2s ─────────────────────────────────────────────────────────────── MTEB(rus) ──────────────────────────────────────────────────────────────── PairClassification - TERRa, s2s Classification - GeoreviewClassification, p2p - HeadlineClassification, s2s - InappropriatenessClassification, s2s - KinopoiskClassification, p2p - MassiveIntentClassification, s2s, multilingual 1 / 51 Subsets - MassiveScenarioClassification, s2s, multilingual 1 / 51 Subsets - RuReviewsClassification, p2p - RuSciBenchGRNTIClassification, p2p - RuSciBenchOECDClassification, p2p MultilabelClassification - CEDRClassification, s2s - SensitiveTopicsClassification, s2s Retrieval - MIRACLRetrieval, s2p, multilingual 1 / 18 Subsets - RiaNewsRetrieval, s2p - RuBQRetrieval, s2p STS - RUParaPhraserSTS, s2s - RuSTSBenchmarkSTS, s2s - STS22, p2p, multilingual 1 / 18 Subsets Clustering - GeoreviewClusteringP2P, p2p - RuSciBenchGRNTIClusteringP2P, p2p - RuSciBenchOECDClusteringP2P, p2p Reranking - MIRACLReranking, s2s, multilingual 1 / 18 Subsets - RuBQReranking, s2p ───────────────────────────────────────────────────── MTEB(Retrieval w/Instructions) ───────────────────────────────────────────────────── InstructionRetrieval - Robust04InstructionRetrieval, s2p - News21InstructionRetrieval, s2p - Core17InstructionRetrieval, s2p ─────────────────────────────────────────────────────────────── MTEB(law) ──────────────────────────────────────────────────────────────── Retrieval - AILACasedocs, p2p - AILAStatutes, p2p - LegalSummarization, s2p - GerDaLIRSmall, p2p - LeCaRDv2, p2p - LegalBenchConsumerContractsQA, s2p - LegalBenchCorporateLobbying, s2p - LegalQuAD, s2p ─────────────────────────────────────────────────────────── MINERSBitextMining ─────────────────────────────────────────────────────────── BitextMining - BUCC, s2s, multilingual 4 / 4 Subsets - LinceMTBitextMining, s2s, multilingual 1 / 1 Subsets - NollySentiBitextMining, s2s, multilingual 4 / 4 Subsets - NusaXBitextMining, s2s, multilingual 11 / 11 Subsets - NusaTranslationBitextMining, s2s, multilingual 11 / 11 Subsets - PhincBitextMining, s2s, multilingual 1 / 1 Subsets - Tatoeba, s2s, multilingual 112 / 112 Subsets ─────────────────────────────────────────────────────────── MTEB(Scandinavian) ─────────────────────────────────────────────────────────── Classification - AngryTweetsClassification, s2s - DanishPoliticalCommentsClassification, s2s - DalajClassification, s2s - DKHateClassification, s2s - LccSentimentClassification, s2s - MassiveIntentClassification, s2s, multilingual 3 / 51 Subsets - MassiveScenarioClassification, s2s, multilingual 3 / 51 Subsets - NordicLangClassification, s2s - NoRecClassification, s2s - NorwegianParliamentClassification, s2s - ScalaClassification, s2s, multilingual 4 / 4 Subsets - SwedishSentimentClassification, s2s - SweRecClassification, s2s BitextMining - BornholmBitextMining, s2s - NorwegianCourtsBitextMining, s2s Retrieval - DanFEVER, p2p - NorQuadRetrieval, p2p - SNLRetrieval, p2p - SwednRetrieval, p2p - SweFaqRetrieval, s2s - TV2Nordretrieval, p2p - TwitterHjerneRetrieval, p2p Clustering - SNLHierarchicalClusteringS2S, s2s - SNLHierarchicalClusteringP2P, p2p - SwednClusteringP2P, p2p - SwednClusteringS2S, s2s - VGHierarchicalClusteringS2S, p2p - VGHierarchicalClusteringP2P, p2p ────────────────────────────────────────────────────────────────── CoIR ────────────────────────────────────────────────────────────────── Retrieval - AppsRetrieval, p2p - CodeFeedbackMT, p2p - CodeFeedbackST, p2p - CodeSearchNetCCRetrieval, p2p, multilingual 6 / 6 Subsets - CodeTransOceanContest, p2p - CodeTransOceanDL, p2p - CosQA, p2p - COIRCodeSearchNetRetrieval, p2p, multilingual 6 / 6 Subsets - StackOverflowQA, p2p - SyntheticText2SQL, p2p ─────────────────────────────────────────────────────────────── MTEB(fra) ──────────────────────────────────────────────────────────────── Summarization - SummEvalFr, p2p PairClassification - OpusparcusPC, s2s, multilingual 1 / 6 Subsets - PawsXPairClassification, s2s, multilingual 1 / 7 Subsets Classification - AmazonReviewsClassification, s2s, multilingual 1 / 6 Subsets - MasakhaNEWSClassification, s2s, multilingual 1 / 16 Subsets - MassiveIntentClassification, s2s, multilingual 1 / 51 Subsets - MassiveScenarioClassification, s2s, multilingual 1 / 51 Subsets - MTOPDomainClassification, s2s, multilingual 1 / 6 Subsets - MTOPIntentClassification, s2s, multilingual 1 / 6 Subsets Retrieval - AlloprofRetrieval, s2p - BSARDRetrieval, s2p - MintakaRetrieval, s2p, multilingual 1 / 8 Subsets - SyntecRetrieval, s2p - XPQARetrieval, s2p, multilingual 3 / 36 Subsets STS - SICKFr, s2s - STS22, p2p, multilingual 3 / 18 Subsets - STSBenchmarkMultilingualSTS, s2s, multilingual 1 / 10 Subsets Clustering - AlloProfClusteringP2P, p2p - AlloProfClusteringS2S, s2s - HALClusteringS2S, s2s - MasakhaNEWSClusteringP2P, p2p, multilingual 1 / 16 Subsets - MasakhaNEWSClusteringS2S, s2s, multilingual 1 / 16 Subsets - MLSUMClusteringP2P, p2p, multilingual 1 / 4 Subsets - MLSUMClusteringS2S, s2s, multilingual 1 / 4 Subsets Reranking - AlloprofReranking, s2p - SyntecReranking, s2p ─────────────────────────────────────────────────────────────── MTEB(deu) ──────────────────────────────────────────────────────────────── PairClassification - FalseFriendsGermanEnglish, s2s - PawsXPairClassification, s2s, multilingual 1 / 7 Subsets Classification - AmazonCounterfactualClassification, s2s, multilingual 1 / 4 Subsets - AmazonReviewsClassification, s2s, multilingual 1 / 6 Subsets - MTOPDomainClassification, s2s, multilingual 1 / 6 Subsets - MTOPIntentClassification, s2s, multilingual 1 / 6 Subsets - MassiveIntentClassification, s2s, multilingual 1 / 51 Subsets - MassiveScenarioClassification, s2s, multilingual 1 / 51 Subsets Retrieval - GermanQuAD-Retrieval, s2p - GermanDPR, s2p - XMarket, s2p, multilingual 1 / 3 Subsets - GerDaLIR, s2p STS - GermanSTSBenchmark, s2s - STS22, p2p, multilingual 4 / 18 Subsets Clustering - BlurbsClusteringP2P, p2p - BlurbsClusteringS2S, s2s - TenKGnadClusteringP2P, p2p - TenKGnadClusteringS2S, s2s Reranking - MIRACLReranking, s2s, multilingual 1 / 18 Subsets ─────────────────────────────────────────────────────────────── MTEB(kor) ──────────────────────────────────────────────────────────────── Classification - KLUE-TC, s2s Retrieval - MIRACLRetrieval, s2p, multilingual 1 / 18 Subsets - Ko-StrategyQA, s2p STS - KLUE-STS, s2s - KorSTS, s2s Reranking - MIRACLReranking, s2s, multilingual 1 / 18 Subsets ─────────────────────────────────────────────────────────────── MTEB(pol) ──────────────────────────────────────────────────────────────── PairClassification - CDSC-E, s2s - PpcPC, s2s - PSC, s2s - SICK-E-PL, s2s Classification - AllegroReviews, s2s - CBD, s2s - MassiveIntentClassification, s2s, multilingual 1 / 51 Subsets - MassiveScenarioClassification, s2s, multilingual 1 / 51 Subsets - PolEmo2.0-IN, s2s - PolEmo2.0-OUT, s2s - PAC, p2p STS - CDSC-R, s2s - STS22, p2p, multilingual 4 / 18 Subsets - STSBenchmarkMultilingualSTS, s2s, multilingual 1 / 10 Subsets - SICK-R-PL, s2s Clustering - EightTagsClustering, s2s - PlscClusteringS2S, s2s - PlscClusteringP2P, s2s ─────────────────────────────────────────────────────────────── MTEB(code) ─────────────────────────────────────────────────────────────── Retrieval - AppsRetrieval, p2p - CodeEditSearchRetrieval, p2p, multilingual 13 / 13 Subsets - CodeFeedbackMT, p2p - CodeFeedbackST, p2p - CodeSearchNetCCRetrieval, p2p, multilingual 6 / 6 Subsets - CodeSearchNetRetrieval, p2p, multilingual 6 / 6 Subsets - CodeTransOceanContest, p2p - CodeTransOceanDL, p2p - CosQA, p2p - COIRCodeSearchNetRetrieval, p2p, multilingual 6 / 6 Subsets - StackOverflowQA, p2p - SyntheticText2SQL, p2p ─────────────────────────────────────────────────────────── MTEB(Multilingual) ─────────────────────────────────────────────────────────── PairClassification - CTKFactsNLI, s2s - SprintDuplicateQuestions, s2s - TwitterURLCorpus, s2s - ArmenianParaphrasePC, s2s - indonli, s2s - OpusparcusPC, s2s, multilingual 6 / 6 Subsets - PawsXPairClassification, s2s, multilingual 7 / 7 Subsets - RTE3, s2s, multilingual 4 / 4 Subsets - XNLI, s2s, multilingual 14 / 14 Subsets - PpcPC, s2s - TERRa, s2s Classification - BulgarianStoreReviewSentimentClassfication, s2s - CzechProductReviewSentimentClassification, s2s - GreekLegalCodeClassification, s2s - DBpediaClassification, s2s - FinancialPhrasebankClassification, s2s - PoemSentimentClassification, s2s - ToxicConversationsClassification, s2s - TweetTopicSingleClassification, s2s - EstonianValenceClassification, s2s - FilipinoShopeeReviewsClassification, s2s - GujaratiNewsClassification, s2s - SentimentAnalysisHindi, s2s - IndonesianIdClickbaitClassification, s2s - ItaCaseholdClassification, s2s - KorSarcasmClassification, s2s - KurdishSentimentClassification, s2s - MacedonianTweetSentimentClassification, s2s - AfriSentiClassification, s2s, multilingual 12 / 12 Subsets - AmazonCounterfactualClassification, s2s, multilingual 4 / 4 Subsets - CataloniaTweetClassification, s2s, multilingual 2 / 2 Subsets - CyrillicTurkicLangClassification, s2s - IndicLangClassification, s2s - MasakhaNEWSClassification, s2s, multilingual 16 / 16 Subsets - MassiveIntentClassification, s2s, multilingual 51 / 51 Subsets - MultiHateClassification, s2s, multilingual 11 / 11 Subsets - NordicLangClassification, s2s - NusaParagraphEmotionClassification, s2s, multilingual 10 / 10 Subsets - NusaX-senti, s2s, multilingual 12 / 12 Subsets - ScalaClassification, s2s, multilingual 4 / 4 Subsets - SwissJudgementClassification, s2s, multilingual 3 / 3 Subsets - NepaliNewsClassification, s2s - OdiaNewsClassification, s2s - PunjabiNewsClassification, s2s - PolEmo2.0-OUT, s2s - PAC, p2p - SinhalaNewsClassification, s2s - CSFDSKMovieReviewSentimentClassification, s2s - SiswatiNewsClassification, s2s - SlovakMovieReviewSentimentClassification, s2s - SwahiliNewsClassification, s2s - DalajClassification, s2s - TswanaNewsClassification, s2s - IsiZuluNewsClassification, s2s BitextMining - BornholmBitextMining, s2s - BibleNLPBitextMining, s2s, multilingual 1656 / 1656 Subsets - BUCC.v2, s2s, multilingual 4 / 4 Subsets - DiaBlaBitextMining, s2s, multilingual 2 / 2 Subsets - FloresBitextMining, s2s, multilingual 41412 / 41412 Subsets - IN22GenBitextMining, s2s, multilingual 506 / 506 Subsets - IndicGenBenchFloresBitextMining, s2s, multilingual 58 / 58 Subsets - NollySentiBitextMining, s2s, multilingual 4 / 4 Subsets - NorwegianCourtsBitextMining, s2s - NTREXBitextMining, s2s, multilingual 1916 / 1916 Subsets - NusaTranslationBitextMining, s2s, multilingual 11 / 11 Subsets - NusaXBitextMining, s2s, multilingual 11 / 11 Subsets - Tatoeba, s2s, multilingual 112 / 112 Subsets MultilabelClassification - KorHateSpeechMLClassification, s2s - MalteseNewsClassification, s2s - MultiEURLEXMultilabelClassification, p2p, multilingual 23 / 23 Subsets - BrazilianToxicTweetsClassification, s2s - CEDRClassification, s2s InstructionRetrieval - Core17InstructionRetrieval, s2p - News21InstructionRetrieval, s2p - Robust04InstructionRetrieval, s2p Retrieval - StackOverflowQA, p2p - TwitterHjerneRetrieval, p2p - AILAStatutes, p2p - ArguAna, s2p - HagridRetrieval, s2p - LegalBenchCorporateLobbying, s2p - LEMBPasskeyRetrieval, s2p - SCIDOCS, s2p - SpartQA, s2s - TempReasonL1, s2s - TRECCOVID, s2p - WinoGrande, s2s - BelebeleRetrieval, s2p, multilingual 376 / 376 Subsets - MLQARetrieval, s2p, multilingual 49 / 49 Subsets - StatcanDialogueDatasetRetrieval, s2p, multilingual 2 / 2 Subsets - WikipediaRetrievalMultilingual, s2p, multilingual 16 / 16 Subsets - CovidRetrieval, s2p STS - GermanSTSBenchmark, s2s - SICK-R, s2s - STS12, s2s - STS13, s2s - STS14, s2s - STS15, s2s - STSBenchmark, s2s - FaroeseSTS, s2s - FinParaSTS, s2s - JSICK, s2s - IndicCrosslingualSTS, s2s, multilingual 12 / 12 Subsets - SemRel24STS, s2s, multilingual 12 / 12 Subsets - STS17, s2s, multilingual 11 / 11 Subsets - STS22.v2, p2p, multilingual 18 / 18 Subsets - STSES, s2s - STSB, s2s Clustering - WikiCitiesClustering, p2p - MasakhaNEWSClusteringS2S, s2s, multilingual 16 / 16 Subsets - RomaniBibleClustering, p2p - ArXivHierarchicalClusteringP2P, p2p - ArXivHierarchicalClusteringS2S, p2p - BigPatentClustering.v2, p2p - BiorxivClusteringP2P.v2, p2p - MedrxivClusteringP2P.v2, p2p - StackExchangeClustering.v2, s2s - AlloProfClusteringS2S.v2, s2s - HALClusteringS2S.v2, s2s - SIB200ClusteringS2S, s2s, multilingual 197 / 197 Subsets - WikiClusteringP2P.v2, p2p, multilingual 14 / 14 Subsets - SNLHierarchicalClusteringP2P, p2p - PlscClusteringP2P.v2, s2s - SwednClusteringP2P, p2p - CLSClusteringP2P.v2, p2p Reranking - WebLINXCandidatesReranking, p2p - AlloprofReranking, s2p - VoyageMMarcoReranking, s2s - WikipediaRerankingMultilingual, s2p, multilingual 16 / 16 Subsets - RuBQReranking, s2p - T2Reranking, s2s ``` </details> ![image](https://github.com/user-attachments/assets/3d05c14f-8f40-4239-83bc-02afd7374292) ## Checklist <!-- Please do not delete this --> - [x] Run tests locally to make sure nothing is broken using `make test`. - [x] Run the formatter to format the code using `make lint`. ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in mteb/cli.py] (definition of available_benchmarks:) def available_benchmarks(args: argparse.Namespace) -> None: (definition of add_available_benchmarks_parser:) def add_available_benchmarks_parser(subparsers) -> None: [end of new definitions in mteb/cli.py] [start of new definitions in mteb/evaluation/MTEB.py] (definition of MTEB.mteb_benchmarks:) def mteb_benchmarks(self): """Get all benchmarks available in the MTEB.""" [end of new definitions in mteb/evaluation/MTEB.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
b580b95fc91a7e7e675d27c3ae9a9df64ddad169
google-deepmind__optax-1063
1,063
google-deepmind/optax
null
ee63e4500fbd412d778a1ea143237007e45a5628
2024-09-17T21:50:23Z
diff --git a/docs/api/utilities.rst b/docs/api/utilities.rst index b199697f6..c792944fd 100644 --- a/docs/api/utilities.rst +++ b/docs/api/utilities.rst @@ -101,6 +101,7 @@ Tree tree_mul tree_ones_like tree_random_like + tree_split_key_like tree_scalar_mul tree_set tree_sub @@ -153,6 +154,10 @@ Tree ones like ~~~~~~~~~~~~~~ .. autofunction:: tree_ones_like +Tree with random keys +~~~~~~~~~~~~~~~~~~~~~~~ +.. autofunction:: tree_split_key_like + Tree with random values ~~~~~~~~~~~~~~~~~~~~~~~ .. autofunction:: tree_random_like diff --git a/optax/tree_utils/__init__.py b/optax/tree_utils/__init__.py index e89aef861..44e2e195d 100644 --- a/optax/tree_utils/__init__.py +++ b/optax/tree_utils/__init__.py @@ -17,6 +17,7 @@ # pylint: disable=g-importing-member from optax.tree_utils._casting import tree_cast from optax.tree_utils._random import tree_random_like +from optax.tree_utils._random import tree_split_key_like from optax.tree_utils._state_utils import NamedTupleKey from optax.tree_utils._state_utils import tree_get from optax.tree_utils._state_utils import tree_get_all_with_path diff --git a/optax/tree_utils/_random.py b/optax/tree_utils/_random.py index 33783b2b1..6b4fab307 100644 --- a/optax/tree_utils/_random.py +++ b/optax/tree_utils/_random.py @@ -21,7 +21,7 @@ from jax import tree_util as jtu -def _tree_rng_keys_split( +def tree_split_key_like( rng_key: chex.PRNGKey, target_tree: chex.ArrayTree ) -> chex.ArrayTree: """Split keys to match structure of target tree. @@ -67,7 +67,7 @@ def tree_random_like( .. versionadded:: 0.2.1 """ - keys_tree = _tree_rng_keys_split(rng_key, target_tree) + keys_tree = tree_split_key_like(rng_key, target_tree) return jtu.tree_map( lambda l, k: sampler(k, l.shape, dtype or l.dtype), target_tree,
diff --git a/optax/tree_utils/_random_test.py b/optax/tree_utils/_random_test.py index 25ea580aa..077ca678a 100644 --- a/optax/tree_utils/_random_test.py +++ b/optax/tree_utils/_random_test.py @@ -22,6 +22,7 @@ import jax.numpy as jnp import jax.random as jrd import jax.tree_util as jtu +import numpy as np from optax import tree_utils as otu # We consider samplers with varying input dtypes, we do not test all possible @@ -48,6 +49,19 @@ def get_variable(type_var: str): class RandomTest(chex.TestCase): + def test_tree_split_key_like(self): + rng_key = jrd.PRNGKey(0) + tree = {'a': jnp.zeros(2), 'b': {'c': [jnp.ones(3), jnp.zeros([4, 5])]}} + keys_tree = otu.tree_split_key_like(rng_key, tree) + + with self.subTest('Test structure matches'): + self.assertEqual(jtu.tree_structure(tree), jtu.tree_structure(keys_tree)) + + with self.subTest('Test random key split'): + fst = jnp.stack(jtu.tree_flatten(keys_tree)[0]) + snd = jrd.split(rng_key, jtu.tree_structure(tree).num_leaves) + np.testing.assert_array_equal(fst, snd) + @parameterized.product( _SAMPLER_DTYPES, type_var=['real_array', 'complex_array', 'pytree'],
diff --git a/docs/api/utilities.rst b/docs/api/utilities.rst index b199697f6..c792944fd 100644 --- a/docs/api/utilities.rst +++ b/docs/api/utilities.rst @@ -101,6 +101,7 @@ Tree tree_mul tree_ones_like tree_random_like + tree_split_key_like tree_scalar_mul tree_set tree_sub @@ -153,6 +154,10 @@ Tree ones like ~~~~~~~~~~~~~~ .. autofunction:: tree_ones_like +Tree with random keys +~~~~~~~~~~~~~~~~~~~~~~~ +.. autofunction:: tree_split_key_like + Tree with random values ~~~~~~~~~~~~~~~~~~~~~~~ .. autofunction:: tree_random_like
[ { "components": [ { "doc": "Split keys to match structure of target tree.\n\nArgs:\n rng_key: the key to split.\n target_tree: the tree whose structure to match.\n\nReturns:\n a tree of rng keys.", "lines": [ 24, 38 ], "name": "tree_split_key_like", "signature": "def tree_split_key_like( rng_key: chex.PRNGKey, target_tree: chex.ArrayTree ) -> chex.ArrayTree:", "type": "function" } ], "file": "optax/tree_utils/_random.py" } ]
[ "optax/tree_utils/_random_test.py::RandomTest::test_tree_split_key_like" ]
[ "optax/tree_utils/_random_test.py::RandomTest::test_tree_random_like0", "optax/tree_utils/_random_test.py::RandomTest::test_tree_random_like1", "optax/tree_utils/_random_test.py::RandomTest::test_tree_random_like10", "optax/tree_utils/_random_test.py::RandomTest::test_tree_random_like11", "optax/tree_utils/_random_test.py::RandomTest::test_tree_random_like12", "optax/tree_utils/_random_test.py::RandomTest::test_tree_random_like13", "optax/tree_utils/_random_test.py::RandomTest::test_tree_random_like14", "optax/tree_utils/_random_test.py::RandomTest::test_tree_random_like2", "optax/tree_utils/_random_test.py::RandomTest::test_tree_random_like3", "optax/tree_utils/_random_test.py::RandomTest::test_tree_random_like4", "optax/tree_utils/_random_test.py::RandomTest::test_tree_random_like5", "optax/tree_utils/_random_test.py::RandomTest::test_tree_random_like6", "optax/tree_utils/_random_test.py::RandomTest::test_tree_random_like7", "optax/tree_utils/_random_test.py::RandomTest::test_tree_random_like8", "optax/tree_utils/_random_test.py::RandomTest::test_tree_random_like9" ]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> Add optax.tree_utils.tree_random_split. This exposes the formerly private function `_tree_rng_keys_split` in [`optax/tree_utils/_random.py`](https://github.com/google-deepmind/optax/blob/main/optax/tree_utils/_random.py) to the public API. I've found this to be a useful helper function for manipulation of random trees, and intend to use it for future PRs. ---------- Thanks for doing that, it's a good idea, happy to know it can be useful. (sorry for the incremental review, didn't mean to do it like that). </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in optax/tree_utils/_random.py] (definition of tree_split_key_like:) def tree_split_key_like( rng_key: chex.PRNGKey, target_tree: chex.ArrayTree ) -> chex.ArrayTree: """Split keys to match structure of target tree. Args: rng_key: the key to split. target_tree: the tree whose structure to match. Returns: a tree of rng keys.""" [end of new definitions in optax/tree_utils/_random.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
1e08bccf195ac54e7d9d766eb5e69345bf0e3230
lark-parser__lark-1467
1,467
lark-parser/lark
null
5faea9223cc54d1dbd0985cf830d05a10a7729ec
2024-09-11T20:10:22Z
diff --git a/.gitignore b/.gitignore index 26275e4b..d4e64180 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,7 @@ *.pyc *.pyo /.tox +/lark.egg-info/** /lark_parser.egg-info/** tags .vscode diff --git a/lark/tree.py b/lark/tree.py index 76f8738e..9dccadd7 100644 --- a/lark/tree.py +++ b/lark/tree.py @@ -3,8 +3,10 @@ from typing import List, Callable, Iterator, Union, Optional, Generic, TypeVar, TYPE_CHECKING +from .lexer import Token + if TYPE_CHECKING: - from .lexer import TerminalDef, Token + from .lexer import TerminalDef try: import rich except ImportError: @@ -171,6 +173,16 @@ def find_data(self, data: str) -> 'Iterator[Tree[_Leaf_T]]': ###} + def find_token(self, token_type: str) -> Iterator[_Leaf_T]: + """Returns all tokens whose type equals the given token_type. + + This is a recursive function that will find tokens in all the subtrees. + + Example: + >>> term_tokens = tree.find_token('TERM') + """ + return self.scan_values(lambda v: isinstance(v, Token) and v.type == token_type) + def expand_kids_by_data(self, *data_values): """Expand (inline) children with any of the given data values. Returns True if anything changed""" changed = False
diff --git a/tests/test_trees.py b/tests/test_trees.py index 1f69869e..55fdae91 100644 --- a/tests/test_trees.py +++ b/tests/test_trees.py @@ -17,6 +17,11 @@ class TestTrees(TestCase): def setUp(self): self.tree1 = Tree('a', [Tree(x, y) for x, y in zip('bcd', 'xyz')]) + self.tree2 = Tree('a', [ + Tree('b', [Token('T', 'x')]), + Tree('c', [Token('T', 'y')]), + Tree('d', [Tree('z', [Token('T', 'zz'), Tree('zzz', 'zzz')])]), + ]) def test_eq(self): assert self.tree1 == self.tree1 @@ -48,6 +53,11 @@ def test_iter_subtrees_topdown(self): nodes = list(self.tree1.iter_subtrees_topdown()) self.assertEqual(nodes, expected) + def test_find_token(self): + expected = [Token('T', 'x'), Token('T', 'y'), Token('T', 'zz')] + tokens = list(self.tree2.find_token('T')) + self.assertEqual(tokens, expected) + def test_visitor(self): class Visitor1(Visitor): def __init__(self):
diff --git a/.gitignore b/.gitignore index 26275e4b..d4e64180 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,7 @@ *.pyc *.pyo /.tox +/lark.egg-info/** /lark_parser.egg-info/** tags .vscode
[ { "components": [ { "doc": "Returns all tokens whose type equals the given token_type.\n\nThis is a recursive function that will find tokens in all the subtrees.\n\nExample:\n >>> term_tokens = tree.find_token('TERM')", "lines": [ 176, 184 ], "name": "Tree.find_token", "signature": "def find_token(self, token_type: str) -> Iterator[_Leaf_T]:", "type": "function" } ], "file": "lark/tree.py" } ]
[ "tests/test_trees.py::TestTrees::test_find_token" ]
[ "tests/test_trees.py::TestTrees::test_copy", "tests/test_trees.py::TestTrees::test_deepcopy", "tests/test_trees.py::TestTrees::test_discard", "tests/test_trees.py::TestTrees::test_eq", "tests/test_trees.py::TestTrees::test_inline_static", "tests/test_trees.py::TestTrees::test_interp", "tests/test_trees.py::TestTrees::test_iter_subtrees", "tests/test_trees.py::TestTrees::test_iter_subtrees_topdown", "tests/test_trees.py::TestTrees::test_merge_transformers", "tests/test_trees.py::TestTrees::test_partial", "tests/test_trees.py::TestTrees::test_pickle", "tests/test_trees.py::TestTrees::test_repr_runnable", "tests/test_trees.py::TestTrees::test_smart_decorator", "tests/test_trees.py::TestTrees::test_transform_token", "tests/test_trees.py::TestTrees::test_transformer", "tests/test_trees.py::TestTrees::test_transformer_variants", "tests/test_trees.py::TestTrees::test_vargs", "tests/test_trees.py::TestTrees::test_vargs_override", "tests/test_trees.py::TestTrees::test_vargs_set_name", "tests/test_trees.py::TestTrees::test_visitor" ]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> Add Tree.find_token() method Resolves #1466. ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in lark/tree.py] (definition of Tree.find_token:) def find_token(self, token_type: str) -> Iterator[_Leaf_T]: """Returns all tokens whose type equals the given token_type. This is a recursive function that will find tokens in all the subtrees. Example: >>> term_tokens = tree.find_token('TERM')""" [end of new definitions in lark/tree.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
Here is the discussion in the issues of the pull request. <issues> Syntactic sugar: Tree.find_token() **Suggestion** Add new method `Tree.find_type(typ: str) -> Iterator[Token]` as a companion for `Tree.find_data()`: ```python for term in tree.find_type('TERM'): ... ``` **Describe alternatives you've considered** Right now this can be achieved by ```python for term in tree.find_pred(lambda node: isinstance(node, Token) and node.type == 'TERM'): ... ``` which doesn't fit Black's line width and will look even uglier in real cases. **Additional context** I can provide PR if you find this enhancement reasonable. The method proposed seems to be a logical extension of existing API: ``` Tree => find_data() Token => find_type() ``` ---------- Sorry for bothering, just started using Lark, and see missing pieces (as of my taste). Handy API already made many packages super-popular (like click, requests etc.) Actually you need to use `scan_values()` But, yeah, I think that's a good one to add. But let's call it find_token -------------------- </issues>
5faea9223cc54d1dbd0985cf830d05a10a7729ec
tobymao__sqlglot-4084
4,084
tobymao/sqlglot
null
dbb1ddef53e76ee51a1cf6a24a1de854a69c6093
2024-09-07T18:28:31Z
diff --git a/sqlglot/__init__.py b/sqlglot/__init__.py index e272b9f1c5..f3e97f01b1 100644 --- a/sqlglot/__init__.py +++ b/sqlglot/__init__.py @@ -32,6 +32,7 @@ func as func, intersect as intersect, maybe_parse as maybe_parse, + merge as merge, not_ as not_, or_ as or_, select as select, diff --git a/sqlglot/expressions.py b/sqlglot/expressions.py index ac48541c15..6bbd0fb4fa 100644 --- a/sqlglot/expressions.py +++ b/sqlglot/expressions.py @@ -6885,6 +6885,49 @@ def insert( return insert +def merge( + *when_exprs: ExpOrStr, + into: ExpOrStr, + using: ExpOrStr, + on: ExpOrStr, + dialect: DialectType = None, + copy: bool = True, + **opts, +) -> Merge: + """ + Builds a MERGE statement. + + Example: + >>> merge("WHEN MATCHED THEN UPDATE SET col1 = source_table.col1", + ... "WHEN NOT MATCHED THEN INSERT (col1) VALUES (source_table.col1)", + ... into="my_table", + ... using="source_table", + ... on="my_table.id = source_table.id").sql() + 'MERGE INTO my_table USING source_table ON my_table.id = source_table.id WHEN MATCHED THEN UPDATE SET col1 = source_table.col1 WHEN NOT MATCHED THEN INSERT (col1) VALUES (source_table.col1)' + + Args: + *when_exprs: The WHEN clauses specifying actions for matched and unmatched rows. + into: The target table to merge data into. + using: The source table to merge data from. + on: The join condition for the merge. + dialect: The dialect used to parse the input expressions. + copy: Whether to copy the expression. + **opts: Other options to use to parse the input expressions. + + Returns: + Merge: The syntax tree for the MERGE statement. + """ + return Merge( + this=maybe_parse(into, dialect=dialect, copy=copy, **opts), + using=maybe_parse(using, dialect=dialect, copy=copy, **opts), + on=maybe_parse(on, dialect=dialect, copy=copy, **opts), + expressions=[ + maybe_parse(when_expr, dialect=dialect, copy=copy, into=When, **opts) + for when_expr in when_exprs + ], + ) + + def condition( expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts ) -> Condition:
diff --git a/tests/test_build.py b/tests/test_build.py index e074fea119..d169530461 100644 --- a/tests/test_build.py +++ b/tests/test_build.py @@ -731,6 +731,36 @@ def test_build(self): lambda: exp.rename_column("table1", "c1", "c2"), "ALTER TABLE table1 RENAME COLUMN c1 TO c2", ), + ( + lambda: exp.merge( + "WHEN MATCHED THEN UPDATE SET col1 = source.col1", + "WHEN NOT MATCHED THEN INSERT (col1) VALUES (source.col1)", + into="target_table", + using="source_table", + on="target_table.id = source_table.id", + ), + "MERGE INTO target_table USING source_table ON target_table.id = source_table.id WHEN MATCHED THEN UPDATE SET col1 = source.col1 WHEN NOT MATCHED THEN INSERT (col1) VALUES (source.col1)", + ), + ( + lambda: exp.merge( + "WHEN MATCHED AND source.is_deleted = 1 THEN DELETE", + "WHEN MATCHED THEN UPDATE SET val = source.val", + "WHEN NOT MATCHED THEN INSERT (id, val) VALUES (source.id, source.val)", + into="target_table", + using="source_table", + on="target_table.id = source_table.id", + ), + "MERGE INTO target_table USING source_table ON target_table.id = source_table.id WHEN MATCHED AND source.is_deleted = 1 THEN DELETE WHEN MATCHED THEN UPDATE SET val = source.val WHEN NOT MATCHED THEN INSERT (id, val) VALUES (source.id, source.val)", + ), + ( + lambda: exp.merge( + "WHEN MATCHED THEN UPDATE SET target.name = source.name", + into=exp.table_("target_table").as_("target"), + using=exp.table_("source_table").as_("source"), + on="target.id = source.id", + ), + "MERGE INTO target_table AS target USING source_table AS source ON target.id = source.id WHEN MATCHED THEN UPDATE SET target.name = source.name", + ), ]: with self.subTest(sql): self.assertEqual(expression().sql(dialect[0] if dialect else None), sql)
[ { "components": [ { "doc": "Builds a MERGE statement.\n\nExample:\n >>> merge(\"WHEN MATCHED THEN UPDATE SET col1 = source_table.col1\",\n ... \"WHEN NOT MATCHED THEN INSERT (col1) VALUES (source_table.col1)\",\n ... into=\"my_table\",\n ... using=\"source_table\",\n ... on=\"my_table.id = source_table.id\").sql()\n 'MERGE INTO my_table USING source_table ON my_table.id = source_table.id WHEN MATCHED THEN UPDATE SET col1 = source_table.col1 WHEN NOT MATCHED THEN INSERT (col1) VALUES (source_table.col1)'\n\nArgs:\n *when_exprs: The WHEN clauses specifying actions for matched and unmatched rows.\n into: The target table to merge data into.\n using: The source table to merge data from.\n on: The join condition for the merge.\n dialect: The dialect used to parse the input expressions.\n copy: Whether to copy the expression.\n **opts: Other options to use to parse the input expressions.\n\nReturns:\n Merge: The syntax tree for the MERGE statement.", "lines": [ 6888, 6926 ], "name": "merge", "signature": "def merge( *when_exprs: ExpOrStr, into: ExpOrStr, using: ExpOrStr, on: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts, ) -> Merge:", "type": "function" } ], "file": "sqlglot/expressions.py" } ]
[ "tests/test_build.py::TestBuild::test_build" ]
[]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> Feat: add merge expression builder I have a use-case around building merge statements similar to variety of other types of expressions that sqlglot can programmatically build. This PR adds a simple `merge` function allowing for dynamic construction of merge statements. ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in sqlglot/expressions.py] (definition of merge:) def merge( *when_exprs: ExpOrStr, into: ExpOrStr, using: ExpOrStr, on: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts, ) -> Merge: """Builds a MERGE statement. Example: >>> merge("WHEN MATCHED THEN UPDATE SET col1 = source_table.col1", ... "WHEN NOT MATCHED THEN INSERT (col1) VALUES (source_table.col1)", ... into="my_table", ... using="source_table", ... on="my_table.id = source_table.id").sql() 'MERGE INTO my_table USING source_table ON my_table.id = source_table.id WHEN MATCHED THEN UPDATE SET col1 = source_table.col1 WHEN NOT MATCHED THEN INSERT (col1) VALUES (source_table.col1)' Args: *when_exprs: The WHEN clauses specifying actions for matched and unmatched rows. into: The target table to merge data into. using: The source table to merge data from. on: The join condition for the merge. dialect: The dialect used to parse the input expressions. copy: Whether to copy the expression. **opts: Other options to use to parse the input expressions. Returns: Merge: The syntax tree for the MERGE statement.""" [end of new definitions in sqlglot/expressions.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
ceb42fabad60312699e4b15936aeebac00e22e4d
deepset-ai__haystack-8336
8,336
deepset-ai/haystack
null
5514676b5ecea45c5b93da75bfa271059f89197d
2024-09-05T20:21:06Z
diff --git a/haystack/components/preprocessors/document_splitter.py b/haystack/components/preprocessors/document_splitter.py index c0c39ea82f..556878a965 100644 --- a/haystack/components/preprocessors/document_splitter.py +++ b/haystack/components/preprocessors/document_splitter.py @@ -3,11 +3,13 @@ # SPDX-License-Identifier: Apache-2.0 from copy import deepcopy -from typing import Dict, List, Literal, Tuple +from typing import Any, Callable, Dict, List, Literal, Optional, Tuple from more_itertools import windowed from haystack import Document, component +from haystack.core.serialization import default_from_dict, default_to_dict +from haystack.utils import deserialize_callable, serialize_callable @component @@ -46,10 +48,11 @@ class DocumentSplitter: def __init__( self, - split_by: Literal["word", "sentence", "page", "passage"] = "word", + split_by: Literal["function", "page", "passage", "sentence", "word"] = "word", split_length: int = 200, split_overlap: int = 0, split_threshold: int = 0, + splitting_function: Optional[Callable[[str], List[str]]] = None, ): """ Initialize DocumentSplitter. @@ -61,11 +64,16 @@ def __init__( :param split_overlap: The number of overlapping units for each split. :param split_threshold: The minimum number of units per split. If a split has fewer units than the threshold, it's attached to the previous split. + :param splitting_function: Necessary when `split_by` is set to "function". + This is a function which must accept a single `str` as input and return a `list` of `str` as output, + representing the chunks after splitting. """ self.split_by = split_by - if split_by not in ["word", "sentence", "page", "passage"]: + if split_by not in ["function", "page", "passage", "sentence", "word"]: raise ValueError("split_by must be one of 'word', 'sentence', 'page' or 'passage'.") + if split_by == "function" and splitting_function is None: + raise ValueError("When 'split_by' is set to 'function', a valid 'splitting_function' must be provided.") if split_length <= 0: raise ValueError("split_length must be greater than 0.") self.split_length = split_length @@ -73,6 +81,7 @@ def __init__( raise ValueError("split_overlap must be greater than or equal to 0.") self.split_overlap = split_overlap self.split_threshold = split_threshold + self.splitting_function = splitting_function @component.output_types(documents=List[Document]) def run(self, documents: List[Document]): @@ -114,7 +123,9 @@ def run(self, documents: List[Document]): ) return {"documents": split_docs} - def _split_into_units(self, text: str, split_by: Literal["word", "sentence", "passage", "page"]) -> List[str]: + def _split_into_units( + self, text: str, split_by: Literal["function", "page", "passage", "sentence", "word"] + ) -> List[str]: if split_by == "page": self.split_at = "\f" elif split_by == "passage": @@ -123,9 +134,11 @@ def _split_into_units(self, text: str, split_by: Literal["word", "sentence", "pa self.split_at = "." elif split_by == "word": self.split_at = " " + elif split_by == "function" and self.splitting_function is not None: + return self.splitting_function(text) else: raise NotImplementedError( - "DocumentSplitter only supports 'word', 'sentence', 'page' or 'passage' split_by options." + "DocumentSplitter only supports 'function', 'page', 'passage', 'sentence' or 'word' split_by options." ) units = text.split(self.split_at) # Add the delimiter back to all units except the last one @@ -232,3 +245,31 @@ def _add_split_overlap_information( # add split overlap information to previous Document regarding this Document overlapping_range = (0, overlapping_range[1] - overlapping_range[0]) previous_doc.meta["_split_overlap"].append({"doc_id": current_doc.id, "range": overlapping_range}) + + def to_dict(self) -> Dict[str, Any]: + """ + Serializes the component to a dictionary. + """ + serialized = default_to_dict( + self, + split_by=self.split_by, + split_length=self.split_length, + split_overlap=self.split_overlap, + split_threshold=self.split_threshold, + ) + if self.splitting_function: + serialized["init_parameters"]["splitting_function"] = serialize_callable(self.splitting_function) + return serialized + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "DocumentSplitter": + """ + Deserializes the component from a dictionary. + """ + init_params = data.get("init_parameters", {}) + + splitting_function = init_params.get("splitting_function", None) + if splitting_function: + init_params["splitting_function"] = deserialize_callable(splitting_function) + + return default_from_dict(cls, data) diff --git a/releasenotes/notes/feat-documentsplitter-add-split-by-function-77501f439b63bb49.yaml b/releasenotes/notes/feat-documentsplitter-add-split-by-function-77501f439b63bb49.yaml new file mode 100644 index 0000000000..e8b170442a --- /dev/null +++ b/releasenotes/notes/feat-documentsplitter-add-split-by-function-77501f439b63bb49.yaml @@ -0,0 +1,6 @@ +--- +features: + - | + Added the option to use a custom splitting function in DocumentSplitter. The function must accept a string as + input and return a list of strings, representing the split units. To use the feature initialise `DocumentSplitter` + with `split_by="function"` providing the custom splitting function as `splitting_function=custom_function`.
diff --git a/test/components/preprocessors/test_document_splitter.py b/test/components/preprocessors/test_document_splitter.py index d9fa85f005..7c942ab4cc 100644 --- a/test/components/preprocessors/test_document_splitter.py +++ b/test/components/preprocessors/test_document_splitter.py @@ -1,10 +1,18 @@ # SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai> # # SPDX-License-Identifier: Apache-2.0 +import re + import pytest from haystack import Document from haystack.components.preprocessors import DocumentSplitter +from haystack.utils import deserialize_callable, serialize_callable + + +# custom split function for testing +def custom_split(text): + return text.split(".") def merge_documents(documents): @@ -165,6 +173,27 @@ def test_split_by_page(self): assert docs[2].meta["split_idx_start"] == text.index(docs[2].content) assert docs[2].meta["page_number"] == 3 + def test_split_by_function(self): + splitting_function = lambda input_str: input_str.split(".") + splitter = DocumentSplitter(split_by="function", splitting_function=splitting_function, split_length=1) + text = "This.Is.A.Test" + result = splitter.run(documents=[Document(content=text)]) + docs = result["documents"] + + word_list = ["This", "Is", "A", "Test"] + assert len(docs) == 4 + for w_target, w_split in zip(word_list, docs): + assert w_split.content == w_target + + splitting_function = lambda input_str: re.split("[\s]{2,}", input_str) + splitter = DocumentSplitter(split_by="function", splitting_function=splitting_function, split_length=1) + text = "This Is\n A Test" + result = splitter.run(documents=[Document(content=text)]) + docs = result["documents"] + assert len(docs) == 4 + for w_target, w_split in zip(word_list, docs): + assert w_split.content == w_target + def test_split_by_word_with_overlap(self): splitter = DocumentSplitter(split_by="word", split_length=10, split_overlap=2) text = "This is a text with some words. There is a second sentence. And there is a third sentence." @@ -329,3 +358,90 @@ def test_add_split_overlap_information(self): # reconstruct the original document content from the split documents assert doc.content == merge_documents(docs) + + def test_to_dict(self): + """ + Test the to_dict method of the DocumentSplitter class. + """ + splitter = DocumentSplitter(split_by="word", split_length=10, split_overlap=2, split_threshold=5) + serialized = splitter.to_dict() + + assert serialized["type"] == "haystack.components.preprocessors.document_splitter.DocumentSplitter" + assert serialized["init_parameters"]["split_by"] == "word" + assert serialized["init_parameters"]["split_length"] == 10 + assert serialized["init_parameters"]["split_overlap"] == 2 + assert serialized["init_parameters"]["split_threshold"] == 5 + assert "splitting_function" not in serialized["init_parameters"] + + def test_to_dict_with_splitting_function(self): + """ + Test the to_dict method of the DocumentSplitter class when a custom splitting function is provided. + """ + + splitter = DocumentSplitter(split_by="function", splitting_function=custom_split) + serialized = splitter.to_dict() + + assert serialized["type"] == "haystack.components.preprocessors.document_splitter.DocumentSplitter" + assert serialized["init_parameters"]["split_by"] == "function" + assert "splitting_function" in serialized["init_parameters"] + assert callable(deserialize_callable(serialized["init_parameters"]["splitting_function"])) + + def test_from_dict(self): + """ + Test the from_dict class method of the DocumentSplitter class. + """ + data = { + "type": "haystack.components.preprocessors.document_splitter.DocumentSplitter", + "init_parameters": {"split_by": "word", "split_length": 10, "split_overlap": 2, "split_threshold": 5}, + } + splitter = DocumentSplitter.from_dict(data) + + assert splitter.split_by == "word" + assert splitter.split_length == 10 + assert splitter.split_overlap == 2 + assert splitter.split_threshold == 5 + assert splitter.splitting_function is None + + def test_from_dict_with_splitting_function(self): + """ + Test the from_dict class method of the DocumentSplitter class when a custom splitting function is provided. + """ + + def custom_split(text): + return text.split(".") + + data = { + "type": "haystack.components.preprocessors.document_splitter.DocumentSplitter", + "init_parameters": {"split_by": "function", "splitting_function": serialize_callable(custom_split)}, + } + splitter = DocumentSplitter.from_dict(data) + + assert splitter.split_by == "function" + assert callable(splitter.splitting_function) + assert splitter.splitting_function("a.b.c") == ["a", "b", "c"] + + def test_roundtrip_serialization(self): + """ + Test the round-trip serialization of the DocumentSplitter class. + """ + original_splitter = DocumentSplitter(split_by="word", split_length=10, split_overlap=2, split_threshold=5) + serialized = original_splitter.to_dict() + deserialized_splitter = DocumentSplitter.from_dict(serialized) + + assert original_splitter.split_by == deserialized_splitter.split_by + assert original_splitter.split_length == deserialized_splitter.split_length + assert original_splitter.split_overlap == deserialized_splitter.split_overlap + assert original_splitter.split_threshold == deserialized_splitter.split_threshold + + def test_roundtrip_serialization_with_splitting_function(self): + """ + Test the round-trip serialization of the DocumentSplitter class when a custom splitting function is provided. + """ + + original_splitter = DocumentSplitter(split_by="function", splitting_function=custom_split) + serialized = original_splitter.to_dict() + deserialized_splitter = DocumentSplitter.from_dict(serialized) + + assert original_splitter.split_by == deserialized_splitter.split_by + assert callable(deserialized_splitter.splitting_function) + assert deserialized_splitter.splitting_function("a.b.c") == ["a", "b", "c"]
diff --git a/releasenotes/notes/feat-documentsplitter-add-split-by-function-77501f439b63bb49.yaml b/releasenotes/notes/feat-documentsplitter-add-split-by-function-77501f439b63bb49.yaml new file mode 100644 index 0000000000..e8b170442a --- /dev/null +++ b/releasenotes/notes/feat-documentsplitter-add-split-by-function-77501f439b63bb49.yaml @@ -0,0 +1,6 @@ +--- +features: + - | + Added the option to use a custom splitting function in DocumentSplitter. The function must accept a string as + input and return a list of strings, representing the split units. To use the feature initialise `DocumentSplitter` + with `split_by="function"` providing the custom splitting function as `splitting_function=custom_function`.
[ { "components": [ { "doc": "Serializes the component to a dictionary.", "lines": [ 249, 262 ], "name": "DocumentSplitter.to_dict", "signature": "def to_dict(self) -> Dict[str, Any]:", "type": "function" }, { "doc": "Deserializes the component from a dictionary.", "lines": [ 265, 275 ], "name": "DocumentSplitter.from_dict", "signature": "def from_dict(cls, data: Dict[str, Any]) -> \"DocumentSplitter\":", "type": "function" } ], "file": "haystack/components/preprocessors/document_splitter.py" } ]
[ "test/components/preprocessors/test_document_splitter.py::TestDocumentSplitter::test_split_by_function", "test/components/preprocessors/test_document_splitter.py::TestDocumentSplitter::test_to_dict", "test/components/preprocessors/test_document_splitter.py::TestDocumentSplitter::test_to_dict_with_splitting_function", "test/components/preprocessors/test_document_splitter.py::TestDocumentSplitter::test_from_dict", "test/components/preprocessors/test_document_splitter.py::TestDocumentSplitter::test_from_dict_with_splitting_function", "test/components/preprocessors/test_document_splitter.py::TestDocumentSplitter::test_roundtrip_serialization", "test/components/preprocessors/test_document_splitter.py::TestDocumentSplitter::test_roundtrip_serialization_with_splitting_function" ]
[ "test/components/preprocessors/test_document_splitter.py::TestDocumentSplitter::test_non_text_document", "test/components/preprocessors/test_document_splitter.py::TestDocumentSplitter::test_single_doc", "test/components/preprocessors/test_document_splitter.py::TestDocumentSplitter::test_empty_list", "test/components/preprocessors/test_document_splitter.py::TestDocumentSplitter::test_unsupported_split_by", "test/components/preprocessors/test_document_splitter.py::TestDocumentSplitter::test_unsupported_split_length", "test/components/preprocessors/test_document_splitter.py::TestDocumentSplitter::test_unsupported_split_overlap", "test/components/preprocessors/test_document_splitter.py::TestDocumentSplitter::test_split_by_word", "test/components/preprocessors/test_document_splitter.py::TestDocumentSplitter::test_split_by_word_with_threshold", "test/components/preprocessors/test_document_splitter.py::TestDocumentSplitter::test_split_by_word_multiple_input_docs", "test/components/preprocessors/test_document_splitter.py::TestDocumentSplitter::test_split_by_sentence", "test/components/preprocessors/test_document_splitter.py::TestDocumentSplitter::test_split_by_passage", "test/components/preprocessors/test_document_splitter.py::TestDocumentSplitter::test_split_by_page", "test/components/preprocessors/test_document_splitter.py::TestDocumentSplitter::test_split_by_word_with_overlap", "test/components/preprocessors/test_document_splitter.py::TestDocumentSplitter::test_source_id_stored_in_metadata", "test/components/preprocessors/test_document_splitter.py::TestDocumentSplitter::test_copy_metadata", "test/components/preprocessors/test_document_splitter.py::TestDocumentSplitter::test_add_page_number_to_metadata_with_no_overlap_word_split", "test/components/preprocessors/test_document_splitter.py::TestDocumentSplitter::test_add_page_number_to_metadata_with_no_overlap_sentence_split", "test/components/preprocessors/test_document_splitter.py::TestDocumentSplitter::test_add_page_number_to_metadata_with_no_overlap_passage_split", "test/components/preprocessors/test_document_splitter.py::TestDocumentSplitter::test_add_page_number_to_metadata_with_no_overlap_page_split", "test/components/preprocessors/test_document_splitter.py::TestDocumentSplitter::test_add_page_number_to_metadata_with_overlap_word_split", "test/components/preprocessors/test_document_splitter.py::TestDocumentSplitter::test_add_page_number_to_metadata_with_overlap_sentence_split", "test/components/preprocessors/test_document_splitter.py::TestDocumentSplitter::test_add_page_number_to_metadata_with_overlap_passage_split", "test/components/preprocessors/test_document_splitter.py::TestDocumentSplitter::test_add_page_number_to_metadata_with_overlap_page_split", "test/components/preprocessors/test_document_splitter.py::TestDocumentSplitter::test_add_split_overlap_information" ]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> feat : DocumentSplitter, adding the option to split_by function ### Proposed Changes: Adding the possibility to pass a function and personalise the way in which DocumentSplitter defines a unit. This means a user can, for example, use the following to split and define units: `splitter_function = lambda text: re.split('[\n]{2,}, text)` (or use spacy or anything else). ### How did you test it? Added two tests with two "mock" splitter functions. ### Notes for the reviewer There are some issues related to document splitting #5922 . Given the fact that the current methods are very basic and the issues have been open for moths, I think it would make sense to let the user define how text is split. ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in haystack/components/preprocessors/document_splitter.py] (definition of DocumentSplitter.to_dict:) def to_dict(self) -> Dict[str, Any]: """Serializes the component to a dictionary.""" (definition of DocumentSplitter.from_dict:) def from_dict(cls, data: Dict[str, Any]) -> "DocumentSplitter": """Deserializes the component from a dictionary.""" [end of new definitions in haystack/components/preprocessors/document_splitter.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
f4d9c2bb917be0ffe132dffcc2ad4f1b0fcc5967
tobymao__sqlglot-3991
3,991
tobymao/sqlglot
null
f5bfd67341518d0ecb1c3693e0b41ed5c1cf0596
2024-08-28T13:44:49Z
diff --git a/sqlglot/dialects/hive.py b/sqlglot/dialects/hive.py index 990991357e..d428db71ba 100644 --- a/sqlglot/dialects/hive.py +++ b/sqlglot/dialects/hive.py @@ -436,6 +436,14 @@ def _parse_parameter(self) -> exp.Parameter: self._match(TokenType.R_BRACE) return self.expression(exp.Parameter, this=this, expression=expression) + def _to_prop_eq(self, expression: exp.Expression, index: int) -> exp.Expression: + if isinstance(expression, exp.Column): + key = expression.this + else: + key = exp.to_identifier(f"col{index + 1}") + + return self.expression(exp.PropertyEQ, this=key, expression=expression) + class Generator(generator.Generator): LIMIT_FETCH = "LIMIT" TABLESAMPLE_WITH_METHOD = False diff --git a/sqlglot/parser.py b/sqlglot/parser.py index 17d5de3d8b..81e06ba926 100644 --- a/sqlglot/parser.py +++ b/sqlglot/parser.py @@ -5112,10 +5112,13 @@ def _parse_function_call( self._match_r_paren(this) return self._parse_window(this) + def _to_prop_eq(self, expression: exp.Expression, index: int) -> exp.Expression: + return expression + def _kv_to_prop_eq(self, expressions: t.List[exp.Expression]) -> t.List[exp.Expression]: transformed = [] - for e in expressions: + for index, e in enumerate(expressions): if isinstance(e, self.KEY_VALUE_DEFINITIONS): if isinstance(e, exp.Alias): e = self.expression(exp.PropertyEQ, this=e.args.get("alias"), expression=e.this) @@ -5127,6 +5130,8 @@ def _kv_to_prop_eq(self, expressions: t.List[exp.Expression]) -> t.List[exp.Expr if isinstance(e.this, exp.Column): e.this.replace(e.this.this) + else: + e = self._to_prop_eq(e, index) transformed.append(e)
diff --git a/tests/dialects/test_presto.py b/tests/dialects/test_presto.py index 950c89f82d..173d16eb80 100644 --- a/tests/dialects/test_presto.py +++ b/tests/dialects/test_presto.py @@ -715,9 +715,6 @@ def test_presto(self): ) self.validate_all( "SELECT ROW(1, 2)", - read={ - "spark": "SELECT STRUCT(1, 2)", - }, write={ "presto": "SELECT ROW(1, 2)", "spark": "SELECT STRUCT(1, 2)", diff --git a/tests/dialects/test_spark.py b/tests/dialects/test_spark.py index c9b7897429..cbaa169af9 100644 --- a/tests/dialects/test_spark.py +++ b/tests/dialects/test_spark.py @@ -485,7 +485,7 @@ def test_spark(self): ) self.validate_all( "SELECT CAST(STRUCT('fooo') AS STRUCT<a: VARCHAR(2)>)", - write={"spark": "SELECT CAST(STRUCT('fooo') AS STRUCT<a: STRING>)"}, + write={"spark": "SELECT CAST(STRUCT('fooo' AS col1) AS STRUCT<a: STRING>)"}, ) self.validate_all( "SELECT CAST(123456 AS VARCHAR(3))", @@ -718,6 +718,22 @@ def test_spark(self): }, ) + self.validate_all( + "SELECT STRUCT(1, 2)", + write={ + "spark": "SELECT STRUCT(1 AS col1, 2 AS col2)", + "presto": "SELECT CAST(ROW(1, 2) AS ROW(col1 INTEGER, col2 INTEGER))", + "duckdb": "SELECT {'col1': 1, 'col2': 2}", + }, + ) + self.validate_all( + "SELECT STRUCT(x, 1, y AS col3, STRUCT(5)) FROM t", + write={ + "spark": "SELECT STRUCT(x AS x, 1 AS col2, y AS col3, STRUCT(5 AS col1) AS col4) FROM t", + "duckdb": "SELECT {'x': x, 'col2': 1, 'col3': y, 'col4': {'col1': 5}} FROM t", + }, + ) + def test_bool_or(self): self.validate_all( "SELECT a, LOGICAL_OR(b) FROM table GROUP BY a",
[ { "components": [ { "doc": "", "lines": [ 439, 445 ], "name": "Hive.Parser._to_prop_eq", "signature": "def _to_prop_eq(self, expression: exp.Expression, index: int) -> exp.Expression:", "type": "function" } ], "file": "sqlglot/dialects/hive.py" }, { "components": [ { "doc": "", "lines": [ 5115, 5116 ], "name": "Parser._to_prop_eq", "signature": "def _to_prop_eq(self, expression: exp.Expression, index: int) -> exp.Expression:", "type": "function" } ], "file": "sqlglot/parser.py" } ]
[ "tests/dialects/test_spark.py::TestSpark::test_spark" ]
[ "tests/dialects/test_presto.py::TestPresto::test_cast", "tests/dialects/test_presto.py::TestPresto::test_ddl", "tests/dialects/test_presto.py::TestPresto::test_encode_decode", "tests/dialects/test_presto.py::TestPresto::test_hex_unhex", "tests/dialects/test_presto.py::TestPresto::test_interval_plural_to_singular", "tests/dialects/test_presto.py::TestPresto::test_json", "tests/dialects/test_presto.py::TestPresto::test_json_vs_row_extract", "tests/dialects/test_presto.py::TestPresto::test_match_recognize", "tests/dialects/test_presto.py::TestPresto::test_presto", "tests/dialects/test_presto.py::TestPresto::test_quotes", "tests/dialects/test_presto.py::TestPresto::test_regex", "tests/dialects/test_presto.py::TestPresto::test_signum", "tests/dialects/test_presto.py::TestPresto::test_time", "tests/dialects/test_presto.py::TestPresto::test_to_char", "tests/dialects/test_presto.py::TestPresto::test_unicode_string", "tests/dialects/test_presto.py::TestPresto::test_unnest", "tests/dialects/test_spark.py::TestSpark::test_bool_or", "tests/dialects/test_spark.py::TestSpark::test_current_user", "tests/dialects/test_spark.py::TestSpark::test_ddl", "tests/dialects/test_spark.py::TestSpark::test_explode_to_unnest", "tests/dialects/test_spark.py::TestSpark::test_hint", "tests/dialects/test_spark.py::TestSpark::test_insert_cte", "tests/dialects/test_spark.py::TestSpark::test_minus", "tests/dialects/test_spark.py::TestSpark::test_schema_binding_options", "tests/dialects/test_spark.py::TestSpark::test_strip_modifiers", "tests/dialects/test_spark.py::TestSpark::test_to_date", "tests/dialects/test_spark.py::TestSpark::test_transform_query" ]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> feat(spark): Default naming of STRUCT fields Fixes #3988 In Spark, STRUCT values/fields that are not explicitly named by the user are default initialized to: - The column name itself, if the expression is a column - The name `col_i` for other literals/nested structs, where `i` is the 1-based index position of the field in the struct: ``` spark-sql (default)> WITH t AS (SELECT 1 AS x, 2 AS y) SELECT STRUCT(x, 1, y AS col3, struct(5)) FROM t; {"x":1,"col2":1,"col3":2,"col4":{"col1":5}} ``` This PR extends `kv_to_prop_eq` by also standardizing non-aliased expressions (`exp.Column`, `exp.Literal` etc) to key-value `exp.PropertyEQ` pairs with their respective name. ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in sqlglot/dialects/hive.py] (definition of Hive.Parser._to_prop_eq:) def _to_prop_eq(self, expression: exp.Expression, index: int) -> exp.Expression: [end of new definitions in sqlglot/dialects/hive.py] [start of new definitions in sqlglot/parser.py] (definition of Parser._to_prop_eq:) def _to_prop_eq(self, expression: exp.Expression, index: int) -> exp.Expression: [end of new definitions in sqlglot/parser.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
Here is the discussion in the issues of the pull request. <issues> Incorrect Parsing Between Spark SQL and DuckDB **Fully reproducible code snippet** ```python from sqlglot import parse_one spark_query = "SELECT struct(col1, col2 as col3) FROM table" parse_one(spark_query, dialect="spark").sql(dialect="duckdb") ``` The output is: 'SELECT {\'_0\': col1, \'col3\': col2} FROM "table"' while it should be 'SELECT {\'col1\': col1, \'col3\': col2}' As spark uses the original name for the column if it wasn't aliased ---------- -------------------- </issues>
ceb42fabad60312699e4b15936aeebac00e22e4d
conan-io__conan-16871
16,871
conan-io/conan
null
d99c7149ff64c2dd98b5d9752f5308f8ffd70474
2024-08-25T21:10:13Z
diff --git a/conans/client/graph/build_mode.py b/conans/client/graph/build_mode.py index f7a3cd61f81..8efbd99da3b 100644 --- a/conans/client/graph/build_mode.py +++ b/conans/client/graph/build_mode.py @@ -16,6 +16,8 @@ def __init__(self, params): self.patterns = [] self.build_missing_patterns = [] self._build_missing_excluded = [] + self._build_compatible_patterns = [] + self._build_compatible_excluded = [] self._excluded_patterns = [] if params is None: return @@ -39,6 +41,14 @@ def __init__(self, params): self._build_missing_excluded.append(clean_pattern[1:]) else: self.build_missing_patterns.append(clean_pattern) + elif param == "compatible": + self._build_compatible_patterns = ["*"] + elif param.startswith("compatible:"): + clean_pattern = param[len("compatible:"):] + if clean_pattern and clean_pattern[0] in ["!", "~"]: + self._build_compatible_excluded.append(clean_pattern[1:]) + else: + self._build_compatible_patterns.append(clean_pattern) else: clean_pattern = param if clean_pattern and clean_pattern[0] in ["!", "~"]: @@ -87,8 +97,21 @@ def allowed(self, conan_file): return True if self.should_build_missing(conan_file): return True + if self.allowed_compatible(conan_file): + return True return False + def allowed_compatible(self, conanfile): + if self._build_compatible_excluded: + for pattern in self._build_compatible_excluded: + if ref_matches(conanfile.ref, pattern, is_consumer=False): + return False + return True # If it has not been excluded by the negated patterns, it is included + + for pattern in self._build_compatible_patterns: + if ref_matches(conanfile.ref, pattern, is_consumer=conanfile._conan_is_consumer): + return True + def should_build_missing(self, conanfile): if self._build_missing_excluded: for pattern in self._build_missing_excluded: diff --git a/conans/client/graph/compute_pid.py b/conans/client/graph/compute_pid.py index 2ed1d6a5f4c..5855eafb63e 100644 --- a/conans/client/graph/compute_pid.py +++ b/conans/client/graph/compute_pid.py @@ -58,15 +58,6 @@ def compute_package_id(node, new_config, config_version): config_version=config_version.copy() if config_version else None) conanfile.original_info = conanfile.info.clone() - if hasattr(conanfile, "validate_build"): - with conanfile_exception_formatter(conanfile, "validate_build"): - with conanfile_remove_attr(conanfile, ['cpp_info'], "validate_build"): - try: - conanfile.validate_build() - except ConanInvalidConfiguration as e: - # This 'cant_build' will be ignored if we don't have to build the node. - conanfile.info.cant_build = str(e) - run_validate_package_id(conanfile) if conanfile.info.settings_target: @@ -79,6 +70,15 @@ def compute_package_id(node, new_config, config_version): def run_validate_package_id(conanfile): # IMPORTANT: This validation code must run before calling info.package_id(), to mark "invalid" + if hasattr(conanfile, "validate_build"): + with conanfile_exception_formatter(conanfile, "validate_build"): + with conanfile_remove_attr(conanfile, ['cpp_info'], "validate_build"): + try: + conanfile.validate_build() + except ConanInvalidConfiguration as e: + # This 'cant_build' will be ignored if we don't have to build the node. + conanfile.info.cant_build = str(e) + if hasattr(conanfile, "validate"): with conanfile_exception_formatter(conanfile, "validate"): with conanfile_remove_attr(conanfile, ['cpp_info'], "validate"): diff --git a/conans/client/graph/graph_binaries.py b/conans/client/graph/graph_binaries.py index f10991628e6..cecd9f88efa 100644 --- a/conans/client/graph/graph_binaries.py +++ b/conans/client/graph/graph_binaries.py @@ -21,7 +21,7 @@ from conans.util.files import load -class GraphBinariesAnalyzer(object): +class GraphBinariesAnalyzer: def __init__(self, conan_app, global_conf): self._cache = conan_app.cache @@ -145,7 +145,7 @@ def _find_existing_compatible_binaries(self, node, compatibles, remotes, update) conanfile = node.conanfile original_binary = node.binary original_package_id = node.package_id - + conanfile.output.info(f"Main binary package '{original_package_id}' missing") conanfile.output.info(f"Checking {len(compatibles)} compatible configurations") for package_id, compatible_package in compatibles.items(): if should_update_reference(node.ref, update): @@ -173,24 +173,47 @@ def _find_existing_compatible_binaries(self, node, compatibles, remotes, update) node.binary = original_binary node._package_id = original_package_id + def _find_build_compatible_binary(self, node, compatibles): + original_binary = node.binary + original_package_id = node.package_id + output = node.conanfile.output + output.info(f"Requested binary package '{original_package_id}' invalid, can't be built") + output.info(f"Checking {len(compatibles)} configurations, to build a compatible one, " + f"as requested by '--build=compatible'") + for pkg_id, compatible in compatibles.items(): + if not compatible.cant_build: + node._package_id = pkg_id # Modifying package id under the hood, FIXME + self._compatible_found(node.conanfile, pkg_id, compatible) + node.binary = BINARY_BUILD + return + node.binary = original_binary + node._package_id = original_package_id + def _evaluate_node(self, node, build_mode, remotes, update): assert node.binary is None, "Node.binary should be None" assert node.package_id is not None, "Node.package_id shouldn't be None" assert node.prev is None, "Node.prev should be None" self._process_node(node, build_mode, remotes, update) - original_package_id = node.package_id + compatibles = None + if node.binary == BINARY_MISSING \ and not build_mode.should_build_missing(node.conanfile) and not node.should_build: compatibles = self._get_compatible_packages(node) - node.conanfile.output.info(f"Main binary package '{original_package_id}' missing") - self._find_existing_compatible_binaries(node, compatibles, remotes, update) + if compatibles: + self._find_existing_compatible_binaries(node, compatibles, remotes, update) if node.binary == BINARY_MISSING and build_mode.allowed(node.conanfile): node.should_build = True node.build_allowed = True node.binary = BINARY_BUILD if not node.conanfile.info.cant_build else BINARY_INVALID + if node.binary == BINARY_INVALID and build_mode.allowed_compatible(node.conanfile): + if compatibles is None: + compatibles = self._get_compatible_packages(node) + if compatibles: + self._find_build_compatible_binary(node, compatibles) + if node.binary == BINARY_BUILD: conanfile = node.conanfile if conanfile.vendor and not conanfile.conf.get("tools.graph:vendor", choices=("build",)):
diff --git a/test/integration/package_id/compatible_test.py b/test/integration/package_id/compatible_test.py index 5e27f7816f6..b7719e41711 100644 --- a/test/integration/package_id/compatible_test.py +++ b/test/integration/package_id/compatible_test.py @@ -448,3 +448,173 @@ def test_compatibility_msvc_and_cppstd(self): tc.run("create dep -pr=profile -s compiler.cppstd=20") tc.run("create . -pr=profile -s compiler.cppstd=17") tc.assert_listed_binary({"dep/1.0": ("b6d26a6bc439b25b434113982791edf9cab4d004", "Cache")}) + + +class TestCompatibleBuild: + def test_build_compatible(self): + c = TestClient() + conanfile = textwrap.dedent(""" + from conan import ConanFile + from conan.tools.build import check_min_cppstd + + class Pkg(ConanFile): + name = "pkg" + version = "0.1" + settings = "os", "compiler" + + def validate(self): + check_min_cppstd(self, 14) + """) + c.save({"conanfile.py": conanfile}) + settings = "-s os=Windows -s compiler=gcc -s compiler.version=11 " \ + "-s compiler.libcxx=libstdc++11 -s compiler.cppstd=11" + c.run(f"create . {settings}", assert_error=True) + c.assert_listed_binary({"pkg/0.1": ("bb33db23c961978d08dc0cdd6bc786b45b3e5943", "Invalid")}) + assert "pkg/0.1: Invalid: Current cppstd (11)" in c.out + + c.run(f"create . {settings} --build=compatible:&") + # the one for cppstd=14 is built!! + c.assert_listed_binary({"pkg/0.1": ("389803bed06200476fcee1af2023d4e9bfa24ff9", "Build")}) + c.run("list *:*") + assert "compiler.cppstd: 14" in c.out + + def test_build_compatible_cant_build(self): + # requires c++17 to build, can be consumed with c++14 + c = TestClient() + conanfile = textwrap.dedent(""" + from conan import ConanFile + from conan.tools.build import check_min_cppstd + + class Pkg(ConanFile): + name = "pkg" + version = "0.1" + settings = "os", "compiler" + + def validate(self): + check_min_cppstd(self, 14) + + def validate_build(self): + check_min_cppstd(self, 17) + """) + c.save({"conanfile.py": conanfile}) + settings = "-s os=Windows -s compiler=gcc -s compiler.version=11 " \ + "-s compiler.libcxx=libstdc++11 -s compiler.cppstd=11" + c.run(f"create . {settings}", assert_error=True) + c.assert_listed_binary({"pkg/0.1": ("bb33db23c961978d08dc0cdd6bc786b45b3e5943", "Invalid")}) + assert "pkg/0.1: Invalid: Current cppstd (11)" in c.out + + c.run(f"create . {settings} --build=missing", assert_error=True) + c.assert_listed_binary({"pkg/0.1": ("bb33db23c961978d08dc0cdd6bc786b45b3e5943", "Invalid")}) + assert "pkg/0.1: Invalid: Current cppstd (11)" in c.out + + c.run(f"create . {settings} --build=compatible:&") + # the one for cppstd=17 is built!! + c.assert_listed_binary({"pkg/0.1": ("58fb8ac6c2dc3e3f837253ce1a6ea59011525866", "Build")}) + c.run("list *:*") + assert "compiler.cppstd: 17" in c.out + + def test_build_compatible_cant_build2(self): + # requires c++17 to build, can be consumed with c++11 + c = TestClient() + conanfile = textwrap.dedent(""" + from conan import ConanFile + from conan.tools.build import check_min_cppstd + + class Pkg(ConanFile): + name = "pkg" + version = "0.1" + settings = "os", "compiler" + + def validate(self): + check_min_cppstd(self, 11) + + def validate_build(self): + check_min_cppstd(self, 17) + """) + c.save({"conanfile.py": conanfile}) + settings = "-s os=Windows -s compiler=gcc -s compiler.version=11 " \ + "-s compiler.libcxx=libstdc++11 -s compiler.cppstd=11" + c.run(f"create . {settings}", assert_error=True) + c.assert_listed_binary({"pkg/0.1": ("bb33db23c961978d08dc0cdd6bc786b45b3e5943", "Invalid")}) + assert "pkg/0.1: Cannot build for this configuration: Current cppstd (11)" in c.out + + c.run(f"create . {settings} --build=missing", assert_error=True) + # the one for cppstd=17 is built!! + c.assert_listed_binary({"pkg/0.1": ("bb33db23c961978d08dc0cdd6bc786b45b3e5943", "Invalid")}) + assert "pkg/0.1: Cannot build for this configuration: Current cppstd (11)" in c.out + + c.run(f"create . {settings} --build=compatible:&") + # the one for cppstd=17 is built!! + c.assert_listed_binary({"pkg/0.1": ("58fb8ac6c2dc3e3f837253ce1a6ea59011525866", "Build")}) + c.run("list *:*") + assert "compiler.cppstd: 17" in c.out + + def test_build_compatible_cant_build_only(self): + # requires c++17 to build, but don't specify consumption + c = TestClient() + conanfile = textwrap.dedent(""" + from conan import ConanFile + from conan.tools.build import check_min_cppstd + + class Pkg(ConanFile): + name = "pkg" + version = "0.1" + settings = "os", "compiler" + + def validate_build(self): + check_min_cppstd(self, 17) + """) + c.save({"conanfile.py": conanfile}) + settings = "-s os=Windows -s compiler=gcc -s compiler.version=11 " \ + "-s compiler.libcxx=libstdc++11 -s compiler.cppstd=11" + c.run(f"create . {settings}", assert_error=True) + c.assert_listed_binary({"pkg/0.1": ("bb33db23c961978d08dc0cdd6bc786b45b3e5943", "Invalid")}) + assert "pkg/0.1: Cannot build for this configuration: Current cppstd (11)" in c.out + + c.run(f"create . {settings} --build=missing", assert_error=True) + # the one for cppstd=17 is built!! + c.assert_listed_binary({"pkg/0.1": ("bb33db23c961978d08dc0cdd6bc786b45b3e5943", "Invalid")}) + assert "pkg/0.1: Cannot build for this configuration: Current cppstd (11)" in c.out + + c.run(f"create . {settings} --build=compatible:&") + # the one for cppstd=17 is built!! + c.assert_listed_binary({"pkg/0.1": ("58fb8ac6c2dc3e3f837253ce1a6ea59011525866", "Build")}) + c.run("list *:*") + assert "compiler.cppstd: 17" in c.out + + def test_multi_level_build_compatible(self): + c = TestClient() + conanfile = textwrap.dedent(""" + from conan import ConanFile + from conan.tools.build import check_min_cppstd + + class Pkg(ConanFile): + name = "{name}" + version = "0.1" + settings = "os", "compiler" + {requires} + + def validate(self): + check_min_cppstd(self, {cppstd}) + """) + c.save({"liba/conanfile.py": conanfile.format(name="liba", cppstd=14, requires=""), + "libb/conanfile.py": conanfile.format(name="libb", cppstd=17, + requires='requires="liba/0.1"')}) + c.run("export liba") + c.run("export libb") + settings = "-s os=Windows -s compiler=gcc -s compiler.version=11 " \ + "-s compiler.libcxx=libstdc++11 -s compiler.cppstd=11" + c.run(f"install --requires=libb/0.1 {settings}", assert_error=True) + c.assert_listed_binary({"liba/0.1": ("bb33db23c961978d08dc0cdd6bc786b45b3e5943", "Invalid"), + "libb/0.1": ("144910d65b27bcbf7d544201f5578555bbd0376e", "Invalid")}) + assert "liba/0.1: Invalid: Current cppstd (11)" in c.out + assert "libb/0.1: Invalid: Current cppstd (11)" in c.out + + c.run(f"install --requires=libb/0.1 {settings} --build=compatible") + # the one for cppstd=14 is built!! + c.assert_listed_binary({"liba/0.1": ("389803bed06200476fcee1af2023d4e9bfa24ff9", "Build"), + "libb/0.1": ("8f29f49be3ba2b6cbc9fa1e05432ce928b96ae5d", "Build")}) + c.run("list liba:*") + assert "compiler.cppstd: 14" in c.out + c.run("list libb:*") + assert "compiler.cppstd: 17" in c.out
[ { "components": [ { "doc": "", "lines": [ 104, 113 ], "name": "BuildMode.allowed_compatible", "signature": "def allowed_compatible(self, conanfile):", "type": "function" } ], "file": "conans/client/graph/build_mode.py" }, { "components": [ { "doc": "", "lines": [ 176, 190 ], "name": "GraphBinariesAnalyzer._find_build_compatible_binary", "signature": "def _find_build_compatible_binary(self, node, compatibles):", "type": "function" } ], "file": "conans/client/graph/graph_binaries.py" } ]
[ "test/integration/package_id/compatible_test.py::TestCompatibleBuild::test_build_compatible", "test/integration/package_id/compatible_test.py::TestCompatibleBuild::test_build_compatible_cant_build", "test/integration/package_id/compatible_test.py::TestCompatibleBuild::test_build_compatible_cant_build2", "test/integration/package_id/compatible_test.py::TestCompatibleBuild::test_build_compatible_cant_build_only", "test/integration/package_id/compatible_test.py::TestCompatibleBuild::test_multi_level_build_compatible" ]
[ "test/integration/package_id/compatible_test.py::CompatibleIDsTest::test_build_missing", "test/integration/package_id/compatible_test.py::CompatibleIDsTest::test_compatible_diamond", "test/integration/package_id/compatible_test.py::CompatibleIDsTest::test_compatible_lockfile", "test/integration/package_id/compatible_test.py::CompatibleIDsTest::test_compatible_option", "test/integration/package_id/compatible_test.py::CompatibleIDsTest::test_compatible_package_python_requires", "test/integration/package_id/compatible_test.py::CompatibleIDsTest::test_compatible_setting", "test/integration/package_id/compatible_test.py::CompatibleIDsTest::test_compatible_setting_no_binary", "test/integration/package_id/compatible_test.py::CompatibleIDsTest::test_compatible_setting_no_user_channel", "test/integration/package_id/compatible_test.py::CompatibleIDsTest::test_package_id_consumers", "test/integration/package_id/compatible_test.py::TestNewCompatibility::test_compatible_setting", "test/integration/package_id/compatible_test.py::TestNewCompatibility::test_compatibility_remove_package_id", "test/integration/package_id/compatible_test.py::TestNewCompatibility::test_compatibility_erase_package_id", "test/integration/package_id/compatible_test.py::TestNewCompatibility::test_compatibility_msvc_and_cppstd" ]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> Feature/build compatibles Changelog: Feature: Allow building a compatible package still of the current profile one. Docs: Omit Lets keep this not documented at the moment, as there is a gap in ``conan graph build-order`` Close https://github.com/conan-io/conan/issues/16148 Close https://github.com/conan-io/conan/issues/14291 ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in conans/client/graph/build_mode.py] (definition of BuildMode.allowed_compatible:) def allowed_compatible(self, conanfile): [end of new definitions in conans/client/graph/build_mode.py] [start of new definitions in conans/client/graph/graph_binaries.py] (definition of GraphBinariesAnalyzer._find_build_compatible_binary:) def _find_build_compatible_binary(self, node, compatibles): [end of new definitions in conans/client/graph/graph_binaries.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
4a5b19a75db9225316c8cb022a2dfb9705a2af34
deepset-ai__haystack-8103
8,103
deepset-ai/haystack
null
e17d0c41926849975166e70ec46411f402c8098e
2024-07-29T04:06:24Z
diff --git a/haystack/components/preprocessors/document_cleaner.py b/haystack/components/preprocessors/document_cleaner.py index 233dfed50a..282728ea74 100644 --- a/haystack/components/preprocessors/document_cleaner.py +++ b/haystack/components/preprocessors/document_cleaner.py @@ -6,7 +6,8 @@ from copy import deepcopy from functools import partial, reduce from itertools import chain -from typing import Generator, List, Optional, Set +from typing import Generator, List, Literal, Optional, Set +from unicodedata import normalize from haystack import Document, component, logging @@ -45,6 +46,8 @@ def __init__( keep_id: bool = False, remove_substrings: Optional[List[str]] = None, remove_regex: Optional[str] = None, + unicode_normalization: Optional[Literal["NFC", "NFKC", "NFD", "NFKD"]] = None, + ascii_only: bool = False, ): """ Initialize DocumentCleaner. @@ -57,14 +60,34 @@ def __init__( :param remove_substrings: List of substrings to remove from the text. :param remove_regex: Regex to match and replace substrings by "". :param keep_id: If `True`, keeps the IDs of the original documents. + :param unicode_normalization: Unicode normalization form to apply to the text. + Note: This will run before any other steps. + :param ascii_only: Whether to convert the text to ASCII only. + Will remove accents from characters and replace them with ASCII characters. + Other non-ASCII characters will be removed. + Note: This will run before any pattern matching or removal. """ + self._validate_params(unicode_normalization=unicode_normalization) + self.remove_empty_lines = remove_empty_lines self.remove_extra_whitespaces = remove_extra_whitespaces self.remove_repeated_substrings = remove_repeated_substrings self.remove_substrings = remove_substrings self.remove_regex = remove_regex self.keep_id = keep_id + self.unicode_normalization = unicode_normalization + self.ascii_only = ascii_only + + def _validate_params(self, unicode_normalization: Optional[str]): + """ + Validate the parameters of the DocumentCleaner. + + :param unicode_normalization: Unicode normalization form to apply to the text. + :raises ValueError: if the parameters are not valid. + """ + if unicode_normalization and unicode_normalization not in ["NFC", "NFKC", "NFD", "NFKD"]: + raise ValueError("unicode_normalization must be one of 'NFC', 'NFKC', 'NFD', 'NFKD'.") @component.output_types(documents=List[Document]) def run(self, documents: List[Document]): @@ -93,6 +116,10 @@ def run(self, documents: List[Document]): continue text = doc.content + if self.unicode_normalization: + text = self._normalize_unicode(text, self.unicode_normalization) + if self.ascii_only: + text = self._ascii_only(text) if self.remove_extra_whitespaces: text = self._remove_extra_whitespaces(text) if self.remove_empty_lines: @@ -108,6 +135,32 @@ def run(self, documents: List[Document]): return {"documents": cleaned_docs} + def _normalize_unicode(self, text: str, form: Literal["NFC", "NFKC", "NFD", "NFKD"]) -> str: + """ + Normalize the unicode of the text. + + :param text: Text to normalize. + :param form: Unicode normalization form to apply to the text. + Options: "NFC", "NFKC", "NFD", "NFKD". + :returns: The normalized text. + """ + return normalize(form, text) + + def _ascii_only(self, text: str) -> str: + """ + Convert the text to ASCII only. + + Will remove accents from characters and replace them with ASCII characters. + Other non-ASCII characters will be removed. + + :param text: Text to convert to ASCII only. + :returns: The text in ASCII only. + """ + + # First normalize the text to NFKD to separate the characters and their diacritics + # Then encode it to ASCII and ignore any characters that can't be encoded + return self._normalize_unicode(text, "NFKD").encode("ascii", "ignore").decode("utf-8") + def _remove_empty_lines(self, text: str) -> str: """ Remove empty lines and lines that contain nothing but whitespaces from text. diff --git a/releasenotes/notes/add-unicode-normalization-and-ascii-mode-to-document-cleaner-ba536b46e499663c.yaml b/releasenotes/notes/add-unicode-normalization-and-ascii-mode-to-document-cleaner-ba536b46e499663c.yaml new file mode 100644 index 0000000000..d4d28ee47b --- /dev/null +++ b/releasenotes/notes/add-unicode-normalization-and-ascii-mode-to-document-cleaner-ba536b46e499663c.yaml @@ -0,0 +1,6 @@ +--- +enhancements: + - | + Added `unicode_normalization` parameter to the DocumentCleaner, allowing to normalize the text to NFC, NFD, NFKC, or NFKD. + - | + Added `ascii_only` parameter to the DocumentCleaner, transforming letters with diacritics to their ASCII equivalent and removing other non-ASCII characters.
diff --git a/test/components/preprocessors/test_document_cleaner.py b/test/components/preprocessors/test_document_cleaner.py index 0acd9e8e8c..9bd5df549e 100644 --- a/test/components/preprocessors/test_document_cleaner.py +++ b/test/components/preprocessors/test_document_cleaner.py @@ -139,3 +139,68 @@ def test_keep_id_does_not_alter_document_ids(self): assert len(result["documents"]) == 2 assert result["documents"][0].id == "1" assert result["documents"][1].id == "2" + + def test_unicode_normalization(self): + text = """\ + アイウエオ + Comment ça va + مرحبا بالعالم + em Space""" + + expected_text_NFC = """\ + アイウエオ + Comment ça va + مرحبا بالعالم + em Space""" + + expected_text_NFD = """\ + アイウエオ + Comment ça va + مرحبا بالعالم + em Space""" + + expected_text_NFKC = """\ + アイウエオ + Comment ça va + مرحبا بالعالم + em Space""" + + expected_text_NFKD = """\ + アイウエオ + Comment ça va + مرحبا بالعالم + em Space""" + + nfc_cleaner = DocumentCleaner(unicode_normalization="NFC", remove_extra_whitespaces=False) + nfd_cleaner = DocumentCleaner(unicode_normalization="NFD", remove_extra_whitespaces=False) + nfkc_cleaner = DocumentCleaner(unicode_normalization="NFKC", remove_extra_whitespaces=False) + nfkd_cleaner = DocumentCleaner(unicode_normalization="NFKD", remove_extra_whitespaces=False) + + nfc_result = nfc_cleaner.run(documents=[Document(content=text)]) + nfd_result = nfd_cleaner.run(documents=[Document(content=text)]) + nfkc_result = nfkc_cleaner.run(documents=[Document(content=text)]) + nfkd_result = nfkd_cleaner.run(documents=[Document(content=text)]) + + assert nfc_result["documents"][0].content == expected_text_NFC + assert nfd_result["documents"][0].content == expected_text_NFD + assert nfkc_result["documents"][0].content == expected_text_NFKC + assert nfkd_result["documents"][0].content == expected_text_NFKD + + def test_ascii_only(self): + text = """\ + アイウエオ + Comment ça va + Á + مرحبا بالعالم + em Space""" + + expected_text = """\ + \n\ + Comment ca va + A + \n\ + em Space""" + + cleaner = DocumentCleaner(ascii_only=True, remove_extra_whitespaces=False, remove_empty_lines=False) + result = cleaner.run(documents=[Document(content=text)]) + assert result["documents"][0].content == expected_text
diff --git a/releasenotes/notes/add-unicode-normalization-and-ascii-mode-to-document-cleaner-ba536b46e499663c.yaml b/releasenotes/notes/add-unicode-normalization-and-ascii-mode-to-document-cleaner-ba536b46e499663c.yaml new file mode 100644 index 0000000000..d4d28ee47b --- /dev/null +++ b/releasenotes/notes/add-unicode-normalization-and-ascii-mode-to-document-cleaner-ba536b46e499663c.yaml @@ -0,0 +1,6 @@ +--- +enhancements: + - | + Added `unicode_normalization` parameter to the DocumentCleaner, allowing to normalize the text to NFC, NFD, NFKC, or NFKD. + - | + Added `ascii_only` parameter to the DocumentCleaner, transforming letters with diacritics to their ASCII equivalent and removing other non-ASCII characters.
[ { "components": [ { "doc": "Validate the parameters of the DocumentCleaner.\n\n:param unicode_normalization: Unicode normalization form to apply to the text.\n:raises ValueError: if the parameters are not valid.", "lines": [ 82, 90 ], "name": "DocumentCleaner._validate_params", "signature": "def _validate_params(self, unicode_normalization: Optional[str]):", "type": "function" }, { "doc": "Normalize the unicode of the text.\n\n:param text: Text to normalize.\n:param form: Unicode normalization form to apply to the text.\n Options: \"NFC\", \"NFKC\", \"NFD\", \"NFKD\".\n:returns: The normalized text.", "lines": [ 138, 147 ], "name": "DocumentCleaner._normalize_unicode", "signature": "def _normalize_unicode(self, text: str, form: Literal[\"NFC\", \"NFKC\", \"NFD\", \"NFKD\"]) -> str:", "type": "function" }, { "doc": "Convert the text to ASCII only.\n\nWill remove accents from characters and replace them with ASCII characters.\nOther non-ASCII characters will be removed.\n\n:param text: Text to convert to ASCII only.\n:returns: The text in ASCII only.", "lines": [ 149, 162 ], "name": "DocumentCleaner._ascii_only", "signature": "def _ascii_only(self, text: str) -> str:", "type": "function" } ], "file": "haystack/components/preprocessors/document_cleaner.py" } ]
[ "test/components/preprocessors/test_document_cleaner.py::TestDocumentCleaner::test_unicode_normalization", "test/components/preprocessors/test_document_cleaner.py::TestDocumentCleaner::test_ascii_only" ]
[ "[", "test/components/preprocessors/test_document_cleaner.py::TestDocumentCleaner::test_init", "test/components/preprocessors/test_document_cleaner.py::TestDocumentCleaner::test_non_text_document", "test/components/preprocessors/test_document_cleaner.py::TestDocumentCleaner::test_single_document", "test/components/preprocessors/test_document_cleaner.py::TestDocumentCleaner::test_empty_list", "test/components/preprocessors/test_document_cleaner.py::TestDocumentCleaner::test_remove_empty_lines", "test/components/preprocessors/test_document_cleaner.py::TestDocumentCleaner::test_remove_whitespaces", "test/components/preprocessors/test_document_cleaner.py::TestDocumentCleaner::test_remove_substrings", "test/components/preprocessors/test_document_cleaner.py::TestDocumentCleaner::test_remove_regex", "test/components/preprocessors/test_document_cleaner.py::TestDocumentCleaner::test_remove_repeated_substrings", "test/components/preprocessors/test_document_cleaner.py::TestDocumentCleaner::test_copy_metadata", "test/components/preprocessors/test_document_cleaner.py::TestDocumentCleaner::test_keep_id_does_not_alter_document_ids" ]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> feat: add unicode normalization & ascii_only mode for DocumentCleaner ### Proposed Changes: Added two new parameters to the `DocumentCleaner` Component, `unicode_normalization` and `ascii_only`. `unicode_normalization` allows to normalize unicodes within documents using python's [unicodedata module](https://docs.python.org/3/library/unicodedata.html#unicodedata.normalize). `ascii_only` mode converts letters with accents to regular ascii letters, removes other non ascii characters. I decided not to use [unidecode](https://pypi.org/project/Unidecode) since it would add a new dependency with possible unknown transformations but could be a path for improvement, adding support for languages / alphabets. ### How did you test it? Added 2 new unit tests to the DocumentCleaner component (1 per new parameter/step). ### Notes for the reviewer I made the arbitrary decision to have the unicode normalization run first, followed by ascii before any other steps in the DocumentCleaner. **This means regex & substring removal will be made against the normalized documents.** ### Checklist - [x] I have read the [contributors guidelines](https://github.com/deepset-ai/haystack/blob/main/CONTRIBUTING.md) and the [code of conduct](https://github.com/deepset-ai/haystack/blob/main/code_of_conduct.txt) - [ ] I have updated the related issue with new insights and changes - [x] I added unit tests and updated the docstrings - [x] I've used one of the [conventional commit types](https://www.conventionalcommits.org/en/v1.0.0/) for my PR title: `fix:`, `feat:`, `build:`, `chore:`, `ci:`, `docs:`, `style:`, `refactor:`, `perf:`, `test:`. - [x] I documented my code - [x] I ran [pre-commit hooks](https://github.com/deepset-ai/haystack/blob/main/CONTRIBUTING.md#installation) and fixed any issue ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in haystack/components/preprocessors/document_cleaner.py] (definition of DocumentCleaner._validate_params:) def _validate_params(self, unicode_normalization: Optional[str]): """Validate the parameters of the DocumentCleaner. :param unicode_normalization: Unicode normalization form to apply to the text. :raises ValueError: if the parameters are not valid.""" (definition of DocumentCleaner._normalize_unicode:) def _normalize_unicode(self, text: str, form: Literal["NFC", "NFKC", "NFD", "NFKD"]) -> str: """Normalize the unicode of the text. :param text: Text to normalize. :param form: Unicode normalization form to apply to the text. Options: "NFC", "NFKC", "NFD", "NFKD". :returns: The normalized text.""" (definition of DocumentCleaner._ascii_only:) def _ascii_only(self, text: str) -> str: """Convert the text to ASCII only. Will remove accents from characters and replace them with ASCII characters. Other non-ASCII characters will be removed. :param text: Text to convert to ASCII only. :returns: The text in ASCII only.""" [end of new definitions in haystack/components/preprocessors/document_cleaner.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
f4d9c2bb917be0ffe132dffcc2ad4f1b0fcc5967
deepset-ai__haystack-8042
8,042
deepset-ai/haystack
null
031b0bfbd836f128736220589917a62c43c9c512
2024-07-18T09:14:08Z
diff --git a/haystack/document_stores/types/__init__.py b/haystack/document_stores/types/__init__.py index df2032f79c..ed6becf8b4 100644 --- a/haystack/document_stores/types/__init__.py +++ b/haystack/document_stores/types/__init__.py @@ -2,8 +2,8 @@ # # SPDX-License-Identifier: Apache-2.0 -from .filter_policy import FilterPolicy +from .filter_policy import FilterPolicy, apply_filter_policy from .policy import DuplicatePolicy from .protocol import DocumentStore -__all__ = ["DocumentStore", "DuplicatePolicy", "FilterPolicy"] +__all__ = ["apply_filter_policy", "DocumentStore", "DuplicatePolicy", "FilterPolicy"] diff --git a/haystack/document_stores/types/filter_policy.py b/haystack/document_stores/types/filter_policy.py index a2be576d20..b0dc58d895 100644 --- a/haystack/document_stores/types/filter_policy.py +++ b/haystack/document_stores/types/filter_policy.py @@ -3,7 +3,11 @@ # SPDX-License-Identifier: Apache-2.0 from enum import Enum -from typing import Any, Dict, Optional +from typing import Any, Dict, Literal, Optional + +from haystack import logging + +logger = logging.getLogger(__name__) class FilterPolicy(Enum): @@ -28,18 +32,259 @@ def from_str(filter_policy: str) -> "FilterPolicy": :param filter_policy: The string to convert. :return: The corresponding FilterPolicy enum. """ - enum_map = {e.value: e for e in FilterPolicy} - policy = enum_map.get(filter_policy) + enum_map = {e.value.lower(): e for e in FilterPolicy} + policy = enum_map.get(filter_policy.lower() if filter_policy else "") if policy is None: msg = f"Unknown FilterPolicy type '{filter_policy}'. Supported types are: {list(enum_map.keys())}" raise ValueError(msg) return policy +def is_comparison_filter(filter_item: Dict[str, Any]) -> bool: + """ + Check if the given filter is a comparison filter. + + :param filter_item: The filter to check. + :returns: True if the filter is a comparison filter, False otherwise. + """ + return all(key in filter_item for key in ["field", "operator", "value"]) + + +def is_logical_filter(filter_item: Dict[str, Any]) -> bool: + """ + Check if the given filter is a logical filter. + + :param filter_item: The filter to check. + :returns: True if the filter is a logical filter, False otherwise. + """ + return "operator" in filter_item and "conditions" in filter_item + + +def combine_two_logical_filters( + init_logical_filter: Dict[str, Any], runtime_logical_filter: Dict[str, Any] +) -> Dict[str, Any]: + """ + Combine two logical filters, they must have the same operator. + + If `init_logical_filter["operator"]` and `runtime_logical_filter["operator"]` are the same, the conditions + of both filters are combined. Otherwise, the `init_logical_filter` is ignored and ` + runtime_logical_filter` is returned. + + __Example__: + + ```python + init_logical_filter = { + "operator": "AND", + "conditions": [ + {"field": "meta.type", "operator": "==", "value": "article"}, + {"field": "meta.rating", "operator": ">=", "value": 3}, + ] + } + runtime_logical_filter = { + "operator": "AND", + "conditions": [ + {"field": "meta.genre", "operator": "IN", "value": ["economy", "politics"]}, + {"field": "meta.publisher", "operator": "==", "value": "nytimes"}, + ] + } + new_filters = combine_two_logical_filters( + init_logical_filter, runtime_logical_filter, "AND" + ) + # Output: + { + "operator": "AND", + "conditions": [ + {"field": "meta.type", "operator": "==", "value": "article"}, + {"field": "meta.rating", "operator": ">=", "value": 3}, + {"field": "meta.genre", "operator": "IN", "value": ["economy", "politics"]}, + {"field": "meta.publisher", "operator": "==", "value": "nytimes"}, + ] + } + ``` + """ + if init_logical_filter["operator"] == runtime_logical_filter["operator"]: + return { + "operator": str(init_logical_filter["operator"]), + "conditions": init_logical_filter["conditions"] + runtime_logical_filter["conditions"], + } + + logger.warning( + "The provided logical operators, {parsed_operator} and {operator}, do not match so the parsed logical " + "filter, {init_logical_filter}, will be ignored and only the provided logical filter,{runtime_logical_filter}, " + "will be used. Update the logical operators to match to include the parsed filter.", + parsed_operator=init_logical_filter["operator"], + operator=runtime_logical_filter["operator"], + init_logical_filter=init_logical_filter, + runtime_logical_filter=runtime_logical_filter, + ) + runtime_logical_filter["operator"] = str(runtime_logical_filter["operator"]) + return runtime_logical_filter + + +def combine_init_comparison_and_runtime_logical_filters( + init_comparison_filter: Dict[str, Any], + runtime_logical_filter: Dict[str, Any], + logical_operator: Literal["AND", "OR", "NOT"], +) -> Dict[str, Any]: + """ + Combine a runtime logical filter with the init comparison filter using the provided logical_operator. + + We only add the init_comparison_filter if logical_operator matches the existing + runtime_logical_filter["operator"]. Otherwise, we return the runtime_logical_filter unchanged. + + __Example__: + + ```python + runtime_logical_filter = { + "operator": "AND", + "conditions": [ + {"field": "meta.type", "operator": "==", "value": "article"}, + {"field": "meta.rating", "operator": ">=", "value": 3}, + ] + } + init_comparison_filter = {"field": "meta.date", "operator": ">=", "value": "2015-01-01"} + new_filters = combine_init_comparison_and_runtime_logical_filters( + init_comparison_filter, runtime_logical_filter, "AND" + ) + # Output: + { + "operator": "AND", + "conditions": [ + {"field": "meta.type", "operator": "==", "value": "article"}, + {"field": "meta.rating", "operator": ">=", "value": 3}, + {"field": "meta.date", "operator": ">=", "value": "2015-01-01"}, + ] + } + ``` + """ + if runtime_logical_filter["operator"] == logical_operator: + conditions = runtime_logical_filter["conditions"] + fields = {c.get("field") for c in conditions} + if init_comparison_filter["field"] not in fields: + conditions.append(init_comparison_filter) + else: + logger.warning( + "The init filter, {init_filter}, is ignored as the field is already present in the existing " + "filters, {filters}.", + init_filter=init_comparison_filter, + filters=runtime_logical_filter, + ) + return {"operator": str(runtime_logical_filter["operator"]), "conditions": conditions} + + logger.warning( + "The provided logical_operator, {logical_operator}, does not match the logical operator found in " + "the runtime filters, {filters_logical_operator}, so the init filter will be ignored.", + logical_operator=logical_operator, + filters_logical_operator=runtime_logical_filter["operator"], + ) + runtime_logical_filter["operator"] = str(runtime_logical_filter["operator"]) + return runtime_logical_filter + + +def combine_runtime_comparison_and_init_logical_filters( + runtime_comparison_filter: Dict[str, Any], + init_logical_filter: Dict[str, Any], + logical_operator: Literal["AND", "OR", "NOT"], +) -> Dict[str, Any]: + """ + Combine an init logical filter with the runtime comparison filter using the provided logical_operator. + + We only add the runtime_comparison_filter if logical_operator matches the existing + init_logical_filter["operator"]. Otherwise, we return the runtime_comparison_filter unchanged. + + __Example__: + + ```python + init_logical_filter = { + "operator": "AND", + "conditions": [ + {"field": "meta.type", "operator": "==", "value": "article"}, + {"field": "meta.rating", "operator": ">=", "value": 3}, + ] + } + runtime_comparison_filter = {"field": "meta.date", "operator": ">=", "value": "2015-01-01"} + new_filters = combine_runtime_comparison_and_init_logical_filters( + runtime_comparison_filter, init_logical_filter, "AND" + ) + # Output: + { + "operator": "AND", + "conditions": [ + {"field": "meta.type", "operator": "==", "value": "article"}, + {"field": "meta.rating", "operator": ">=", "value": 3}, + {"field": "meta.date", "operator": ">=", "value": "2015-01-01"}, + ] + } + ``` + """ + if init_logical_filter["operator"] == logical_operator: + conditions = init_logical_filter["conditions"] + fields = {c.get("field") for c in conditions} + if runtime_comparison_filter["field"] in fields: + logger.warning( + "The runtime filter, {runtime_filter}, will overwrite the existing filter with the same " + "field in the init logical filter.", + runtime_filter=runtime_comparison_filter, + ) + conditions = [c for c in conditions if c.get("field") != runtime_comparison_filter["field"]] + conditions.append(runtime_comparison_filter) + return {"operator": str(init_logical_filter["operator"]), "conditions": conditions} + + logger.warning( + "The provided logical_operator, {logical_operator}, does not match the logical operator found in " + "the init logical filter, {filters_logical_operator}, so the init logical filter will be ignored.", + logical_operator=logical_operator, + filters_logical_operator=init_logical_filter["operator"], + ) + return runtime_comparison_filter + + +def combine_two_comparison_filters( + init_comparison_filter: Dict[str, Any], + runtime_comparison_filter: Dict[str, Any], + logical_operator: Literal["AND", "OR", "NOT"], +) -> Dict[str, Any]: + """ + Combine a comparison filter with the `init_comparison_filter` using the provided `logical_operator`. + + If `runtime_comparison_filter` and `init_comparison_filter` target the same field, `init_comparison_filter` + is ignored and `runtime_comparison_filter` is returned unchanged. + + __Example__: + + ```python + runtime_comparison_filter = {"field": "meta.type", "operator": "==", "value": "article"}, + init_comparison_filter = {"field": "meta.date", "operator": ">=", "value": "2015-01-01"}, + new_filters = combine_two_comparison_filters( + init_comparison_filter, runtime_comparison_filter, "AND" + ) + # Output: + { + "operator": "AND", + "conditions": [ + {"field": "meta.type", "operator": "==", "value": "article"}, + {"field": "meta.date", "operator": ">=", "value": "2015-01-01"}, + ] + } + ``` + """ + if runtime_comparison_filter["field"] == init_comparison_filter["field"]: + logger.warning( + "The parsed filter, {parsed_filter}, is ignored as the field is already present in the existing " + "filters, {filters}.", + parsed_filter=init_comparison_filter, + filters=runtime_comparison_filter, + ) + return runtime_comparison_filter + + return {"operator": str(logical_operator), "conditions": [init_comparison_filter, runtime_comparison_filter]} + + def apply_filter_policy( filter_policy: FilterPolicy, init_filters: Optional[Dict[str, Any]] = None, runtime_filters: Optional[Dict[str, Any]] = None, + default_logical_operator: Literal["AND", "OR", "NOT"] = "AND", ) -> Optional[Dict[str, Any]]: """ Apply the filter policy to the given initial and runtime filters to determine the final set of filters used. @@ -52,10 +297,23 @@ def apply_filter_policy( values from the runtime filters will overwrite those from the initial filters. :param init_filters: The initial filters set during the initialization of the relevant retriever. :param runtime_filters: The filters provided at runtime, usually during a query operation execution. These filters - can change for each query/retreiver run invocation. + can change for each query/retriever run invocation. + :param default_logical_operator: The default logical operator to use when merging filters (non-legacy filters only). :returns: A dictionary containing the resulting filters based on the provided policy. """ - if filter_policy == FilterPolicy.MERGE and runtime_filters: - return {**(init_filters or {}), **runtime_filters} - else: - return runtime_filters or init_filters + if filter_policy == FilterPolicy.MERGE and runtime_filters and init_filters: + # now we merge filters + if is_comparison_filter(init_filters) and is_comparison_filter(runtime_filters): + return combine_two_comparison_filters(init_filters, runtime_filters, default_logical_operator) + elif is_comparison_filter(init_filters) and is_logical_filter(runtime_filters): + return combine_init_comparison_and_runtime_logical_filters( + init_filters, runtime_filters, default_logical_operator + ) + elif is_logical_filter(init_filters) and is_comparison_filter(runtime_filters): + return combine_runtime_comparison_and_init_logical_filters( + runtime_filters, init_filters, default_logical_operator + ) + elif is_logical_filter(init_filters) and is_logical_filter(runtime_filters): + return combine_two_logical_filters(init_filters, runtime_filters) + + return runtime_filters or init_filters diff --git a/releasenotes/notes/implement-merge-filter-logic-99e6785a78f80ae9.yaml b/releasenotes/notes/implement-merge-filter-logic-99e6785a78f80ae9.yaml new file mode 100644 index 0000000000..c90479c2c6 --- /dev/null +++ b/releasenotes/notes/implement-merge-filter-logic-99e6785a78f80ae9.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Enhanced filter application logic to support merging of filters. It facilitates more precise retrieval filtering, allowing for both init and runtime complex filter combinations with logical operators. For more details see https://docs.haystack.deepset.ai/docs/metadata-filtering
diff --git a/test/document_stores/test_filter_policy.py b/test/document_stores/test_filter_policy.py index b7efcd0672..d775ee356e 100644 --- a/test/document_stores/test_filter_policy.py +++ b/test/document_stores/test_filter_policy.py @@ -3,43 +3,178 @@ # SPDX-License-Identifier: Apache-2.0 import pytest -from typing import Any, Dict, Optional -from enum import Enum -from haystack.document_stores.types import FilterPolicy -from haystack.document_stores.types.filter_policy import apply_filter_policy +from haystack.document_stores.types import apply_filter_policy, FilterPolicy -def test_replace_policy_with_both_filters(): - init_filters = {"status": "active", "category": "news"} - runtime_filters = {"author": "John Doe"} - result = apply_filter_policy(FilterPolicy.REPLACE, init_filters, runtime_filters) - assert result == runtime_filters +def test_merge_two_comparison_filters(): + """ + Merging two comparison filters + Result: AND operator with both filters + """ + init_filters = {"field": "meta.date", "operator": ">=", "value": "2015-01-01"} + runtime_filters = {"field": "meta.type", "operator": "==", "value": "article"} + result = apply_filter_policy(FilterPolicy.MERGE, init_filters, runtime_filters) + assert result == { + "operator": "AND", + "conditions": [ + {"field": "meta.date", "operator": ">=", "value": "2015-01-01"}, + {"field": "meta.type", "operator": "==", "value": "article"}, + ], + } -def test_merge_policy_with_both_filters(): - init_filters = {"status": "active", "category": "news"} - runtime_filters = {"author": "John Doe"} +def test_merge_init_comparison_and_runtime_logical_filters(): + """ + Merging init comparison and runtime logical filters + Result: AND operator with both filters + """ + init_filters = {"field": "meta.date", "operator": ">=", "value": "2015-01-01"} + runtime_filters = { + "operator": "AND", + "conditions": [ + {"field": "meta.type", "operator": "==", "value": "article"}, + {"field": "meta.rating", "operator": ">=", "value": 3}, + ], + } result = apply_filter_policy(FilterPolicy.MERGE, init_filters, runtime_filters) - assert result == {"status": "active", "category": "news", "author": "John Doe"} + assert result == { + "operator": "AND", + "conditions": [ + {"field": "meta.type", "operator": "==", "value": "article"}, + {"field": "meta.rating", "operator": ">=", "value": 3}, + {"field": "meta.date", "operator": ">=", "value": "2015-01-01"}, + ], + } -def test_replace_policy_with_only_init_filters(): - init_filters = {"status": "active", "category": "news"} - runtime_filters = None - result = apply_filter_policy(FilterPolicy.REPLACE, init_filters, runtime_filters) - assert result == init_filters +def test_merge_runtime_comparison_and_init_logical_filters_with_string_operators(): + """ + Merging a runtime comparison filter with an init logical filter, but with string-based logical operators + Result: AND operator with both filters + """ + # Test with string-based logical operators + init_filters = { + "operator": "AND", + "conditions": [ + {"field": "meta.type", "operator": "==", "value": "article"}, + {"field": "meta.rating", "operator": ">=", "value": 3}, + ], + } + runtime_filters = { + "operator": "AND", + "conditions": [ + {"field": "meta.genre", "operator": "IN", "value": ["economy", "politics"]}, + {"field": "meta.publisher", "operator": "==", "value": "nytimes"}, + ], + } + result = apply_filter_policy(FilterPolicy.MERGE, init_filters, runtime_filters) + assert result == { + "operator": "AND", + "conditions": [ + {"field": "meta.type", "operator": "==", "value": "article"}, + {"field": "meta.rating", "operator": ">=", "value": 3}, + {"field": "meta.genre", "operator": "IN", "value": ["economy", "politics"]}, + {"field": "meta.publisher", "operator": "==", "value": "nytimes"}, + ], + } -def test_merge_policy_with_only_init_filters(): - init_filters = {"status": "active", "category": "news"} - runtime_filters = None +def test_merge_runtime_comparison_and_init_logical_filters(): + """ + Merging a runtime comparison filter with an init logical filter + Result: AND operator with both filters + """ + init_filters = { + "operator": "AND", + "conditions": [ + {"field": "meta.type", "operator": "==", "value": "article"}, + {"field": "meta.rating", "operator": ">=", "value": 3}, + ], + } + runtime_filters = {"field": "meta.date", "operator": ">=", "value": "2015-01-01"} result = apply_filter_policy(FilterPolicy.MERGE, init_filters, runtime_filters) - assert result == init_filters + assert result == { + "operator": "AND", + "conditions": [ + {"field": "meta.type", "operator": "==", "value": "article"}, + {"field": "meta.rating", "operator": ">=", "value": 3}, + {"field": "meta.date", "operator": ">=", "value": "2015-01-01"}, + ], + } -def test_merge_policy_with_overlapping_keys(): - init_filters = {"status": "active", "category": "news"} - runtime_filters = {"category": "science", "author": "John Doe"} +def test_merge_two_logical_filters(): + """ + Merging two logical filters + Result: AND operator with both filters + """ + init_filters = { + "operator": "AND", + "conditions": [ + {"field": "meta.type", "operator": "==", "value": "article"}, + {"field": "meta.rating", "operator": ">=", "value": 3}, + ], + } + runtime_filters = { + "operator": "AND", + "conditions": [ + {"field": "meta.genre", "operator": "IN", "value": ["economy", "politics"]}, + {"field": "meta.publisher", "operator": "==", "value": "nytimes"}, + ], + } result = apply_filter_policy(FilterPolicy.MERGE, init_filters, runtime_filters) - assert result == {"status": "active", "category": "science", "author": "John Doe"} + assert result == { + "operator": "AND", + "conditions": [ + {"field": "meta.type", "operator": "==", "value": "article"}, + {"field": "meta.rating", "operator": ">=", "value": 3}, + {"field": "meta.genre", "operator": "IN", "value": ["economy", "politics"]}, + {"field": "meta.publisher", "operator": "==", "value": "nytimes"}, + ], + } + + +def test_merge_with_different_logical_operators(): + """ + Merging with a different logical operator + Result: warnings and runtime filters + """ + init_filters = {"operator": "AND", "conditions": [{"field": "meta.type", "operator": "==", "value": "article"}]} + runtime_filters = { + "operator": "OR", + "conditions": [{"field": "meta.genre", "operator": "IN", "value": ["economy", "politics"]}], + } + result = apply_filter_policy(FilterPolicy.MERGE, init_filters, runtime_filters) + assert result == runtime_filters + + +def test_merge_comparison_filters_with_same_field(): + """ + Merging comparison filters with the same field + Result: warnings and runtime filters + """ + init_filters = {"field": "meta.date", "operator": ">=", "value": "2015-01-01"} + runtime_filters = {"field": "meta.date", "operator": "<=", "value": "2020-12-31"} + result = apply_filter_policy(FilterPolicy.MERGE, init_filters, runtime_filters) + assert result == runtime_filters + + +@pytest.mark.parametrize("logical_operator", ["AND", "OR", "NOT"]) +def test_merge_with_custom_logical_operator(logical_operator: str): + """ + Merging with a custom logical operator + Result: The given logical operator with both filters + """ + init_filters = {"field": "meta.date", "operator": ">=", "value": "2015-01-01"} + runtime_filters = {"field": "meta.type", "operator": "==", "value": "article"} + result = apply_filter_policy( + FilterPolicy.MERGE, init_filters, runtime_filters, default_logical_operator=logical_operator + ) + assert result == { + "operator": logical_operator, + "conditions": [ + {"field": "meta.date", "operator": ">=", "value": "2015-01-01"}, + {"field": "meta.type", "operator": "==", "value": "article"}, + ], + }
diff --git a/releasenotes/notes/implement-merge-filter-logic-99e6785a78f80ae9.yaml b/releasenotes/notes/implement-merge-filter-logic-99e6785a78f80ae9.yaml new file mode 100644 index 0000000000..c90479c2c6 --- /dev/null +++ b/releasenotes/notes/implement-merge-filter-logic-99e6785a78f80ae9.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Enhanced filter application logic to support merging of filters. It facilitates more precise retrieval filtering, allowing for both init and runtime complex filter combinations with logical operators. For more details see https://docs.haystack.deepset.ai/docs/metadata-filtering
[ { "components": [ { "doc": "Check if the given filter is a comparison filter.\n\n:param filter_item: The filter to check.\n:returns: True if the filter is a comparison filter, False otherwise.", "lines": [ 43, 50 ], "name": "is_comparison_filter", "signature": "def is_comparison_filter(filter_item: Dict[str, Any]) -> bool:", "type": "function" }, { "doc": "Check if the given filter is a logical filter.\n\n:param filter_item: The filter to check.\n:returns: True if the filter is a logical filter, False otherwise.", "lines": [ 53, 60 ], "name": "is_logical_filter", "signature": "def is_logical_filter(filter_item: Dict[str, Any]) -> bool:", "type": "function" }, { "doc": "Combine two logical filters, they must have the same operator.\n\nIf `init_logical_filter[\"operator\"]` and `runtime_logical_filter[\"operator\"]` are the same, the conditions\nof both filters are combined. Otherwise, the `init_logical_filter` is ignored and `\nruntime_logical_filter` is returned.\n\n __Example__:\n\n ```python\n init_logical_filter = {\n \"operator\": \"AND\",\n \"conditions\": [\n {\"field\": \"meta.type\", \"operator\": \"==\", \"value\": \"article\"},\n {\"field\": \"meta.rating\", \"operator\": \">=\", \"value\": 3},\n ]\n }\n runtime_logical_filter = {\n \"operator\": \"AND\",\n \"conditions\": [\n {\"field\": \"meta.genre\", \"operator\": \"IN\", \"value\": [\"economy\", \"politics\"]},\n {\"field\": \"meta.publisher\", \"operator\": \"==\", \"value\": \"nytimes\"},\n ]\n }\n new_filters = combine_two_logical_filters(\n init_logical_filter, runtime_logical_filter, \"AND\"\n )\n # Output:\n {\n \"operator\": \"AND\",\n \"conditions\": [\n {\"field\": \"meta.type\", \"operator\": \"==\", \"value\": \"article\"},\n {\"field\": \"meta.rating\", \"operator\": \">=\", \"value\": 3},\n {\"field\": \"meta.genre\", \"operator\": \"IN\", \"value\": [\"economy\", \"politics\"]},\n {\"field\": \"meta.publisher\", \"operator\": \"==\", \"value\": \"nytimes\"},\n ]\n }\n ```", "lines": [ 63, 121 ], "name": "combine_two_logical_filters", "signature": "def combine_two_logical_filters( init_logical_filter: Dict[str, Any], runtime_logical_filter: Dict[str, Any] ) -> Dict[str, Any]:", "type": "function" }, { "doc": "Combine a runtime logical filter with the init comparison filter using the provided logical_operator.\n\nWe only add the init_comparison_filter if logical_operator matches the existing\nruntime_logical_filter[\"operator\"]. Otherwise, we return the runtime_logical_filter unchanged.\n\n__Example__:\n\n```python\nruntime_logical_filter = {\n \"operator\": \"AND\",\n \"conditions\": [\n {\"field\": \"meta.type\", \"operator\": \"==\", \"value\": \"article\"},\n {\"field\": \"meta.rating\", \"operator\": \">=\", \"value\": 3},\n ]\n}\ninit_comparison_filter = {\"field\": \"meta.date\", \"operator\": \">=\", \"value\": \"2015-01-01\"}\nnew_filters = combine_init_comparison_and_runtime_logical_filters(\n init_comparison_filter, runtime_logical_filter, \"AND\"\n)\n# Output:\n{\n \"operator\": \"AND\",\n \"conditions\": [\n {\"field\": \"meta.type\", \"operator\": \"==\", \"value\": \"article\"},\n {\"field\": \"meta.rating\", \"operator\": \">=\", \"value\": 3},\n {\"field\": \"meta.date\", \"operator\": \">=\", \"value\": \"2015-01-01\"},\n ]\n}\n```", "lines": [ 124, 181 ], "name": "combine_init_comparison_and_runtime_logical_filters", "signature": "def combine_init_comparison_and_runtime_logical_filters( init_comparison_filter: Dict[str, Any], runtime_logical_filter: Dict[str, Any], logical_operator: Literal[\"AND\", \"OR\", \"NOT\"], ) -> Dict[str, Any]:", "type": "function" }, { "doc": "Combine an init logical filter with the runtime comparison filter using the provided logical_operator.\n\nWe only add the runtime_comparison_filter if logical_operator matches the existing\ninit_logical_filter[\"operator\"]. Otherwise, we return the runtime_comparison_filter unchanged.\n\n__Example__:\n\n```python\ninit_logical_filter = {\n \"operator\": \"AND\",\n \"conditions\": [\n {\"field\": \"meta.type\", \"operator\": \"==\", \"value\": \"article\"},\n {\"field\": \"meta.rating\", \"operator\": \">=\", \"value\": 3},\n ]\n}\nruntime_comparison_filter = {\"field\": \"meta.date\", \"operator\": \">=\", \"value\": \"2015-01-01\"}\nnew_filters = combine_runtime_comparison_and_init_logical_filters(\n runtime_comparison_filter, init_logical_filter, \"AND\"\n)\n# Output:\n{\n \"operator\": \"AND\",\n \"conditions\": [\n {\"field\": \"meta.type\", \"operator\": \"==\", \"value\": \"article\"},\n {\"field\": \"meta.rating\", \"operator\": \">=\", \"value\": 3},\n {\"field\": \"meta.date\", \"operator\": \">=\", \"value\": \"2015-01-01\"},\n ]\n}\n```", "lines": [ 184, 239 ], "name": "combine_runtime_comparison_and_init_logical_filters", "signature": "def combine_runtime_comparison_and_init_logical_filters( runtime_comparison_filter: Dict[str, Any], init_logical_filter: Dict[str, Any], logical_operator: Literal[\"AND\", \"OR\", \"NOT\"], ) -> Dict[str, Any]:", "type": "function" }, { "doc": "Combine a comparison filter with the `init_comparison_filter` using the provided `logical_operator`.\n\nIf `runtime_comparison_filter` and `init_comparison_filter` target the same field, `init_comparison_filter`\nis ignored and `runtime_comparison_filter` is returned unchanged.\n\n __Example__:\n\n ```python\n runtime_comparison_filter = {\"field\": \"meta.type\", \"operator\": \"==\", \"value\": \"article\"},\n init_comparison_filter = {\"field\": \"meta.date\", \"operator\": \">=\", \"value\": \"2015-01-01\"},\n new_filters = combine_two_comparison_filters(\n init_comparison_filter, runtime_comparison_filter, \"AND\"\n )\n # Output:\n {\n \"operator\": \"AND\",\n \"conditions\": [\n {\"field\": \"meta.type\", \"operator\": \"==\", \"value\": \"article\"},\n {\"field\": \"meta.date\", \"operator\": \">=\", \"value\": \"2015-01-01\"},\n ]\n }\n ```", "lines": [ 242, 280 ], "name": "combine_two_comparison_filters", "signature": "def combine_two_comparison_filters( init_comparison_filter: Dict[str, Any], runtime_comparison_filter: Dict[str, Any], logical_operator: Literal[\"AND\", \"OR\", \"NOT\"], ) -> Dict[str, Any]:", "type": "function" } ], "file": "haystack/document_stores/types/filter_policy.py" } ]
[ "[", "test/document_stores/test_filter_policy.py::test_merge_two_comparison_filters", "test/document_stores/test_filter_policy.py::test_merge_init_comparison_and_runtime_logical_filters", "test/document_stores/test_filter_policy.py::test_merge_runtime_comparison_and_init_logical_filters_with_string_operators", "test/document_stores/test_filter_policy.py::test_merge_runtime_comparison_and_init_logical_filters", "test/document_stores/test_filter_policy.py::test_merge_two_logical_filters", "test/document_stores/test_filter_policy.py::test_merge_with_different_logical_operators", "test/document_stores/test_filter_policy.py::test_merge_comparison_filters_with_same_field", "test/document_stores/test_filter_policy.py::test_merge_with_custom_logical_operator[AND]", "test/document_stores/test_filter_policy.py::test_merge_with_custom_logical_operator[OR]", "test/document_stores/test_filter_policy.py::test_merge_with_custom_logical_operator[NOT]" ]
[]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> feat: Implement apply_filter_policy and FilterPolicy.MERGE for the new filters ### Why: Implements proper merging of new filters. - fixes: https://github.com/deepset-ai/haystack/issues/7995 ### What: - Implemented new utility functions to determine filter types (`is_legacy`, `is_comparison_filter`, `is_logical_filter`). - Extended the `apply_filter: policy` function to support merging of `init_filters` with `runtime_filters` using a logical operator, facilitating complex filter scenarios. - Added a comprehensive suite of tests to validate the functionality of applying filter policies including scenarios with no filters, comparison filters, logical operators, and user-defined logical operators. ### How can it be used: The enhancements enable complex filter logic to be applied seamlessly in document query operations, such as: - Merging initial and runtime filters with support for legacy filter formats. - Applying logical operators (`AND`, `OR`) when merging comparison or logical filters, allowing for a more nuanced filter logic that can accurately reflect user needs or query specifics. Example usage of merging comparison and logical filters: ```python init_filter = {"field": "meta.type", "operator": "==", "value": "pdf"} runtime_filter = { "operator": "AND", "conditions": [ {"field": "meta.name", "operator": "==", "value": "John"}, {"field": "meta.year", "operator": "==", "value": "2022"}, ], } # Merging the above would result in runtime_filter including the init_filter as another condition under the same logical operator "AND". ``` ### How did you test it: A series of unit tests were added covering various scenarios including: - Merging filters under both `MERGE` and `REPLACE` policies with different combinations of comparison and logical filters. - Ensuring that the correct logical operator is applied during the merge process. - Testing the behavior with no filters provided, ensuring backward compatibility and robust error handling. ### Notes for the reviewer: - Special attention should be given to the logic involving merging different types of filters (comparison vs. logical) and ensuring the intended behavior aligns with real-world use cases. - Review the test cases for `apply_filter_policy` to ensure all potential scenarios are covered and the expected behavior is clearly documented and verified. ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in haystack/document_stores/types/filter_policy.py] (definition of is_comparison_filter:) def is_comparison_filter(filter_item: Dict[str, Any]) -> bool: """Check if the given filter is a comparison filter. :param filter_item: The filter to check. :returns: True if the filter is a comparison filter, False otherwise.""" (definition of is_logical_filter:) def is_logical_filter(filter_item: Dict[str, Any]) -> bool: """Check if the given filter is a logical filter. :param filter_item: The filter to check. :returns: True if the filter is a logical filter, False otherwise.""" (definition of combine_two_logical_filters:) def combine_two_logical_filters( init_logical_filter: Dict[str, Any], runtime_logical_filter: Dict[str, Any] ) -> Dict[str, Any]: """Combine two logical filters, they must have the same operator. If `init_logical_filter["operator"]` and `runtime_logical_filter["operator"]` are the same, the conditions of both filters are combined. Otherwise, the `init_logical_filter` is ignored and ` runtime_logical_filter` is returned. __Example__: ```python init_logical_filter = { "operator": "AND", "conditions": [ {"field": "meta.type", "operator": "==", "value": "article"}, {"field": "meta.rating", "operator": ">=", "value": 3}, ] } runtime_logical_filter = { "operator": "AND", "conditions": [ {"field": "meta.genre", "operator": "IN", "value": ["economy", "politics"]}, {"field": "meta.publisher", "operator": "==", "value": "nytimes"}, ] } new_filters = combine_two_logical_filters( init_logical_filter, runtime_logical_filter, "AND" ) # Output: { "operator": "AND", "conditions": [ {"field": "meta.type", "operator": "==", "value": "article"}, {"field": "meta.rating", "operator": ">=", "value": 3}, {"field": "meta.genre", "operator": "IN", "value": ["economy", "politics"]}, {"field": "meta.publisher", "operator": "==", "value": "nytimes"}, ] } ```""" (definition of combine_init_comparison_and_runtime_logical_filters:) def combine_init_comparison_and_runtime_logical_filters( init_comparison_filter: Dict[str, Any], runtime_logical_filter: Dict[str, Any], logical_operator: Literal["AND", "OR", "NOT"], ) -> Dict[str, Any]: """Combine a runtime logical filter with the init comparison filter using the provided logical_operator. We only add the init_comparison_filter if logical_operator matches the existing runtime_logical_filter["operator"]. Otherwise, we return the runtime_logical_filter unchanged. __Example__: ```python runtime_logical_filter = { "operator": "AND", "conditions": [ {"field": "meta.type", "operator": "==", "value": "article"}, {"field": "meta.rating", "operator": ">=", "value": 3}, ] } init_comparison_filter = {"field": "meta.date", "operator": ">=", "value": "2015-01-01"} new_filters = combine_init_comparison_and_runtime_logical_filters( init_comparison_filter, runtime_logical_filter, "AND" ) # Output: { "operator": "AND", "conditions": [ {"field": "meta.type", "operator": "==", "value": "article"}, {"field": "meta.rating", "operator": ">=", "value": 3}, {"field": "meta.date", "operator": ">=", "value": "2015-01-01"}, ] } ```""" (definition of combine_runtime_comparison_and_init_logical_filters:) def combine_runtime_comparison_and_init_logical_filters( runtime_comparison_filter: Dict[str, Any], init_logical_filter: Dict[str, Any], logical_operator: Literal["AND", "OR", "NOT"], ) -> Dict[str, Any]: """Combine an init logical filter with the runtime comparison filter using the provided logical_operator. We only add the runtime_comparison_filter if logical_operator matches the existing init_logical_filter["operator"]. Otherwise, we return the runtime_comparison_filter unchanged. __Example__: ```python init_logical_filter = { "operator": "AND", "conditions": [ {"field": "meta.type", "operator": "==", "value": "article"}, {"field": "meta.rating", "operator": ">=", "value": 3}, ] } runtime_comparison_filter = {"field": "meta.date", "operator": ">=", "value": "2015-01-01"} new_filters = combine_runtime_comparison_and_init_logical_filters( runtime_comparison_filter, init_logical_filter, "AND" ) # Output: { "operator": "AND", "conditions": [ {"field": "meta.type", "operator": "==", "value": "article"}, {"field": "meta.rating", "operator": ">=", "value": 3}, {"field": "meta.date", "operator": ">=", "value": "2015-01-01"}, ] } ```""" (definition of combine_two_comparison_filters:) def combine_two_comparison_filters( init_comparison_filter: Dict[str, Any], runtime_comparison_filter: Dict[str, Any], logical_operator: Literal["AND", "OR", "NOT"], ) -> Dict[str, Any]: """Combine a comparison filter with the `init_comparison_filter` using the provided `logical_operator`. If `runtime_comparison_filter` and `init_comparison_filter` target the same field, `init_comparison_filter` is ignored and `runtime_comparison_filter` is returned unchanged. __Example__: ```python runtime_comparison_filter = {"field": "meta.type", "operator": "==", "value": "article"}, init_comparison_filter = {"field": "meta.date", "operator": ">=", "value": "2015-01-01"}, new_filters = combine_two_comparison_filters( init_comparison_filter, runtime_comparison_filter, "AND" ) # Output: { "operator": "AND", "conditions": [ {"field": "meta.type", "operator": "==", "value": "article"}, {"field": "meta.date", "operator": ">=", "value": "2015-01-01"}, ] } ```""" [end of new definitions in haystack/document_stores/types/filter_policy.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
f4d9c2bb917be0ffe132dffcc2ad4f1b0fcc5967
roboflow__supervision-1340
1,340
roboflow/supervision
null
de896189b83a1f9434c0a37dd9192ee00d2a1283
2024-07-10T10:14:46Z
diff --git a/docs/detection/utils.md b/docs/detection/utils.md index ea98c8683..85fcacda5 100644 --- a/docs/detection/utils.md +++ b/docs/detection/utils.md @@ -80,6 +80,18 @@ comments: true <h2><a href="#supervision.detection.utils.contains_holes">contains_holes</a></h2> </div> +:::supervision.detection.utils.xywh_to_xyxy + +<div class="md-typeset"> + <h2><a href="#supervision.detection.utils.xywh_to_xyxy">xywh_to_xyxy</a></h2> +</div> + +:::supervision.detection.utils.xcycwh_to_xyxy + +<div class="md-typeset"> + <h2><a href="#supervision.detection.utils.xcycwh_to_xyxy">xcycwh_to_xyxy</a></h2> +</div> + :::supervision.detection.utils.contains_holes <div class="md-typeset"> diff --git a/supervision/__init__.py b/supervision/__init__.py index 4f28d49f4..a4126f31a 100644 --- a/supervision/__init__.py +++ b/supervision/__init__.py @@ -67,6 +67,8 @@ polygon_to_mask, polygon_to_xyxy, scale_boxes, + xcycwh_to_xyxy, + xywh_to_xyxy, ) from supervision.draw.color import Color, ColorPalette from supervision.draw.utils import ( diff --git a/supervision/detection/core.py b/supervision/detection/core.py index 61a08b7e2..48711bce1 100644 --- a/supervision/detection/core.py +++ b/supervision/detection/core.py @@ -686,7 +686,7 @@ def from_sam(cls, sam_result: List[dict]) -> Detections: if np.asarray(xywh).shape[0] == 0: return cls.empty() - xyxy = xywh_to_xyxy(boxes_xywh=xywh) + xyxy = xywh_to_xyxy(xywh=xywh) return cls(xyxy=xyxy, mask=mask) @classmethod diff --git a/supervision/detection/utils.py b/supervision/detection/utils.py index 5b92aedd9..e7090be3e 100644 --- a/supervision/detection/utils.py +++ b/supervision/detection/utils.py @@ -228,10 +228,78 @@ def pad_boxes(xyxy: np.ndarray, px: int, py: Optional[int] = None) -> np.ndarray return result -def xywh_to_xyxy(boxes_xywh: np.ndarray) -> np.ndarray: - xyxy = boxes_xywh.copy() - xyxy[:, 2] = boxes_xywh[:, 0] + boxes_xywh[:, 2] - xyxy[:, 3] = boxes_xywh[:, 1] + boxes_xywh[:, 3] +def xywh_to_xyxy(xywh: np.ndarray) -> np.ndarray: + """ + Converts bounding box coordinates from `(x, y, width, height)` + format to `(x_min, y_min, x_max, y_max)` format. + + Args: + xywh (np.ndarray): A numpy array of shape `(N, 4)` where each row + corresponds to a bounding box in the format `(x, y, width, height)`. + + Returns: + np.ndarray: A numpy array of shape `(N, 4)` where each row corresponds + to a bounding box in the format `(x_min, y_min, x_max, y_max)`. + + Examples: + ```python + import numpy as np + import supervision as sv + + xywh = np.array([ + [10, 20, 30, 40], + [15, 25, 35, 45] + ]) + + sv.xywh_to_xyxy(xywh=xywh) + # array([ + # [10, 20, 40, 60], + # [15, 25, 50, 70] + # ]) + ``` + """ + xyxy = xywh.copy() + xyxy[:, 2] = xywh[:, 0] + xywh[:, 2] + xyxy[:, 3] = xywh[:, 1] + xywh[:, 3] + return xyxy + + +def xcycwh_to_xyxy(xcycwh: np.ndarray) -> np.ndarray: + """ + Converts bounding box coordinates from `(center_x, center_y, width, height)` + format to `(x_min, y_min, x_max, y_max)` format. + + Args: + xcycwh (np.ndarray): A numpy array of shape `(N, 4)` where each row + corresponds to a bounding box in the format `(center_x, center_y, width, + height)`. + + Returns: + np.ndarray: A numpy array of shape `(N, 4)` where each row corresponds + to a bounding box in the format `(x_min, y_min, x_max, y_max)`. + + Examples: + ```python + import numpy as np + import supervision as sv + + xcycwh = np.array([ + [50, 50, 20, 30], + [30, 40, 10, 15] + ]) + + sv.xcycwh_to_xyxy(xcycwh=xcycwh) + # array([ + # [40, 35, 60, 65], + # [25, 32.5, 35, 47.5] + # ]) + ``` + """ + xyxy = xcycwh.copy() + xyxy[:, 0] = xcycwh[:, 0] - xcycwh[:, 2] / 2 + xyxy[:, 1] = xcycwh[:, 1] - xcycwh[:, 3] / 2 + xyxy[:, 2] = xcycwh[:, 0] + xcycwh[:, 2] / 2 + xyxy[:, 3] = xcycwh[:, 1] + xcycwh[:, 3] / 2 return xyxy
diff --git a/test/detection/test_utils.py b/test/detection/test_utils.py index 20c818e61..9224c6760 100644 --- a/test/detection/test_utils.py +++ b/test/detection/test_utils.py @@ -17,6 +17,8 @@ move_boxes, process_roboflow_result, scale_boxes, + xcycwh_to_xyxy, + xywh_to_xyxy, ) TEST_MASK = np.zeros((1, 1000, 1000), dtype=bool) @@ -1090,3 +1092,49 @@ def test_contains_multiple_segments( with exception: result = contains_multiple_segments(mask=mask, connectivity=connectivity) assert result == expected_result + + +@pytest.mark.parametrize( + "xywh, expected_result", + [ + (np.array([[10, 20, 30, 40]]), np.array([[10, 20, 40, 60]])), # standard case + (np.array([[0, 0, 0, 0]]), np.array([[0, 0, 0, 0]])), # zero size bounding box + ( + np.array([[50, 50, 100, 100]]), + np.array([[50, 50, 150, 150]]), + ), # large bounding box + ( + np.array([[-10, -20, 30, 40]]), + np.array([[-10, -20, 20, 20]]), + ), # negative coordinates + (np.array([[50, 50, 0, 30]]), np.array([[50, 50, 50, 80]])), # zero width + (np.array([[50, 50, 20, 0]]), np.array([[50, 50, 70, 50]])), # zero height + (np.array([]).reshape(0, 4), np.array([]).reshape(0, 4)), # empty array + ], +) +def test_xywh_to_xyxy(xywh: np.ndarray, expected_result: np.ndarray) -> None: + result = xywh_to_xyxy(xywh) + np.testing.assert_array_equal(result, expected_result) + + +@pytest.mark.parametrize( + "xcycwh, expected_result", + [ + (np.array([[50, 50, 20, 30]]), np.array([[40, 35, 60, 65]])), # standard case + (np.array([[0, 0, 0, 0]]), np.array([[0, 0, 0, 0]])), # zero size bounding box + ( + np.array([[50, 50, 100, 100]]), + np.array([[0, 0, 100, 100]]), + ), # large bounding box centered at (50, 50) + ( + np.array([[-10, -10, 20, 30]]), + np.array([[-20, -25, 0, 5]]), + ), # negative coordinates + (np.array([[50, 50, 0, 30]]), np.array([[50, 35, 50, 65]])), # zero width + (np.array([[50, 50, 20, 0]]), np.array([[40, 50, 60, 50]])), # zero height + (np.array([]).reshape(0, 4), np.array([]).reshape(0, 4)), # empty array + ], +) +def test_xcycwh_to_xyxy(xcycwh: np.ndarray, expected_result: np.ndarray) -> None: + result = xcycwh_to_xyxy(xcycwh) + np.testing.assert_array_equal(result, expected_result)
diff --git a/docs/detection/utils.md b/docs/detection/utils.md index ea98c8683..85fcacda5 100644 --- a/docs/detection/utils.md +++ b/docs/detection/utils.md @@ -80,6 +80,18 @@ comments: true <h2><a href="#supervision.detection.utils.contains_holes">contains_holes</a></h2> </div> +:::supervision.detection.utils.xywh_to_xyxy + +<div class="md-typeset"> + <h2><a href="#supervision.detection.utils.xywh_to_xyxy">xywh_to_xyxy</a></h2> +</div> + +:::supervision.detection.utils.xcycwh_to_xyxy + +<div class="md-typeset"> + <h2><a href="#supervision.detection.utils.xcycwh_to_xyxy">xcycwh_to_xyxy</a></h2> +</div> + :::supervision.detection.utils.contains_holes <div class="md-typeset">
[ { "components": [ { "doc": "Converts bounding box coordinates from `(center_x, center_y, width, height)`\nformat to `(x_min, y_min, x_max, y_max)` format.\n\nArgs:\n xcycwh (np.ndarray): A numpy array of shape `(N, 4)` where each row\n corresponds to a bounding box in the format `(center_x, center_y, width,\n height)`.\n\nReturns:\n np.ndarray: A numpy array of shape `(N, 4)` where each row corresponds\n to a bounding box in the format `(x_min, y_min, x_max, y_max)`.\n\nExamples:\n ```python\n import numpy as np\n import supervision as sv\n\n xcycwh = np.array([\n [50, 50, 20, 30],\n [30, 40, 10, 15]\n ])\n\n sv.xcycwh_to_xyxy(xcycwh=xcycwh)\n # array([\n # [40, 35, 60, 65],\n # [25, 32.5, 35, 47.5]\n # ])\n ```", "lines": [ 267, 303 ], "name": "xcycwh_to_xyxy", "signature": "def xcycwh_to_xyxy(xcycwh: np.ndarray) -> np.ndarray:", "type": "function" } ], "file": "supervision/detection/utils.py" } ]
[ "test/detection/test_utils.py::test_clip_boxes[xyxy0-resolution_wh0-expected_result0]", "test/detection/test_utils.py::test_clip_boxes[xyxy1-resolution_wh1-expected_result1]", "test/detection/test_utils.py::test_clip_boxes[xyxy2-resolution_wh2-expected_result2]", "test/detection/test_utils.py::test_clip_boxes[xyxy3-resolution_wh3-expected_result3]", "test/detection/test_utils.py::test_clip_boxes[xyxy4-resolution_wh4-expected_result4]", "test/detection/test_utils.py::test_clip_boxes[xyxy5-resolution_wh5-expected_result5]", "test/detection/test_utils.py::test_filter_polygons_by_area[polygons0-None-None-expected_result0-exception0]", "test/detection/test_utils.py::test_filter_polygons_by_area[polygons1-50-None-expected_result1-exception1]", "test/detection/test_utils.py::test_filter_polygons_by_area[polygons2-None-50-expected_result2-exception2]", "test/detection/test_utils.py::test_filter_polygons_by_area[polygons3-200-None-expected_result3-exception3]", "test/detection/test_utils.py::test_filter_polygons_by_area[polygons4-None-200-expected_result4-exception4]", "test/detection/test_utils.py::test_filter_polygons_by_area[polygons5-200-200-expected_result5-exception5]", "test/detection/test_utils.py::test_filter_polygons_by_area[polygons6-100-100-expected_result6-exception6]", "test/detection/test_utils.py::test_filter_polygons_by_area[polygons7-400-400-expected_result7-exception7]", "test/detection/test_utils.py::test_process_roboflow_result[roboflow_result0-expected_result0-exception0]", "test/detection/test_utils.py::test_process_roboflow_result[roboflow_result1-expected_result1-exception1]", "test/detection/test_utils.py::test_process_roboflow_result[roboflow_result2-expected_result2-exception2]", "test/detection/test_utils.py::test_process_roboflow_result[roboflow_result3-expected_result3-exception3]", "test/detection/test_utils.py::test_process_roboflow_result[roboflow_result4-expected_result4-exception4]", "test/detection/test_utils.py::test_process_roboflow_result[roboflow_result5-expected_result5-exception5]", "test/detection/test_utils.py::test_process_roboflow_result[roboflow_result6-expected_result6-exception6]", "test/detection/test_utils.py::test_move_boxes[xyxy0-offset0-expected_result0-exception0]", "test/detection/test_utils.py::test_move_boxes[xyxy1-offset1-expected_result1-exception1]", "test/detection/test_utils.py::test_move_boxes[xyxy2-offset2-expected_result2-exception2]", "test/detection/test_utils.py::test_move_boxes[xyxy3-offset3-expected_result3-exception3]", "test/detection/test_utils.py::test_move_boxes[xyxy4-offset4-expected_result4-exception4]", "test/detection/test_utils.py::test_scale_boxes[xyxy0-2.0-expected_result0-exception0]", "test/detection/test_utils.py::test_scale_boxes[xyxy1-1.0-expected_result1-exception1]", "test/detection/test_utils.py::test_scale_boxes[xyxy2-2.0-expected_result2-exception2]", "test/detection/test_utils.py::test_scale_boxes[xyxy3-0.5-expected_result3-exception3]", "test/detection/test_utils.py::test_scale_boxes[xyxy4-2.0-expected_result4-exception4]", "test/detection/test_utils.py::test_calculate_masks_centroids[masks0-expected_result0-exception0]", "test/detection/test_utils.py::test_calculate_masks_centroids[masks1-expected_result1-exception1]", "test/detection/test_utils.py::test_calculate_masks_centroids[masks2-expected_result2-exception2]", "test/detection/test_utils.py::test_calculate_masks_centroids[masks3-expected_result3-exception3]", "test/detection/test_utils.py::test_calculate_masks_centroids[masks4-expected_result4-exception4]", "test/detection/test_utils.py::test_merge_data[data_list0-expected_result0-exception0]", "test/detection/test_utils.py::test_merge_data[data_list1-expected_result1-exception1]", "test/detection/test_utils.py::test_merge_data[data_list2-expected_result2-exception2]", "test/detection/test_utils.py::test_merge_data[data_list3-expected_result3-exception3]", "test/detection/test_utils.py::test_merge_data[data_list4-expected_result4-exception4]", "test/detection/test_utils.py::test_merge_data[data_list5-expected_result5-exception5]", "test/detection/test_utils.py::test_merge_data[data_list6-expected_result6-exception6]", "test/detection/test_utils.py::test_merge_data[data_list7-expected_result7-exception7]", "test/detection/test_utils.py::test_merge_data[data_list8-expected_result8-exception8]", "test/detection/test_utils.py::test_merge_data[data_list9-expected_result9-exception9]", "test/detection/test_utils.py::test_merge_data[data_list10-expected_result10-exception10]", "test/detection/test_utils.py::test_merge_data[data_list11-None-exception11]", "test/detection/test_utils.py::test_merge_data[data_list12-expected_result12-exception12]", "test/detection/test_utils.py::test_merge_data[data_list13-expected_result13-exception13]", "test/detection/test_utils.py::test_merge_data[data_list14-expected_result14-exception14]", "test/detection/test_utils.py::test_merge_data[data_list15-expected_result15-exception15]", "test/detection/test_utils.py::test_merge_data[data_list16-None-exception16]", "test/detection/test_utils.py::test_merge_data[data_list17-None-exception17]", "test/detection/test_utils.py::test_merge_data[data_list18-None-exception18]", "test/detection/test_utils.py::test_merge_data[data_list19-expected_result19-exception19]", "test/detection/test_utils.py::test_merge_data[data_list20-None-exception20]", "test/detection/test_utils.py::test_merge_data[data_list21-None-exception21]", "test/detection/test_utils.py::test_merge_data[data_list22-None-exception22]", "test/detection/test_utils.py::test_merge_data[data_list23-None-exception23]", "test/detection/test_utils.py::test_get_data_item[data0-0-expected_result0-exception0]", "test/detection/test_utils.py::test_get_data_item[data1-0-expected_result1-exception1]", "test/detection/test_utils.py::test_get_data_item[data2-0-expected_result2-exception2]", "test/detection/test_utils.py::test_get_data_item[data3-index3-expected_result3-exception3]", "test/detection/test_utils.py::test_get_data_item[data4-index4-expected_result4-exception4]", "test/detection/test_utils.py::test_get_data_item[data5--1-expected_result5-exception5]", "test/detection/test_utils.py::test_get_data_item[data6--1-expected_result6-exception6]", "test/detection/test_utils.py::test_get_data_item[data7-index7-expected_result7-exception7]", "test/detection/test_utils.py::test_get_data_item[data8-index8-expected_result8-exception8]", "test/detection/test_utils.py::test_get_data_item[data9-index9-expected_result9-exception9]", "test/detection/test_utils.py::test_get_data_item[data10-index10-expected_result10-exception10]", "test/detection/test_utils.py::test_get_data_item[data11-index11-expected_result11-exception11]", "test/detection/test_utils.py::test_get_data_item[data12-index12-expected_result12-exception12]", "test/detection/test_utils.py::test_get_data_item[data13-index13-expected_result13-exception13]", "test/detection/test_utils.py::test_get_data_item[data14-0-expected_result14-exception14]", "test/detection/test_utils.py::test_get_data_item[data15--1-expected_result15-exception15]", "test/detection/test_utils.py::test_get_data_item[data16-index16-expected_result16-exception16]", "test/detection/test_utils.py::test_contains_holes[mask0-False-exception0]", "test/detection/test_utils.py::test_contains_holes[mask1-False-exception1]", "test/detection/test_utils.py::test_contains_holes[mask2-False-exception2]", "test/detection/test_utils.py::test_contains_holes[mask3-False-exception3]", "test/detection/test_utils.py::test_contains_holes[mask4-True-exception4]", "test/detection/test_utils.py::test_contains_holes[mask5-True-exception5]", "test/detection/test_utils.py::test_contains_multiple_segments[mask0-4-False-exception0]", "test/detection/test_utils.py::test_contains_multiple_segments[mask1-4-True-exception1]", "test/detection/test_utils.py::test_contains_multiple_segments[mask2-4-False-exception2]", "test/detection/test_utils.py::test_contains_multiple_segments[mask3-4-False-exception3]", "test/detection/test_utils.py::test_contains_multiple_segments[mask4-4-False-exception4]", "test/detection/test_utils.py::test_contains_multiple_segments[mask5-4-True-exception5]", "test/detection/test_utils.py::test_contains_multiple_segments[mask6-8-False-exception6]", "test/detection/test_utils.py::test_contains_multiple_segments[mask7-5-None-exception7]", "test/detection/test_utils.py::test_xywh_to_xyxy[xywh0-expected_result0]", "test/detection/test_utils.py::test_xywh_to_xyxy[xywh1-expected_result1]", "test/detection/test_utils.py::test_xywh_to_xyxy[xywh2-expected_result2]", "test/detection/test_utils.py::test_xywh_to_xyxy[xywh3-expected_result3]", "test/detection/test_utils.py::test_xywh_to_xyxy[xywh4-expected_result4]", "test/detection/test_utils.py::test_xywh_to_xyxy[xywh5-expected_result5]", "test/detection/test_utils.py::test_xywh_to_xyxy[xywh6-expected_result6]", "test/detection/test_utils.py::test_xcycwh_to_xyxy[xcycwh0-expected_result0]", "test/detection/test_utils.py::test_xcycwh_to_xyxy[xcycwh1-expected_result1]", "test/detection/test_utils.py::test_xcycwh_to_xyxy[xcycwh2-expected_result2]", "test/detection/test_utils.py::test_xcycwh_to_xyxy[xcycwh3-expected_result3]", "test/detection/test_utils.py::test_xcycwh_to_xyxy[xcycwh4-expected_result4]", "test/detection/test_utils.py::test_xcycwh_to_xyxy[xcycwh5-expected_result5]", "test/detection/test_utils.py::test_xcycwh_to_xyxy[xcycwh6-expected_result6]" ]
[]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> `xywh_to_xyxy` and `xcycwh_to_xyxy` box utils # Description Updated `xywh_to_xyxy` and added `xcycwh_to_xyxy` box utils. ## Type of change Please delete options that are not relevant. - [ ] Bug fix (non-breaking change which fixes an issue) - [x] New feature (non-breaking change which adds functionality) - [x] This change requires a documentation update ## Docs - [x] Docs updated? What were the changes: ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in supervision/detection/utils.py] (definition of xcycwh_to_xyxy:) def xcycwh_to_xyxy(xcycwh: np.ndarray) -> np.ndarray: """Converts bounding box coordinates from `(center_x, center_y, width, height)` format to `(x_min, y_min, x_max, y_max)` format. Args: xcycwh (np.ndarray): A numpy array of shape `(N, 4)` where each row corresponds to a bounding box in the format `(center_x, center_y, width, height)`. Returns: np.ndarray: A numpy array of shape `(N, 4)` where each row corresponds to a bounding box in the format `(x_min, y_min, x_max, y_max)`. Examples: ```python import numpy as np import supervision as sv xcycwh = np.array([ [50, 50, 20, 30], [30, 40, 10, 15] ]) sv.xcycwh_to_xyxy(xcycwh=xcycwh) # array([ # [40, 35, 60, 65], # [25, 32.5, 35, 47.5] # ]) ```""" [end of new definitions in supervision/detection/utils.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
3eb5c0b024e3e46877b7fe4fd66e6177d1308ba0
pgmpy__pgmpy-1797
1,797
pgmpy/pgmpy
null
336c144b95aa21718e1898930934eb63474d1caf
2024-07-05T15:20:32Z
diff --git a/pgmpy/utils/__init__.py b/pgmpy/utils/__init__.py index adf8bb667..22d901b77 100644 --- a/pgmpy/utils/__init__.py +++ b/pgmpy/utils/__init__.py @@ -2,7 +2,7 @@ from .mathext import cartesian, sample_discrete from .optimizer import optimize, pinverse from .state_name import StateNameMixin -from .utils import discretize, get_example_model +from .utils import discretize, get_example_model, llm_pairwise_orient __all__ = [ "cartesian", @@ -14,4 +14,5 @@ "pinverse", "get_example_model", "discretize", + "llm_pairwise_orient", ] diff --git a/pgmpy/utils/utils.py b/pgmpy/utils/utils.py index 35b465a8c..f568f7a18 100644 --- a/pgmpy/utils/utils.py +++ b/pgmpy/utils/utils.py @@ -1,5 +1,7 @@ import gzip +import os +import google.generativeai as genai import pandas as pd try: @@ -175,3 +177,57 @@ def discretize(data, cardinality, labels=dict(), method="rounding"): ) return df_copy + + +def llm_pairwise_orient( + x, y, descriptions, domain=None, llm_model="gemini-1.5-flash", **kwargs +): + """ + Asks a Large Language Model (LLM) for the orientation of an edge between `x` and `y`. + + Parameters + ---------- + x: str + The first variable's name + + y: str + The second variable's name + + description: dict + A dict of the form {variable: description} containing text description of the variables. + + domain: str + The domain of the variables. The LLM is prompted to be an expert in the domain. + + llm: str (default: gemini) + The LLM to use. Currently only Google's gemini is supported. + """ + if llm_model.startswith("gemini"): + if "GEMINI_API_KEY" not in os.environ: + raise ValueError( + "Please set GEMINI_API_KEY environment variable with the API key to use" + ) + + genai.configure(api_key=os.environ["GEMINI_API_KEY"]) + model = genai.GenerativeModel(model_name=llm_model) + + prompt = f""" You are an expert in {domain}. You are given two variables with the following descriptions: + <A>: {descriptions[x]} + <B>: {descriptions[y]} + + Which of the following two options is the most likely causal direction between them: + 1. <A> causes <B> + 2. <B> causes <A> + + Return a single letter answer between the choices above. I do not need the reasoning behind it. Do not add any formatting in the answer. + """ + response = model.generate_content([prompt]) + response_txt = response.text.strip().lower().replace("*", "") + if response_txt in ("a", "1"): + return (x, y) + elif response_txt in ("b", "2"): + return (y, x) + else: + raise ValueError( + "Results from the LLM are unclear. Try calling the function again." + ) diff --git a/requirements/runtime.txt b/requirements/runtime.txt index c91b5f241..b4f6f5af6 100644 --- a/requirements/runtime.txt +++ b/requirements/runtime.txt @@ -10,3 +10,4 @@ tqdm>=4.64 joblib>=1.2 opt_einsum>=3.3 xgboost>=2.0.3 +google-generativeai>=0.7.1
diff --git a/pgmpy/tests/test_utils/test_utils.py b/pgmpy/tests/test_utils/test_utils.py index 1ab6e78a0..38b1041dd 100644 --- a/pgmpy/tests/test_utils/test_utils.py +++ b/pgmpy/tests/test_utils/test_utils.py @@ -1,11 +1,13 @@ +import os import random import unittest import numpy as np import pandas as pd +import pytest from tqdm.auto import tqdm -from pgmpy.utils import discretize, get_example_model +from pgmpy.utils import discretize, get_example_model, llm_pairwise_orient class TestDAGCreation(unittest.TestCase): @@ -67,3 +69,36 @@ def test_rounding_disc(self): self.assertEqual(df_disc["X"].nunique(), 5) self.assertEqual(df_disc["Y"].nunique(), 4) self.assertEqual(df_disc["Z"].nunique(), 3) + + +class TestPairwiseOrientation(unittest.TestCase): + @pytest.mark.skipif( + "GEMINI_API_KEY" not in os.environ, reason="Gemini API key is not set" + ) + def test_llm(self): + descriptions = { + "Age": "The age of a person", + "Workclass": "The workplace where the person is employed such as Private industry, or self employed", + "Education": "The highest level of education the person has finished", + "MaritalStatus": "The marital status of the person", + "Occupation": "The kind of job the person does. For example, sales, craft repair, clerical", + "Relationship": "The relationship status of the person", + "Race": "The ethnicity of the person", + "Sex": "The sex or gender of the person", + "HoursPerWeek": "The number of hours per week the person works", + "NativeCountry": "The native country of the person", + "Income": "The income i.e. amount of money the person makes", + } + + self.assertEqual( + llm_pairwise_orient( + x="Age", y="Income", descriptions=descriptions, domain="Social Sciences" + ), + ("Age", "Income"), + ) + self.assertEqual( + llm_pairwise_orient( + x="Income", y="Age", descriptions=descriptions, domain="Social Sciences" + ), + ("Age", "Income"), + )
diff --git a/requirements/runtime.txt b/requirements/runtime.txt index c91b5f241..b4f6f5af6 100644 --- a/requirements/runtime.txt +++ b/requirements/runtime.txt @@ -10,3 +10,4 @@ tqdm>=4.64 joblib>=1.2 opt_einsum>=3.3 xgboost>=2.0.3 +google-generativeai>=0.7.1
[ { "components": [ { "doc": "Asks a Large Language Model (LLM) for the orientation of an edge between `x` and `y`.\n\nParameters\n----------\nx: str\n The first variable's name\n\ny: str\n The second variable's name\n\ndescription: dict\n A dict of the form {variable: description} containing text description of the variables.\n\ndomain: str\n The domain of the variables. The LLM is prompted to be an expert in the domain.\n\nllm: str (default: gemini)\n The LLM to use. Currently only Google's gemini is supported.", "lines": [ 182, 232 ], "name": "llm_pairwise_orient", "signature": "def llm_pairwise_orient( x, y, descriptions, domain=None, llm_model=\"gemini-1.5-flash\", **kwargs ):", "type": "function" } ], "file": "pgmpy/utils/utils.py" } ]
[ "pgmpy/tests/test_utils/test_utils.py::TestDAGCreation::test_get_example_model", "pgmpy/tests/test_utils/test_utils.py::TestDiscretization::test_rounding_disc" ]
[]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> Adds an LLM based pairwise orientation method ### Your checklist for this pull request Please review the [guidelines for contributing](CONTRIBUTING.md) to this repository. - [ ] Make sure you are requesting to **pull a topic/feature/bugfix branch** (right side). Don't request your master! - [ ] Make sure you are making a pull request against the **dev branch** (left side). Also you should start *your branch* off *our dev*. - [ ] Check the commit's or even all commits' message styles matches our requested structure. ### Issue number(s) that this pull request fixes - Fixes # ### List of changes to the codebase in this pull request - - - ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in pgmpy/utils/utils.py] (definition of llm_pairwise_orient:) def llm_pairwise_orient( x, y, descriptions, domain=None, llm_model="gemini-1.5-flash", **kwargs ): """Asks a Large Language Model (LLM) for the orientation of an edge between `x` and `y`. Parameters ---------- x: str The first variable's name y: str The second variable's name description: dict A dict of the form {variable: description} containing text description of the variables. domain: str The domain of the variables. The LLM is prompted to be an expert in the domain. llm: str (default: gemini) The LLM to use. Currently only Google's gemini is supported.""" [end of new definitions in pgmpy/utils/utils.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
cf8d0f12e2e5be62b01ff8fded85f3f64eab1e84
astropy__astropy-16677
16,677
astropy/astropy
v5.3
f5126c765a6a8db8abc7504275d9c2e90ffbd526
2024-07-04T20:45:35Z
diff --git a/astropy/modeling/core.py b/astropy/modeling/core.py index b469f32cdf72..f0fd3619f2d4 100644 --- a/astropy/modeling/core.py +++ b/astropy/modeling/core.py @@ -747,6 +747,10 @@ def __init__(self, *args, meta=None, name=None, **kwargs): self._initialize_slices() self._initialize_unit_support() + # Initialize the cache for the constraints (used primarily when + # sync_constraints is False) + self._constraints_cache = {} + def _default_inputs_outputs(self): if self.n_inputs == 1 and self.n_outputs == 1: self._inputs = ("x",) @@ -1293,14 +1297,30 @@ def sync_constraints(self, value): raise ValueError("sync_constraints only accepts True or False as values") self._sync_constraints = value + # We need to invalidate the cache whenever sync_constraints is changed. + # If we are setting sync_constraints to True, then this will ensure + # that we recompute the properties next time they are called, and if + # setting to False, it will allow us to make sure the cache is up-to-date + # below before disabling syncing. + self._constraints_cache.clear() + + # If setting to False, cache all the values with the present state + # to make sure we don't ever update the cache once the syncing is + # disabled. Note that these will automatically then cause 'fixed', + # 'bounds' and 'tied' to be called. + if not value: + _ = self.has_fixed + _ = self.has_bounds + _ = self.has_tied + @property def fixed(self): """ A ``dict`` mapping parameter names to their fixed constraint. """ - if not hasattr(self, "_fixed") or self.sync_constraints: - self._fixed = _ConstraintsDict(self, "fixed") - return self._fixed + if "fixed" not in self._constraints_cache or self.sync_constraints: + self._constraints_cache["fixed"] = _ConstraintsDict(self, "fixed") + return self._constraints_cache["fixed"] @property def bounds(self): @@ -1308,18 +1328,47 @@ def bounds(self): A ``dict`` mapping parameter names to their upper and lower bounds as ``(min, max)`` tuples or ``[min, max]`` lists. """ - if not hasattr(self, "_bounds") or self.sync_constraints: - self._bounds = _ConstraintsDict(self, "bounds") - return self._bounds + if "bounds" not in self._constraints_cache or self.sync_constraints: + self._constraints_cache["bounds"] = _ConstraintsDict(self, "bounds") + return self._constraints_cache["bounds"] @property def tied(self): """ A ``dict`` mapping parameter names to their tied constraint. """ - if not hasattr(self, "_tied") or self.sync_constraints: - self._tied = _ConstraintsDict(self, "tied") - return self._tied + if "tied" not in self._constraints_cache or self.sync_constraints: + self._constraints_cache["tied"] = _ConstraintsDict(self, "tied") + return self._constraints_cache["tied"] + + @property + def has_fixed(self): + """ + Whether the model has any fixed constraints. + """ + if "has_fixed" not in self._constraints_cache or self.sync_constraints: + self._constraints_cache["has_fixed"] = any(self.fixed.values()) + return self._constraints_cache["has_fixed"] + + @property + def has_bounds(self): + """ + Whether the model has any bounds constraints. + """ + if "has_bounds" not in self._constraints_cache or self.sync_constraints: + self._constraints_cache["has_bounds"] = any( + b != (None, None) for b in self.bounds.values() + ) + return self._constraints_cache["has_bounds"] + + @property + def has_tied(self): + """ + Whether the model has any tied constraints. + """ + if "has_tied" not in self._constraints_cache or self.sync_constraints: + self._constraints_cache["has_tied"] = any(self.tied.values()) + return self._constraints_cache["has_tied"] @property def eqcons(self): @@ -3171,6 +3220,10 @@ def __init__(self, op, left, right, name=None): self.n_left_params = len(self.left.parameters) self._map_parameters() + # Initialize the cache for the constraints (used primarily when + # sync_constraints is False) + self._constraints_cache = {} + def _get_left_inputs_from_args(self, args): return args[: self.left.n_inputs] diff --git a/astropy/modeling/fitting.py b/astropy/modeling/fitting.py index 84d8866d0260..a0c6c34b45a6 100644 --- a/astropy/modeling/fitting.py +++ b/astropy/modeling/fitting.py @@ -1176,7 +1176,7 @@ def _wrap_deriv(params, model, weights, x, y, z=None): if weights is None: weights = 1.0 - if any(model.fixed.values()) or any(model.tied.values()): + if model.has_fixed or model.has_tied: # update the parameters with the current values from the fitter fitter_to_model_params(model, params) if z is None: @@ -2002,9 +2002,9 @@ def fitter_to_model_params(model, fps, use_min_max_bounds=True): """ _, fit_param_indices, _ = model_to_fit_params(model) - has_tied = any(model.tied.values()) - has_fixed = any(model.fixed.values()) - has_bound = any(b != (None, None) for b in model.bounds.values()) + has_tied = model.has_tied + has_fixed = model.has_fixed + has_bound = model.has_bounds parameters = model.parameters if not (has_tied or has_fixed or has_bound): @@ -2069,7 +2069,7 @@ def model_to_fit_params(model): fitparam_indices = list(range(len(model.param_names))) model_params = model.parameters model_bounds = list(model.bounds.values()) - if any(model.fixed.values()) or any(model.tied.values()): + if model.has_fixed or model.has_tied: params = list(model_params) param_metrics = model._param_metrics for idx, name in list(enumerate(model.param_names))[::-1]: @@ -2100,16 +2100,13 @@ def _validate_constraints(supported_constraints, model): """Make sure model constraints are supported by the current fitter.""" message = "Optimizer cannot handle {0} constraints." - if any(model.fixed.values()) and "fixed" not in supported_constraints: + if model.has_fixed and "fixed" not in supported_constraints: raise UnsupportedConstraintError(message.format("fixed parameter")) - if any(model.tied.values()) and "tied" not in supported_constraints: + if model.has_tied and "tied" not in supported_constraints: raise UnsupportedConstraintError(message.format("tied parameter")) - if ( - any(tuple(b) != (None, None) for b in model.bounds.values()) - and "bounds" not in supported_constraints - ): + if model.has_bounds and "bounds" not in supported_constraints: raise UnsupportedConstraintError(message.format("bound parameter")) if model.eqcons and "eqcons" not in supported_constraints: diff --git a/docs/changes/modeling/16677.feature.rst b/docs/changes/modeling/16677.feature.rst new file mode 100644 index 000000000000..8c7d14e8555d --- /dev/null +++ b/docs/changes/modeling/16677.feature.rst @@ -0,0 +1,3 @@ +Added ``Model.has_tied``, ``Model.has_fixed``, and ``Model.has_bounds`` attributes to make +it easy to check whether models have various kinds of constraints set without having to +inspect ``Model.tied``, ``Model.fixed``, and ``Model.bounds`` in detail.
diff --git a/astropy/modeling/tests/test_core.py b/astropy/modeling/tests/test_core.py index d1dbe011a61e..097a35cd60d2 100644 --- a/astropy/modeling/tests/test_core.py +++ b/astropy/modeling/tests/test_core.py @@ -1505,3 +1505,68 @@ def test_model_string_indexing(): assert compound["Model1"] == gauss assert compound["Model2"] == airy + + +def test_has_constraints(): + model1 = models.Gaussian1D() + + assert not model1.has_tied + assert not model1.has_fixed + assert model1.has_bounds + + model1.amplitude.fixed = True + + assert model1.has_fixed + + model1.mean.tied = lambda model: model.amplitude + + assert model1.has_tied + + model2 = models.Linear1D() + + assert not model2.has_tied + assert not model2.has_fixed + assert not model2.has_bounds + + model2.slope.bounds = (1, 2) + + assert model2.has_bounds + + +def test_has_constraints_with_sync_constraints(): + # Check that has_tied/has_fixed/has_bounds works when sync_constraints is used + + model = models.Linear1D() + + assert not model.has_tied + assert not model.has_fixed + assert not model.has_bounds + + model.sync_constraints = False + + model.slope.fixed = True + model.intercept.tied = lambda model: model.slope + model.intercept.bounds = (1, 2) + + assert not model.has_tied + assert not model.has_fixed + assert not model.has_bounds + + model.slope.fixed = False + + model.sync_constraints = True + + assert model.has_tied + assert not model.has_fixed + assert model.has_bounds + + model.slope.fixed = True + + # If we set sync_constraints to False, model.has_fixed should then still + # return the correct result because the above line was called before + # sync_constraints was set to False. Basically we need any change in + # sync_constraints to invalidate the cache. + + model.sync_constraints = False + + assert model.has_fixed
diff --git a/docs/changes/modeling/16677.feature.rst b/docs/changes/modeling/16677.feature.rst new file mode 100644 index 000000000000..8c7d14e8555d --- /dev/null +++ b/docs/changes/modeling/16677.feature.rst @@ -0,0 +1,3 @@ +Added ``Model.has_tied``, ``Model.has_fixed``, and ``Model.has_bounds`` attributes to make +it easy to check whether models have various kinds of constraints set without having to +inspect ``Model.tied``, ``Model.fixed``, and ``Model.bounds`` in detail.
[ { "components": [ { "doc": "Whether the model has any fixed constraints.", "lines": [ 1345, 1351 ], "name": "Model.has_fixed", "signature": "def has_fixed(self):", "type": "function" }, { "doc": "Whether the model has any bounds constraints.", "lines": [ 1354, 1362 ], "name": "Model.has_bounds", "signature": "def has_bounds(self):", "type": "function" }, { "doc": "Whether the model has any tied constraints.", "lines": [ 1365, 1371 ], "name": "Model.has_tied", "signature": "def has_tied(self):", "type": "function" } ], "file": "astropy/modeling/core.py" } ]
[ "astropy/modeling/tests/test_core.py::test_has_constraints", "astropy/modeling/tests/test_core.py::test_has_constraints_with_sync_constraints" ]
[ "astropy/modeling/tests/test_core.py::test_Model_instance_repr_and_str", "astropy/modeling/tests/test_core.py::test_Model_array_parameter", "astropy/modeling/tests/test_core.py::test_inputless_model", "astropy/modeling/tests/test_core.py::test_ParametericModel", "astropy/modeling/tests/test_core.py::test_custom_model_signature", "astropy/modeling/tests/test_core.py::test_custom_model_subclass", "astropy/modeling/tests/test_core.py::test_custom_model_parametrized_decorator", "astropy/modeling/tests/test_core.py::test_custom_model_n_outputs", "astropy/modeling/tests/test_core.py::test_custom_model_settable_parameters", "astropy/modeling/tests/test_core.py::test_custom_model_regected_parameters", "astropy/modeling/tests/test_core.py::test_custom_inverse", "astropy/modeling/tests/test_core.py::test_custom_inverse_reset", "astropy/modeling/tests/test_core.py::test_render_model_2d", "astropy/modeling/tests/test_core.py::test_render_model_1d", "astropy/modeling/tests/test_core.py::test_render_model_3d", "astropy/modeling/tests/test_core.py::test_render_model_out_dtype", "astropy/modeling/tests/test_core.py::test_custom_bounding_box_1d", "astropy/modeling/tests/test_core.py::test_n_submodels_in_single_models", "astropy/modeling/tests/test_core.py::test_compound_deepcopy", "astropy/modeling/tests/test_core.py::test_rename_path", "astropy/modeling/tests/test_core.py::test_rename_1d[Gaussian1D]", "astropy/modeling/tests/test_core.py::test_rename_1d[Polynomial1D]", "astropy/modeling/tests/test_core.py::test_rename_1d[Shift]", "astropy/modeling/tests/test_core.py::test_rename_1d[Tabular1D]", "astropy/modeling/tests/test_core.py::test_rename_2d[Gaussian2D]", "astropy/modeling/tests/test_core.py::test_rename_2d[Polynomial2D]", "astropy/modeling/tests/test_core.py::test_rename_2d[Tabular2D]", "astropy/modeling/tests/test_core.py::test_fix_inputs_integer", "astropy/modeling/tests/test_core.py::test_fix_inputs_empty_dict", "astropy/modeling/tests/test_core.py::test_rename_inputs_outputs", "astropy/modeling/tests/test_core.py::test__prepare_output_single_model", "astropy/modeling/tests/test_core.py::test_prepare_outputs_mixed_broadcast", "astropy/modeling/tests/test_core.py::test_prepare_outputs_complex_reshape", "astropy/modeling/tests/test_core.py::test_prepare_outputs_single_entry_vector", "astropy/modeling/tests/test_core.py::test_coerce_units", "astropy/modeling/tests/test_core.py::test_bounding_box_general_inverse", "astropy/modeling/tests/test_core.py::test__add_special_operator", "astropy/modeling/tests/test_core.py::test_print_special_operator_CompoundModel", "astropy/modeling/tests/test_core.py::test__validate_input_shape", "astropy/modeling/tests/test_core.py::test__validate_input_shapes", "astropy/modeling/tests/test_core.py::test__remove_axes_from_shape", "astropy/modeling/tests/test_core.py::test_get_bounding_box", "astropy/modeling/tests/test_core.py::test_compound_bounding_box", "astropy/modeling/tests/test_core.py::test_bind_bounding_box", "astropy/modeling/tests/test_core.py::test_bind_compound_bounding_box_using_with_bounding_box_select", "astropy/modeling/tests/test_core.py::test_fix_inputs_compound_bounding_box", "astropy/modeling/tests/test_core.py::test_model_copy_with_bounding_box", "astropy/modeling/tests/test_core.py::test_compound_model_copy_with_bounding_box", "astropy/modeling/tests/test_core.py::test_model_copy_with_compound_bounding_box", "astropy/modeling/tests/test_core.py::test_compound_model_copy_with_compound_bounding_box", "astropy/modeling/tests/test_core.py::test_compound_model_copy_user_attribute", "astropy/modeling/tests/test_core.py::test_model_mixed_array_scalar_bounding_box", "astropy/modeling/tests/test_core.py::test_compound_model_mixed_array_scalar_bounding_box", "astropy/modeling/tests/test_core.py::test_model_with_bounding_box_true_and_single_output", "astropy/modeling/tests/test_core.py::test_compound_model_with_bounding_box_true_and_single_output", "astropy/modeling/tests/test_core.py::test_bounding_box_pass_with_ignored", "astropy/modeling/tests/test_core.py::test_compound_bounding_box_pass_with_ignored", "astropy/modeling/tests/test_core.py::test_model_integer_indexing[int]", "astropy/modeling/tests/test_core.py::test_model_integer_indexing[int32]", "astropy/modeling/tests/test_core.py::test_model_integer_indexing[int64]", "astropy/modeling/tests/test_core.py::test_model_integer_indexing[uint32]", "astropy/modeling/tests/test_core.py::test_model_integer_indexing[uint64]", "astropy/modeling/tests/test_core.py::test_model_string_indexing" ]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> Add ``has_tied``, ``has_fixed`` and ``has_bounds`` properties to ``Model`` *This has been split out from #16673 for ease of review* Models include ``tied``, ``fixed``, and ``bounds`` properties that return dictionaries with a summary of which parameters have constraints. However, sometimes one wants to quickly know whether there are any specified ``tied``, ``fixed``, or ``bounds`` constraints, and the main way to do that is: ```python any(model.fixed.values()) any(model.tied.values()) any(b != (None, None) for b in model.bounds.values()) ``` These appear notably in the fitting code - this turns out to be reasonably expensive operations especially in the fitting code, where they might be called every time the objective function is called, and it is also clunky to repeat this logic several times in different places. This PR adds: ```python Model.has_fixed Model.has_tied Model.has_bounds ``` which simplifies this. In addition, these properties, like ``fixed``, ``tied``, and ``bounds`` are cached and the cached version is used when ``sync_constraints`` is ``False`` (typically during fitting), removing any performance impact. But beyond this, these properties could be generically useful to users, similarly to how we have e.g. ``has_units``, hence why I made these public. - [ ] By checking this box, the PR author has requested that maintainers do **NOT** use the "Squash and Merge" button. Maintainers should respect this when possible; however, the final decision is at the discretion of the maintainer that merges the PR. ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in astropy/modeling/core.py] (definition of Model.has_fixed:) def has_fixed(self): """Whether the model has any fixed constraints.""" (definition of Model.has_bounds:) def has_bounds(self): """Whether the model has any bounds constraints.""" (definition of Model.has_tied:) def has_tied(self): """Whether the model has any tied constraints.""" [end of new definitions in astropy/modeling/core.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
2d281019494aaebf522f6626c0dae37510c16688
deepset-ai__haystack-7933
7,933
deepset-ai/haystack
null
8b9eddcd948e972c844e03000c2802e85e462c2a
2024-06-26T08:47:37Z
diff --git a/haystack/components/preprocessors/document_splitter.py b/haystack/components/preprocessors/document_splitter.py index f5e048db6e..200fa8aa92 100644 --- a/haystack/components/preprocessors/document_splitter.py +++ b/haystack/components/preprocessors/document_splitter.py @@ -90,38 +90,38 @@ def run(self, documents: List[Document]): f"DocumentSplitter only works with text documents but content for document ID {doc.id} is None." ) units = self._split_into_units(doc.content, self.split_by) - text_splits, splits_pages = self._concatenate_units( + text_splits, splits_pages, splits_start_idxs = self._concatenate_units( units, self.split_length, self.split_overlap, self.split_threshold ) metadata = deepcopy(doc.meta) metadata["source_id"] = doc.id split_docs += self._create_docs_from_splits( - text_splits=text_splits, splits_pages=splits_pages, meta=metadata + text_splits=text_splits, splits_pages=splits_pages, splits_start_idxs=splits_start_idxs, meta=metadata ) return {"documents": split_docs} def _split_into_units(self, text: str, split_by: Literal["word", "sentence", "passage", "page"]) -> List[str]: if split_by == "page": - split_at = "\f" + self.split_at = "\f" elif split_by == "passage": - split_at = "\n\n" + self.split_at = "\n\n" elif split_by == "sentence": - split_at = "." + self.split_at = "." elif split_by == "word": - split_at = " " + self.split_at = " " else: raise NotImplementedError( "DocumentSplitter only supports 'word', 'sentence', 'page' or 'passage' split_by options." ) - units = text.split(split_at) + units = text.split(self.split_at) # Add the delimiter back to all units except the last one for i in range(len(units) - 1): - units[i] += split_at + units[i] += self.split_at return units def _concatenate_units( self, elements: List[str], split_length: int, split_overlap: int, split_threshold: int - ) -> Tuple[List[str], List[int]]: + ) -> Tuple[List[str], List[int], List[int]]: """ Concatenates the elements into parts of split_length units. @@ -132,36 +132,90 @@ def _concatenate_units( text_splits: List[str] = [] splits_pages = [] + splits_start_idxs = [] + split_at_len = len(self.split_at) + cur_start_idx = 0 cur_page = 1 segments = windowed(elements, n=split_length, step=split_length - split_overlap) + for seg in segments: current_units = [unit for unit in seg if unit is not None] txt = "".join(current_units) + # check if length of current units is below split_threshold if len(current_units) < split_threshold and len(text_splits) > 0: # concatenate the last split with the current one text_splits[-1] += txt + elif len(txt) > 0: text_splits.append(txt) splits_pages.append(cur_page) + splits_start_idxs.append(cur_start_idx) + processed_units = current_units[: split_length - split_overlap] + cur_start_idx += len("".join(processed_units)) + split_at_len + if self.split_by == "page": num_page_breaks = len(processed_units) else: num_page_breaks = sum(processed_unit.count("\f") for processed_unit in processed_units) + cur_page += num_page_breaks - return text_splits, splits_pages - @staticmethod - def _create_docs_from_splits(text_splits: List[str], splits_pages: List[int], meta: Dict) -> List[Document]: + return text_splits, splits_pages, splits_start_idxs + + def _create_docs_from_splits( + self, text_splits: List[str], splits_pages: List[int], splits_start_idxs: List[int], meta: Dict + ) -> List[Document]: """ Creates Document objects from splits enriching them with page number and the metadata of the original document. """ documents: List[Document] = [] - for i, txt in enumerate(text_splits): + for i, (txt, split_idx) in enumerate(zip(text_splits, splits_start_idxs)): meta = deepcopy(meta) doc = Document(content=txt, meta=meta) doc.meta["page_number"] = splits_pages[i] + doc.meta["split_id"] = i + doc.meta["split_idx_start"] = split_idx documents.append(doc) + + if self.split_overlap <= 0: + continue + + doc.meta["_split_overlap"] = [] + + if i == 0: + continue + + doc_start_idx = splits_start_idxs[i] + previous_doc = documents[i - 1] + previous_doc_start_idx = splits_start_idxs[i - 1] + self._add_split_overlap_information(doc, doc_start_idx, previous_doc, previous_doc_start_idx) + return documents + + @staticmethod + def _add_split_overlap_information( + current_doc: Document, current_doc_start_idx: int, previous_doc: Document, previous_doc_start_idx: int + ): + """ + Adds split overlap information to the current and previous Document's meta. + + :param current_doc: The Document that is being split. + :param current_doc_start_idx: The starting index of the current Document. + :param previous_doc: The Document that was split before the current Document. + :param previous_doc_start_idx: The starting index of the previous Document. + """ + overlapping_range = (current_doc_start_idx - previous_doc_start_idx - 1, len(previous_doc.content) - 1) # type: ignore + + if overlapping_range[0] < overlapping_range[1]: + overlapping_str = previous_doc.content[overlapping_range[0] : overlapping_range[1]] # type: ignore + + if current_doc.content.startswith(overlapping_str): # type: ignore + # add split overlap information to this Document regarding the previous Document + current_doc.meta["_split_overlap"].append({"doc_id": previous_doc.id, "range": overlapping_range}) + + # add split overlap information to previous Document regarding this Document + overlapping_range = (0, overlapping_range[1] - overlapping_range[0]) + previous_doc.meta["_split_overlap"].append({"doc_id": current_doc.id, "range": overlapping_range}) diff --git a/releasenotes/notes/add-split_id_and_overlap_to_DocumentSplitter-8180ad8f13495741.yaml b/releasenotes/notes/add-split_id_and_overlap_to_DocumentSplitter-8180ad8f13495741.yaml new file mode 100644 index 0000000000..e3eba2d57b --- /dev/null +++ b/releasenotes/notes/add-split_id_and_overlap_to_DocumentSplitter-8180ad8f13495741.yaml @@ -0,0 +1,4 @@ +--- +features: + - | + The `DocumentSplitter` now has support for the `split_id` and `split_overlap` to allow for more control over the splitting process.
diff --git a/test/components/preprocessors/test_document_splitter.py b/test/components/preprocessors/test_document_splitter.py index 4351457f79..d6fcaa9d1c 100644 --- a/test/components/preprocessors/test_document_splitter.py +++ b/test/components/preprocessors/test_document_splitter.py @@ -7,6 +7,28 @@ from haystack.components.preprocessors import DocumentSplitter +def merge_documents(documents): + """Merge a list of doc chunks into a single doc by concatenating their content, eliminating overlapping content.""" + sorted_docs = sorted(documents, key=lambda doc: doc.meta["split_idx_start"]) + merged_text = "" + last_idx_end = 0 + for doc in sorted_docs: + start = doc.meta["split_idx_start"] # start of the current content + + # if the start of the current content is before the end of the last appended content, adjust it + if start < last_idx_end: + start = last_idx_end + + # append the non-overlapping part to the merged text + merged_text = merged_text.strip() + merged_text += doc.content[start - doc.meta["split_idx_start"] :] + + # update the last end index + last_idx_end = doc.meta["split_idx_start"] + len(doc.content) + + return merged_text + + class TestDocumentSplitter: def test_non_text_document(self): with pytest.raises( @@ -219,7 +241,6 @@ def test_add_page_number_to_metadata_with_overlap_word_split(self): expected_pages = [1, 1, 1, 2, 2, 1, 1, 3] for doc, p in zip(result["documents"], expected_pages): - print(doc.content, doc.meta, p) assert doc.meta["page_number"] == p def test_add_page_number_to_metadata_with_overlap_sentence_split(self): @@ -230,7 +251,6 @@ def test_add_page_number_to_metadata_with_overlap_sentence_split(self): expected_pages = [1, 1, 1, 2, 1, 1] for doc, p in zip(result["documents"], expected_pages): - print(doc.content, doc.meta, p) assert doc.meta["page_number"] == p def test_add_page_number_to_metadata_with_overlap_passage_split(self): @@ -254,3 +274,16 @@ def test_add_page_number_to_metadata_with_overlap_page_split(self): for doc, p in zip(result["documents"], expected_pages): assert doc.meta["page_number"] == p + + def test_add_split_overlap_information(self): + splitter = DocumentSplitter(split_length=10, split_overlap=5, split_by="word") + doc = Document(content="This is a text with some words. There is a second sentence. And a third sentence.") + docs = splitter.run(documents=[doc]) + + # check split_overlap is added to all the documents + assert len(docs["documents"]) == 3 + for d in docs["documents"]: + assert "_split_overlap" in d.meta + + # reconstruct the original document content from the split documents + assert doc.content == merge_documents(docs["documents"])
diff --git a/releasenotes/notes/add-split_id_and_overlap_to_DocumentSplitter-8180ad8f13495741.yaml b/releasenotes/notes/add-split_id_and_overlap_to_DocumentSplitter-8180ad8f13495741.yaml new file mode 100644 index 0000000000..e3eba2d57b --- /dev/null +++ b/releasenotes/notes/add-split_id_and_overlap_to_DocumentSplitter-8180ad8f13495741.yaml @@ -0,0 +1,4 @@ +--- +features: + - | + The `DocumentSplitter` now has support for the `split_id` and `split_overlap` to allow for more control over the splitting process.
[ { "components": [ { "doc": "Adds split overlap information to the current and previous Document's meta.\n\n:param current_doc: The Document that is being split.\n:param current_doc_start_idx: The starting index of the current Document.\n:param previous_doc: The Document that was split before the current Document.\n:param previous_doc_start_idx: The starting index of the previous Document.", "lines": [ 199, 221 ], "name": "DocumentSplitter._add_split_overlap_information", "signature": "def _add_split_overlap_information( current_doc: Document, current_doc_start_idx: int, previous_doc: Document, previous_doc_start_idx: int ):", "type": "function" } ], "file": "haystack/components/preprocessors/document_splitter.py" } ]
[ "test/components/preprocessors/test_document_splitter.py::TestDocumentSplitter::test_add_split_overlap_information" ]
[ "test/components/preprocessors/test_document_splitter.py::TestDocumentSplitter::test_non_text_document", "test/components/preprocessors/test_document_splitter.py::TestDocumentSplitter::test_single_doc", "test/components/preprocessors/test_document_splitter.py::TestDocumentSplitter::test_empty_list", "test/components/preprocessors/test_document_splitter.py::TestDocumentSplitter::test_unsupported_split_by", "test/components/preprocessors/test_document_splitter.py::TestDocumentSplitter::test_unsupported_split_length", "test/components/preprocessors/test_document_splitter.py::TestDocumentSplitter::test_unsupported_split_overlap", "test/components/preprocessors/test_document_splitter.py::TestDocumentSplitter::test_split_by_word", "test/components/preprocessors/test_document_splitter.py::TestDocumentSplitter::test_split_by_word_with_threshold", "test/components/preprocessors/test_document_splitter.py::TestDocumentSplitter::test_split_by_word_multiple_input_docs", "test/components/preprocessors/test_document_splitter.py::TestDocumentSplitter::test_split_by_sentence", "test/components/preprocessors/test_document_splitter.py::TestDocumentSplitter::test_split_by_passage", "test/components/preprocessors/test_document_splitter.py::TestDocumentSplitter::test_split_by_page", "test/components/preprocessors/test_document_splitter.py::TestDocumentSplitter::test_split_by_word_with_overlap", "test/components/preprocessors/test_document_splitter.py::TestDocumentSplitter::test_source_id_stored_in_metadata", "test/components/preprocessors/test_document_splitter.py::TestDocumentSplitter::test_copy_metadata", "test/components/preprocessors/test_document_splitter.py::TestDocumentSplitter::test_add_page_number_to_metadata_with_no_overlap_word_split", "test/components/preprocessors/test_document_splitter.py::TestDocumentSplitter::test_add_page_number_to_metadata_with_no_overlap_sentence_split", "test/components/preprocessors/test_document_splitter.py::TestDocumentSplitter::test_add_page_number_to_metadata_with_no_overlap_passage_split", "test/components/preprocessors/test_document_splitter.py::TestDocumentSplitter::test_add_page_number_to_metadata_with_no_overlap_page_split", "test/components/preprocessors/test_document_splitter.py::TestDocumentSplitter::test_add_page_number_to_metadata_with_overlap_word_split", "test/components/preprocessors/test_document_splitter.py::TestDocumentSplitter::test_add_page_number_to_metadata_with_overlap_sentence_split", "test/components/preprocessors/test_document_splitter.py::TestDocumentSplitter::test_add_page_number_to_metadata_with_overlap_passage_split", "test/components/preprocessors/test_document_splitter.py::TestDocumentSplitter::test_add_page_number_to_metadata_with_overlap_page_split" ]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> feat : adding `split_id` and `split_overlap` to `DocumentSplitter` ### Related Issues - fixes [#7389](https://github.com/deepset-ai/haystack/issues/7389) ### Proposed Changes: When a `split_overlap` is set each produced chunk Document will have information: - about the `split_id` allowing an ordering over the document chunks - each document chunk will have in the `meta` the `_split_overlap`, telling with which other docs it overlaps and on what range ### How did you test it? - added new unit tests, did manual verification and run integration tests ### Checklist - I have read the [contributors guidelines](https://github.com/deepset-ai/haystack/blob/main/CONTRIBUTING.md) and the [code of conduct](https://github.com/deepset-ai/haystack/blob/main/code_of_conduct.txt) - I have updated the related issue with new insights and changes - I added unit tests and updated the docstrings - I've used one of the [conventional commit types](https://www.conventionalcommits.org/en/v1.0.0/) for my PR title: `fix:`, `feat:`, `build:`, `chore:`, `ci:`, `docs:`, `style:`, `refactor:`, `perf:`, `test:`. - I documented my code - I ran [pre-commit hooks](https://github.com/deepset-ai/haystack/blob/main/CONTRIBUTING.md#installation) and fixed any issue ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in haystack/components/preprocessors/document_splitter.py] (definition of DocumentSplitter._add_split_overlap_information:) def _add_split_overlap_information( current_doc: Document, current_doc_start_idx: int, previous_doc: Document, previous_doc_start_idx: int ): """Adds split overlap information to the current and previous Document's meta. :param current_doc: The Document that is being split. :param current_doc_start_idx: The starting index of the current Document. :param previous_doc: The Document that was split before the current Document. :param previous_doc_start_idx: The starting index of the previous Document.""" [end of new definitions in haystack/components/preprocessors/document_splitter.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
f4d9c2bb917be0ffe132dffcc2ad4f1b0fcc5967
deepset-ai__haystack-7920
7,920
deepset-ai/haystack
null
c51f8ffb865db54f39103a202d2b6ba81fc68fb9
2024-06-24T14:22:50Z
diff --git a/haystack/components/fetchers/link_content.py b/haystack/components/fetchers/link_content.py index b658ff2450..ccc698f613 100644 --- a/haystack/components/fetchers/link_content.py +++ b/haystack/components/fetchers/link_content.py @@ -4,6 +4,7 @@ from collections import defaultdict from concurrent.futures import ThreadPoolExecutor +from fnmatch import fnmatch from typing import Callable, Dict, List, Optional, Tuple import requests @@ -94,10 +95,12 @@ def __init__( # register default content handlers that extract data from the response self.handlers: Dict[str, Callable[[Response], ByteStream]] = defaultdict(lambda: _text_content_handler) - self.handlers["text/html"] = _text_content_handler - self.handlers["text/plain"] = _text_content_handler - self.handlers["application/pdf"] = _binary_content_handler - self.handlers["application/octet-stream"] = _binary_content_handler + self.handlers["text/*"] = _text_content_handler + self.handlers["application/json"] = _text_content_handler + self.handlers["application/*"] = _binary_content_handler + self.handlers["image/*"] = _binary_content_handler + self.handlers["audio/*"] = _binary_content_handler + self.handlers["video/*"] = _binary_content_handler @retry( reraise=True, @@ -175,7 +178,7 @@ def _fetch(self, url: str) -> Tuple[Dict[str, str], ByteStream]: try: response = self._get_response(url) content_type = self._get_content_type(response) - handler: Callable = self.handlers[content_type] + handler: Callable = self._resolve_handler(content_type) stream = handler(response) except Exception as e: if self.raise_on_failure: @@ -217,6 +220,29 @@ def _get_content_type(self, response: Response): content_type = response.headers.get("Content-Type", "") return content_type.split(";")[0] + def _resolve_handler(self, content_type: str) -> Callable[[Response], ByteStream]: + """ + Resolves the handler for the given content type. + + First, it tries to find a direct match for the content type in the handlers dictionary. + If no direct match is found, it tries to find a pattern match using the fnmatch function. + If no pattern match is found, it returns the default handler for text/plain. + + :param content_type: The content type to resolve the handler for. + :returns: The handler for the given content type, if found. Otherwise, the default handler for text/plain. + """ + # direct match + if content_type in self.handlers: + return self.handlers[content_type] + + # pattern matches + for pattern, handler in self.handlers.items(): + if fnmatch(content_type, pattern): + return handler + + # default handler + return self.handlers["text/plain"] + def _switch_user_agent(self, retry_state: RetryCallState) -> None: """ Switches the User-Agent for this LinkContentRetriever to the next one in the list of user agents. diff --git a/releasenotes/notes/link-content-fetcher-enhancements-49babe1c60888043.yaml b/releasenotes/notes/link-content-fetcher-enhancements-49babe1c60888043.yaml new file mode 100644 index 0000000000..d6a7d24285 --- /dev/null +++ b/releasenotes/notes/link-content-fetcher-enhancements-49babe1c60888043.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Improve LinkContentFetcher to support a broader range of content types, including glob patterns for text, application, audio, and video types. This update introduces a more flexible content handler resolution mechanism, allowing for direct matches and pattern matching, thereby greatly improving the handler's adaptability to various content types encountered on the web.
diff --git a/test/components/fetchers/test_link_content_fetcher.py b/test/components/fetchers/test_link_content_fetcher.py index ac99bc4cfa..c6a4d5c55f 100644 --- a/test/components/fetchers/test_link_content_fetcher.py +++ b/test/components/fetchers/test_link_content_fetcher.py @@ -46,10 +46,12 @@ def test_init(self): assert fetcher.retry_attempts == 2 assert fetcher.timeout == 3 assert fetcher.handlers == { - "text/html": _text_content_handler, - "text/plain": _text_content_handler, - "application/pdf": _binary_content_handler, - "application/octet-stream": _binary_content_handler, + "text/*": _text_content_handler, + "application/json": _text_content_handler, + "application/*": _binary_content_handler, + "image/*": _binary_content_handler, + "audio/*": _binary_content_handler, + "video/*": _binary_content_handler, } assert hasattr(fetcher, "_get_response") @@ -191,3 +193,11 @@ def test_bad_request_exception_raised(self): fetcher = LinkContentFetcher() with pytest.raises(requests.exceptions.ConnectionError): fetcher.run(["https://non_existent_website_dot.com/"]) + + @pytest.mark.integration + def test_link_content_fetcher_audio(self): + fetcher = LinkContentFetcher() + streams = fetcher.run(["https://download.samplelib.com/mp3/sample-3s.mp3"])["streams"] + first_stream = streams[0] + assert first_stream.meta["content_type"] == "audio/mpeg" + assert len(first_stream.data) > 0
diff --git a/releasenotes/notes/link-content-fetcher-enhancements-49babe1c60888043.yaml b/releasenotes/notes/link-content-fetcher-enhancements-49babe1c60888043.yaml new file mode 100644 index 0000000000..d6a7d24285 --- /dev/null +++ b/releasenotes/notes/link-content-fetcher-enhancements-49babe1c60888043.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Improve LinkContentFetcher to support a broader range of content types, including glob patterns for text, application, audio, and video types. This update introduces a more flexible content handler resolution mechanism, allowing for direct matches and pattern matching, thereby greatly improving the handler's adaptability to various content types encountered on the web.
[ { "components": [ { "doc": "Resolves the handler for the given content type.\n\nFirst, it tries to find a direct match for the content type in the handlers dictionary.\nIf no direct match is found, it tries to find a pattern match using the fnmatch function.\nIf no pattern match is found, it returns the default handler for text/plain.\n\n:param content_type: The content type to resolve the handler for.\n:returns: The handler for the given content type, if found. Otherwise, the default handler for text/plain.", "lines": [ 223, 244 ], "name": "LinkContentFetcher._resolve_handler", "signature": "def _resolve_handler(self, content_type: str) -> Callable[[Response], ByteStream]:", "type": "function" } ], "file": "haystack/components/fetchers/link_content.py" } ]
[ "test/components/fetchers/test_link_content_fetcher.py::TestLinkContentFetcher::test_init" ]
[ "[", "test/components/fetchers/test_link_content_fetcher.py::TestLinkContentFetcher::test_init_with_params", "test/components/fetchers/test_link_content_fetcher.py::TestLinkContentFetcher::test_run_text", "test/components/fetchers/test_link_content_fetcher.py::TestLinkContentFetcher::test_run_html", "test/components/fetchers/test_link_content_fetcher.py::TestLinkContentFetcher::test_run_binary", "test/components/fetchers/test_link_content_fetcher.py::TestLinkContentFetcher::test_run_bad_status_code", "test/components/fetchers/test_link_content_fetcher.py::TestLinkContentFetcher::test_link_content_fetcher_html", "test/components/fetchers/test_link_content_fetcher.py::TestLinkContentFetcher::test_link_content_fetcher_text", "test/components/fetchers/test_link_content_fetcher.py::TestLinkContentFetcher::test_link_content_fetcher_pdf", "test/components/fetchers/test_link_content_fetcher.py::TestLinkContentFetcher::test_link_content_fetcher_multiple_different_content_types", "test/components/fetchers/test_link_content_fetcher.py::TestLinkContentFetcher::test_link_content_fetcher_multiple_html_streams", "test/components/fetchers/test_link_content_fetcher.py::TestLinkContentFetcher::test_mix_of_good_and_failed_requests", "test/components/fetchers/test_link_content_fetcher.py::TestLinkContentFetcher::test_bad_request_exception_raised", "test/components/fetchers/test_link_content_fetcher.py::TestLinkContentFetcher::test_link_content_fetcher_audio" ]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> feat: Improve LinkContentFetcher content type handling ### Why: Enhances `LinkContentFetcher` to broaden its content handling capabilities. The primary motivation behind these changes is to allow more content type support utilizing pattern matching for content types and allow fetching web content that includes text, applications, audio, and video files. Direct motivation for this enhancement was an experiment to fetch an audio file and transcribe it via Groq i.e: ``` from haystack.components.audio import RemoteWhisperTranscriber from haystack.components.fetchers import LinkContentFetcher from haystack import Pipeline from haystack.utils import Secret transcriber = RemoteWhisperTranscriber(Secret.from_env_var("GROQ_API_KEY"), api_base_url="https://api.groq.com/openai/v1", model="whisper-large-v3") pipe = Pipeline() pipe.add_component("fetcher", LinkContentFetcher()) pipe.add_component("transcriber", RemoteWhisperTranscriber(Secret.from_env_var("GROQ_API_KEY"), api_base_url="https://api.groq.com/openai/v1", model="whisper-large-v3")) pipe.connect("fetcher", "transcriber") result = pipe.run( data={"fetcher": {"urls": ["https://ia601309.us.archive.org/29/items/jfks19610427/jfk_1961_0427_press_64kb.mp3"]}}) print(result["transcriber"]["documents"]) ``` We couldn't however do this out-of-the box because we didn't have content type handler registered for audio files. This PR remedies this oversight. And adds more flexibility by adding pattern matching for content types ### What: - Simplified and expanded content type handling by implementing wildcard patterns (e.g., `text/*`, `application/*`, `audio/*`, `video/*`) in the fetcher's handlers to efficiently map multiple content types to their appropriate handlers. - Added support for `application/json` as a text content type. - Introduced a `_resolve_handler` method to dynamically determine the correct handler for a content type, utilizing the `fnmatch` module for pattern matching. - Adjusted existing tests and added a new integration test to cover the handling of an `audio/mpeg` content type. ### How can it be used: - All previous use cases are still supported - The above audio transcription example works out of the box ### How did you test it: - Modified unit tests to assert the correct mapping of MIME types to handlers according to the new pattern matching logic. - Added an integration test (`test_link_content_fetcher_audio`) which specifically tests fetching an MP3 file, asserting both the `content_type` to be `audio/mpeg` and that the data stream is correctly retrieved and non-empty. ### Notes for the reviewer: - Pay special attention to the pattern matching implementation in the `_resolve_handler` method to ensure that it properly covers all anticipated content types and does not inadvertently match undesired types. - Review the added integration test for audio content ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in haystack/components/fetchers/link_content.py] (definition of LinkContentFetcher._resolve_handler:) def _resolve_handler(self, content_type: str) -> Callable[[Response], ByteStream]: """Resolves the handler for the given content type. First, it tries to find a direct match for the content type in the handlers dictionary. If no direct match is found, it tries to find a pattern match using the fnmatch function. If no pattern match is found, it returns the default handler for text/plain. :param content_type: The content type to resolve the handler for. :returns: The handler for the given content type, if found. Otherwise, the default handler for text/plain.""" [end of new definitions in haystack/components/fetchers/link_content.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
f4d9c2bb917be0ffe132dffcc2ad4f1b0fcc5967
roboflow__supervision-1296
1,296
roboflow/supervision
null
fbce6e45d427fbbc2f610dfe1adf24bdf608d914
2024-06-20T12:01:50Z
diff --git a/supervision/detection/core.py b/supervision/detection/core.py index 37dde1534..4d913e1bc 100644 --- a/supervision/detection/core.py +++ b/supervision/detection/core.py @@ -7,7 +7,12 @@ import numpy as np from supervision.config import CLASS_NAME_DATA_FIELD, ORIENTED_BOX_COORDINATES -from supervision.detection.lmm import LMM, from_paligemma, validate_lmm_and_kwargs +from supervision.detection.lmm import ( + LMM, + from_florence_2, + from_paligemma, + validate_lmm_parameters, +) from supervision.detection.overlap_filter import ( box_non_max_merge, box_non_max_suppression, @@ -811,7 +816,9 @@ def from_paddledet(cls, paddledet_result) -> Detections: ) @classmethod - def from_lmm(cls, lmm: Union[LMM, str], result: str, **kwargs) -> Detections: + def from_lmm( + cls, lmm: Union[LMM, str], result: Union[str, dict], **kwargs + ) -> Detections: """ Creates a Detections object from the given result string based on the specified Large Multimodal Model (LMM). @@ -847,13 +854,28 @@ def from_lmm(cls, lmm: Union[LMM, str], result: str, **kwargs) -> Detections: # array([0]) ``` """ - lmm = validate_lmm_and_kwargs(lmm, kwargs) + lmm = validate_lmm_parameters(lmm, result, kwargs) if lmm == LMM.PALIGEMMA: + assert isinstance(result, str) xyxy, class_id, class_name = from_paligemma(result, **kwargs) data = {CLASS_NAME_DATA_FIELD: class_name} return cls(xyxy=xyxy, class_id=class_id, data=data) + if lmm == LMM.FLORENCE_2: + assert isinstance(result, dict) + xyxy, labels, mask, xyxyxyxy = from_florence_2(result, **kwargs) + if len(xyxy) == 0: + return cls.empty() + + data = {} + if labels is not None: + data[CLASS_NAME_DATA_FIELD] = labels + if xyxyxyxy is not None: + data[ORIENTED_BOX_COORDINATES] = xyxyxyxy + + return cls(xyxy=xyxy, mask=mask, data=data) + raise ValueError(f"Unsupported LMM: {lmm}") @classmethod diff --git a/supervision/detection/lmm.py b/supervision/detection/lmm.py index 5f61db0a5..e39e434f7 100644 --- a/supervision/detection/lmm.py +++ b/supervision/detection/lmm.py @@ -4,17 +4,43 @@ import numpy as np +from supervision.detection.utils import polygon_to_mask, polygon_to_xyxy + class LMM(Enum): PALIGEMMA = "paligemma" - - -REQUIRED_ARGUMENTS: Dict[LMM, List[str]] = {LMM.PALIGEMMA: ["resolution_wh"]} - -ALLOWED_ARGUMENTS: Dict[LMM, List[str]] = {LMM.PALIGEMMA: ["resolution_wh", "classes"]} - - -def validate_lmm_and_kwargs(lmm: Union[LMM, str], kwargs: Dict[str, Any]) -> LMM: + FLORENCE_2 = "florence_2" + + +RESULT_TYPES: Dict[LMM, type] = {LMM.PALIGEMMA: str, LMM.FLORENCE_2: dict} + +REQUIRED_ARGUMENTS: Dict[LMM, List[str]] = { + LMM.PALIGEMMA: ["resolution_wh"], + LMM.FLORENCE_2: ["resolution_wh"], +} + +ALLOWED_ARGUMENTS: Dict[LMM, List[str]] = { + LMM.PALIGEMMA: ["resolution_wh", "classes"], + LMM.FLORENCE_2: ["resolution_wh"], +} + +SUPPORTED_TASKS_FLORENCE_2 = [ + "<OD>", + "<CAPTION_TO_PHRASE_GROUNDING>", + "<DENSE_REGION_CAPTION>", + "<REGION_PROPOSAL>", + "<OCR_WITH_REGION>", + "<REFERRING_EXPRESSION_SEGMENTATION>", + "<REGION_TO_SEGMENTATION>", + "<OPEN_VOCABULARY_DETECTION>", + "<REGION_TO_CATEGORY>", + "<REGION_TO_DESCRIPTION>", +] + + +def validate_lmm_parameters( + lmm: Union[LMM, str], result: Any, kwargs: Dict[str, Any] +) -> LMM: if isinstance(lmm, str): try: lmm = LMM(lmm.lower()) @@ -23,6 +49,11 @@ def validate_lmm_and_kwargs(lmm: Union[LMM, str], kwargs: Dict[str, Any]) -> LMM f"Invalid lmm value: {lmm}. Must be one of {[e.value for e in LMM]}" ) + if not isinstance(result, RESULT_TYPES[lmm]): + raise ValueError( + f"Invalid LMM result type: {type(result)}. Must be {RESULT_TYPES[lmm]}" + ) + required_args = REQUIRED_ARGUMENTS.get(lmm, []) for arg in required_args: if arg not in kwargs: @@ -57,3 +88,95 @@ def from_paligemma( class_id = np.array([classes.index(name) for name in class_name]) return xyxy, class_id, class_name + + +def from_florence_2( + result: dict, resolution_wh: Tuple[int, int] +) -> Tuple[ + np.ndarray, Optional[np.ndarray], Optional[np.ndarray], Optional[np.ndarray] +]: + """ + Parse results from the Florence 2 multi-model model. + https://huggingface.co/microsoft/Florence-2-large + + Parameters: + result: dict containing the model output + + Returns: + xyxy (np.ndarray): An array of shape `(n, 4)` containing + the bounding boxes coordinates in format `[x1, y1, x2, y2]` + labels: (Optional[np.ndarray]): An array of shape `(n,)` containing + the class labels for each bounding box + masks: (Optional[np.ndarray]): An array of shape `(n, h, w)` containing + the segmentation masks for each bounding box + obb_boxes: (Optional[np.ndarray]): An array of shape `(n, 4, 2)` containing + oriented bounding boxes. + """ + assert len(result) == 1, f"Expected result with a single element. Got: {result}" + task = list(result.keys())[0] + if task not in SUPPORTED_TASKS_FLORENCE_2: + raise ValueError( + f"{task} not supported. Supported tasks are: {SUPPORTED_TASKS_FLORENCE_2}" + ) + result = result[task] + + if task in ["<OD>", "<CAPTION_TO_PHRASE_GROUNDING>", "<DENSE_REGION_CAPTION>"]: + xyxy = np.array(result["bboxes"], dtype=np.float32) + labels = np.array(result["labels"]) + return xyxy, labels, None, None + + if task == "<REGION_PROPOSAL>": + xyxy = np.array(result["bboxes"], dtype=np.float32) + # provides labels, but they are ["", "", "", ...] + return xyxy, None, None, None + + if task == "<OCR_WITH_REGION>": + xyxyxyxy = np.array(result["quad_boxes"], dtype=np.float32) + xyxyxyxy = xyxyxyxy.reshape(-1, 4, 2) + xyxy = np.array([polygon_to_xyxy(polygon) for polygon in xyxyxyxy]) + labels = np.array(result["labels"]) + return xyxy, labels, None, xyxyxyxy + + if task in ["<REFERRING_EXPRESSION_SEGMENTATION>", "<REGION_TO_SEGMENTATION>"]: + xyxy_list = [] + masks_list = [] + for polygons_of_same_class in result["polygons"]: + for polygon in polygons_of_same_class: + polygon = np.reshape(polygon, (-1, 2)).astype(np.int32) + mask = polygon_to_mask(polygon, resolution_wh).astype(bool) + masks_list.append(mask) + xyxy = polygon_to_xyxy(polygon) + xyxy_list.append(xyxy) + # per-class labels also provided, but they are ["", "", "", ...] + # when we figure out how to set class names, we can do + # zip(result["labels"], result["polygons"]) + xyxy = np.array(xyxy_list, dtype=np.float32) + masks = np.array(masks_list) + return xyxy, None, masks, None + + if task == "<OPEN_VOCABULARY_DETECTION>": + xyxy = np.array(result["bboxes"], dtype=np.float32) + labels = np.array(result["bboxes_labels"]) + # Also has "polygons" and "polygons_labels", but they don't seem to be used + return xyxy, labels, None, None + + if task in ["<REGION_TO_CATEGORY>", "<REGION_TO_DESCRIPTION>"]: + assert isinstance( + result, str + ), f"Expected string as <REGION_TO_CATEGORY> result, got {type(result)}" + + if result == "No object detected.": + return np.empty((0, 4), dtype=np.float32), np.array([]), None, None + + pattern = re.compile(r"<loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)>") + match = pattern.search(result) + assert ( + match is not None + ), f"Expected string to end in location tags, but got {result}" + + xyxy = np.array([match.groups()], dtype=np.float32) + result_string = result[: match.start()] + labels = np.array([result_string]) + return xyxy, labels, None, None + + assert False, f"Unimplemented task: {task}"
diff --git a/test/detection/test_lmm_florence_2.py b/test/detection/test_lmm_florence_2.py new file mode 100644 index 000000000..9ffec2a1e --- /dev/null +++ b/test/detection/test_lmm_florence_2.py @@ -0,0 +1,291 @@ +from contextlib import ExitStack as DoesNotRaise +from typing import Optional, Tuple + +import numpy as np +import pytest + +from supervision.detection.lmm import from_florence_2 + + +@pytest.mark.parametrize( + "florence_result, resolution_wh, expected_results, exception", + [ + ( # Object detection: empty + {"<OD>": {"bboxes": [], "labels": []}}, + (10, 10), + (np.array([], dtype=np.float32), np.array([]), None, None), + DoesNotRaise(), + ), + ( # Object detection: two detections + { + "<OD>": { + "bboxes": [[4, 4, 6, 6], [5, 5, 7, 7]], + "labels": ["car", "door"], + } + }, + (10, 10), + ( + np.array([[4, 4, 6, 6], [5, 5, 7, 7]], dtype=np.float32), + np.array(["car", "door"]), + None, + None, + ), + DoesNotRaise(), + ), + ( # Caption: unsupported + {"<CAPTION>": "A green car parked in front of a yellow building."}, + (10, 10), + None, + pytest.raises(ValueError), + ), + ( # Detailed Caption: unsupported + { + "<DETAILED_CAPTION>": "The image shows a blue Volkswagen Beetle parked " + "in front of a yellow building with two brown doors, surrounded by " + "trees and a clear blue sky." + }, + (10, 10), + None, + pytest.raises(ValueError), + ), + ( # More Detailed Caption: unsupported + { + "<MORE_DETAILED_CAPTION>": "The image shows a vintage Volkswagen " + "Beetle car parked on a " + "cobblestone street in front of a yellow building with two wooden " + "doors. The car is painted in a bright turquoise color and has a " + "white stripe running along the side. It has two doors on either side " + "of the car, one on top of the other, and a small window on the " + "front. The building appears to be old and dilapidated, with peeling " + "paint and crumbling walls. The sky is blue and there are trees in " + "the background." + }, + (10, 10), + None, + pytest.raises(ValueError), + ), + ( # Caption to Phrase Grounding: empty + {"<CAPTION_TO_PHRASE_GROUNDING>": {"bboxes": [], "labels": []}}, + (10, 10), + (np.array([], dtype=np.float32), np.array([]), None, None), + DoesNotRaise(), + ), + ( # Caption to Phrase Grounding: two detections + { + "<CAPTION_TO_PHRASE_GROUNDING>": { + "bboxes": [[4, 4, 6, 6], [5, 5, 7, 7]], + "labels": ["a green car", "a yellow building"], + } + }, + (10, 10), + ( + np.array([[4, 4, 6, 6], [5, 5, 7, 7]], dtype=np.float32), + np.array(["a green car", "a yellow building"]), + None, + None, + ), + DoesNotRaise(), + ), + ( # Dense Region caption: empty + {"<DENSE_REGION_CAPTION>": {"bboxes": [], "labels": []}}, + (10, 10), + (np.array([], dtype=np.float32), np.array([]), None, None), + DoesNotRaise(), + ), + ( # Caption to Phrase Grounding: two detections + { + "<DENSE_REGION_CAPTION>": { + "bboxes": [[4, 4, 6, 6], [5, 5, 7, 7]], + "labels": ["a green car", "a yellow building"], + } + }, + (10, 10), + ( + np.array([[4, 4, 6, 6], [5, 5, 7, 7]], dtype=np.float32), + np.array(["a green car", "a yellow building"]), + None, + None, + ), + DoesNotRaise(), + ), + ( # Region proposal + { + "<REGION_PROPOSAL>": { + "bboxes": [[4, 4, 6, 6], [5, 5, 7, 7]], + "labels": ["", ""], + } + }, + (10, 10), + ( + np.array([[4, 4, 6, 6], [5, 5, 7, 7]], dtype=np.float32), + None, + None, + None, + ), + DoesNotRaise(), + ), + ( # Referring Expression Segmentation + { + "<REFERRING_EXPRESSION_SEGMENTATION>": { + "polygons": [[[1, 1, 2, 1, 2, 2, 1, 2]]], + "labels": [""], + } + }, + (10, 10), + ( + np.array([[1.0, 1.0, 2.0, 2.0]], dtype=np.float32), + None, + np.array( + [ + [ + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + ] + ], + dtype=bool, + ), + None, + ), + DoesNotRaise(), + ), + ( # Referring Expression Segmentation + { + "<REFERRING_EXPRESSION_SEGMENTATION>": { + "polygons": [[[1, 1, 2, 1, 2, 2, 1, 2]]], + "labels": [""], + } + }, + (10, 10), + ( + np.array([[1.0, 1.0, 2.0, 2.0]], dtype=np.float32), + None, + np.array( + [ + [ + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + ] + ], + dtype=bool, + ), + None, + ), + DoesNotRaise(), + ), + ( # OCR: unsupported + {"<OCR>": "A"}, + (10, 10), + None, + pytest.raises(ValueError), + ), + ( # OCR with Region: obb boxes + { + "<OCR_WITH_REGION>": { + "quad_boxes": [[2, 2, 6, 4, 5, 6, 1, 5], [4, 4, 5, 5, 4, 6, 3, 5]], + "labels": ["some text", "other text"], + } + }, + (10, 10), + ( + np.array([[1, 2, 6, 6], [3, 4, 5, 6]], dtype=np.float32), + np.array(["some text", "other text"]), + None, + np.array( + [[[2, 2], [6, 4], [5, 6], [1, 5]], [[4, 4], [5, 5], [4, 6], [3, 5]]] + ), + ), + DoesNotRaise(), + ), + ( # Open Vocabulary Detection + { + "<OPEN_VOCABULARY_DETECTION>": { + "bboxes": [[4, 4, 6, 6], [5, 5, 7, 7]], + "bboxes_labels": ["cat", "cat"], + "polygon": [], + "polygons_labels": [], + } + }, + (10, 10), + ( + np.array([[4, 4, 6, 6], [5, 5, 7, 7]], dtype=np.float32), + np.array(["cat", "cat"]), + None, + None, + ), + DoesNotRaise(), + ), + ( # Region to Category: empty + {"<REGION_TO_CATEGORY>": "No object detected."}, + (10, 10), + (np.empty((0, 4), dtype=np.float32), np.array([]), None, None), + DoesNotRaise(), + ), + ( # Region to Category: detected + {"<REGION_TO_CATEGORY>": "some object<loc_3><loc_4><loc_5><loc_6>"}, + (10, 10), + ( + np.array([[3, 4, 5, 6]], dtype=np.float32), + np.array(["some object"]), + None, + None, + ), + DoesNotRaise(), + ), + ( # Region to Description: empty + {"<REGION_TO_DESCRIPTION>": "No object detected."}, + (10, 10), + (np.empty((0, 4), dtype=np.float32), np.array([]), None, None), + DoesNotRaise(), + ), + ( # Region to Description: detected + {"<REGION_TO_DESCRIPTION>": "some description<loc_3><loc_4><loc_5><loc_6>"}, + (10, 10), + ( + np.array([[3, 4, 5, 6]], dtype=np.float32), + np.array(["some description"]), + None, + None, + ), + DoesNotRaise(), + ), + ], +) +def test_florence_2( + florence_result: dict, + resolution_wh: Tuple[int, int], + expected_results: Tuple[ + np.ndarray, Optional[np.ndarray], Optional[np.ndarray], Optional[np.ndarray] + ], + exception: Exception, +) -> None: + with exception: + result = from_florence_2(florence_result, resolution_wh) + np.testing.assert_array_equal(result[0], expected_results[0]) + if expected_results[1] is None: + assert result[1] is None + else: + np.testing.assert_array_equal(result[1], expected_results[1]) + if expected_results[2] is None: + assert result[2] is None + else: + np.testing.assert_array_equal(result[2], expected_results[2]) + if expected_results[3] is None: + assert result[3] is None + else: + np.testing.assert_array_equal(result[3], expected_results[3])
[ { "components": [ { "doc": "", "lines": [ 41, 67 ], "name": "validate_lmm_parameters", "signature": "def validate_lmm_parameters( lmm: Union[LMM, str], result: Any, kwargs: Dict[str, Any] ) -> LMM:", "type": "function" }, { "doc": "Parse results from the Florence 2 multi-model model.\nhttps://huggingface.co/microsoft/Florence-2-large\n\nParameters:\n result: dict containing the model output\n\nReturns:\n xyxy (np.ndarray): An array of shape `(n, 4)` containing\n the bounding boxes coordinates in format `[x1, y1, x2, y2]`\n labels: (Optional[np.ndarray]): An array of shape `(n,)` containing\n the class labels for each bounding box\n masks: (Optional[np.ndarray]): An array of shape `(n, h, w)` containing\n the segmentation masks for each bounding box\n obb_boxes: (Optional[np.ndarray]): An array of shape `(n, 4, 2)` containing\n oriented bounding boxes.", "lines": [ 93, 182 ], "name": "from_florence_2", "signature": "def from_florence_2( result: dict, resolution_wh: Tuple[int, int] ) -> Tuple[ np.ndarray, Optional[np.ndarray], Optional[np.ndarray], Optional[np.ndarray] ]:", "type": "function" } ], "file": "supervision/detection/lmm.py" } ]
[ "test/detection/test_lmm_florence_2.py::test_florence_2[florence_result0-resolution_wh0-expected_results0-exception0]", "test/detection/test_lmm_florence_2.py::test_florence_2[florence_result1-resolution_wh1-expected_results1-exception1]", "test/detection/test_lmm_florence_2.py::test_florence_2[florence_result2-resolution_wh2-None-exception2]", "test/detection/test_lmm_florence_2.py::test_florence_2[florence_result3-resolution_wh3-None-exception3]", "test/detection/test_lmm_florence_2.py::test_florence_2[florence_result4-resolution_wh4-None-exception4]", "test/detection/test_lmm_florence_2.py::test_florence_2[florence_result5-resolution_wh5-expected_results5-exception5]", "test/detection/test_lmm_florence_2.py::test_florence_2[florence_result6-resolution_wh6-expected_results6-exception6]", "test/detection/test_lmm_florence_2.py::test_florence_2[florence_result7-resolution_wh7-expected_results7-exception7]", "test/detection/test_lmm_florence_2.py::test_florence_2[florence_result8-resolution_wh8-expected_results8-exception8]", "test/detection/test_lmm_florence_2.py::test_florence_2[florence_result9-resolution_wh9-expected_results9-exception9]", "test/detection/test_lmm_florence_2.py::test_florence_2[florence_result10-resolution_wh10-expected_results10-exception10]", "test/detection/test_lmm_florence_2.py::test_florence_2[florence_result11-resolution_wh11-expected_results11-exception11]", "test/detection/test_lmm_florence_2.py::test_florence_2[florence_result12-resolution_wh12-None-exception12]", "test/detection/test_lmm_florence_2.py::test_florence_2[florence_result13-resolution_wh13-expected_results13-exception13]", "test/detection/test_lmm_florence_2.py::test_florence_2[florence_result14-resolution_wh14-expected_results14-exception14]", "test/detection/test_lmm_florence_2.py::test_florence_2[florence_result15-resolution_wh15-expected_results15-exception15]", "test/detection/test_lmm_florence_2.py::test_florence_2[florence_result16-resolution_wh16-expected_results16-exception16]", "test/detection/test_lmm_florence_2.py::test_florence_2[florence_result17-resolution_wh17-expected_results17-exception17]", "test/detection/test_lmm_florence_2.py::test_florence_2[florence_result18-resolution_wh18-expected_results18-exception18]" ]
[]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> Add Florence 2 support # Description This PR adds [Florence 2](https://huggingface.co/microsoft/Florence-2-large) support for supervision. Run it with `transfomers` and parse with `from_lmm(sv.LMM.FLORENCE_2, result)`. No extra documentation was added to `from_lmm` at this point. ## Type of change - [x] New feature (non-breaking change which adds functionality) ## How has this change been tested, please provide a testcase or example of how you tested the change? Usage and testing in Colab: https://colab.research.google.com/drive/19XoQZ6LRdTUysAHUp-3JsfT_67T0rffE#scrollTo=CwPzmI9wOSQ6 ## Any specific deployment considerations Run the Colab in High-RAM mode. ## Docs - [ ] Docs updated? What were the changes: ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in supervision/detection/lmm.py] (definition of validate_lmm_parameters:) def validate_lmm_parameters( lmm: Union[LMM, str], result: Any, kwargs: Dict[str, Any] ) -> LMM: (definition of from_florence_2:) def from_florence_2( result: dict, resolution_wh: Tuple[int, int] ) -> Tuple[ np.ndarray, Optional[np.ndarray], Optional[np.ndarray], Optional[np.ndarray] ]: """Parse results from the Florence 2 multi-model model. https://huggingface.co/microsoft/Florence-2-large Parameters: result: dict containing the model output Returns: xyxy (np.ndarray): An array of shape `(n, 4)` containing the bounding boxes coordinates in format `[x1, y1, x2, y2]` labels: (Optional[np.ndarray]): An array of shape `(n,)` containing the class labels for each bounding box masks: (Optional[np.ndarray]): An array of shape `(n, h, w)` containing the segmentation masks for each bounding box obb_boxes: (Optional[np.ndarray]): An array of shape `(n, 4, 2)` containing oriented bounding boxes.""" [end of new definitions in supervision/detection/lmm.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
3eb5c0b024e3e46877b7fe4fd66e6177d1308ba0
deepset-ai__haystack-7902
7,902
deepset-ai/haystack
null
57c1d47c7d55caf1385e8315e18bab2bfe1ce2f6
2024-06-20T11:21:56Z
diff --git a/haystack/document_stores/types/filter_policy.py b/haystack/document_stores/types/filter_policy.py index b30b9d3352..a2be576d20 100644 --- a/haystack/document_stores/types/filter_policy.py +++ b/haystack/document_stores/types/filter_policy.py @@ -3,6 +3,7 @@ # SPDX-License-Identifier: Apache-2.0 from enum import Enum +from typing import Any, Dict, Optional class FilterPolicy(Enum): @@ -33,3 +34,28 @@ def from_str(filter_policy: str) -> "FilterPolicy": msg = f"Unknown FilterPolicy type '{filter_policy}'. Supported types are: {list(enum_map.keys())}" raise ValueError(msg) return policy + + +def apply_filter_policy( + filter_policy: FilterPolicy, + init_filters: Optional[Dict[str, Any]] = None, + runtime_filters: Optional[Dict[str, Any]] = None, +) -> Optional[Dict[str, Any]]: + """ + Apply the filter policy to the given initial and runtime filters to determine the final set of filters used. + + The function combines or replaces the initial and runtime filters based on the specified filter policy. + + :param filter_policy: The policy to apply when handling the filters. It can be one of the following: + - `FilterPolicy.REPLACE`: Runtime filters will replace the initial filters. + - `FilterPolicy.MERGE`: Runtime filters will be merged with the initial filters. If there are overlapping keys, + values from the runtime filters will overwrite those from the initial filters. + :param init_filters: The initial filters set during the initialization of the relevant retriever. + :param runtime_filters: The filters provided at runtime, usually during a query operation execution. These filters + can change for each query/retreiver run invocation. + :returns: A dictionary containing the resulting filters based on the provided policy. + """ + if filter_policy == FilterPolicy.MERGE and runtime_filters: + return {**(init_filters or {}), **runtime_filters} + else: + return runtime_filters or init_filters diff --git a/releasenotes/notes/add-apply_filter_policy-function-ae3152e6afe0ca57.yaml b/releasenotes/notes/add-apply_filter_policy-function-ae3152e6afe0ca57.yaml new file mode 100644 index 0000000000..c890a44297 --- /dev/null +++ b/releasenotes/notes/add-apply_filter_policy-function-ae3152e6afe0ca57.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Added the apply_filter_policy function to standardize the application of filter policies across all document store-specific retrievers, allowing for consistent handling of initial and runtime filters based on the chosen policy (replace or merge).
diff --git a/test/document_stores/test_filter_policy.py b/test/document_stores/test_filter_policy.py new file mode 100644 index 0000000000..b7efcd0672 --- /dev/null +++ b/test/document_stores/test_filter_policy.py @@ -0,0 +1,45 @@ +# SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai> +# +# SPDX-License-Identifier: Apache-2.0 + +import pytest +from typing import Any, Dict, Optional +from enum import Enum + +from haystack.document_stores.types import FilterPolicy +from haystack.document_stores.types.filter_policy import apply_filter_policy + + +def test_replace_policy_with_both_filters(): + init_filters = {"status": "active", "category": "news"} + runtime_filters = {"author": "John Doe"} + result = apply_filter_policy(FilterPolicy.REPLACE, init_filters, runtime_filters) + assert result == runtime_filters + + +def test_merge_policy_with_both_filters(): + init_filters = {"status": "active", "category": "news"} + runtime_filters = {"author": "John Doe"} + result = apply_filter_policy(FilterPolicy.MERGE, init_filters, runtime_filters) + assert result == {"status": "active", "category": "news", "author": "John Doe"} + + +def test_replace_policy_with_only_init_filters(): + init_filters = {"status": "active", "category": "news"} + runtime_filters = None + result = apply_filter_policy(FilterPolicy.REPLACE, init_filters, runtime_filters) + assert result == init_filters + + +def test_merge_policy_with_only_init_filters(): + init_filters = {"status": "active", "category": "news"} + runtime_filters = None + result = apply_filter_policy(FilterPolicy.MERGE, init_filters, runtime_filters) + assert result == init_filters + + +def test_merge_policy_with_overlapping_keys(): + init_filters = {"status": "active", "category": "news"} + runtime_filters = {"category": "science", "author": "John Doe"} + result = apply_filter_policy(FilterPolicy.MERGE, init_filters, runtime_filters) + assert result == {"status": "active", "category": "science", "author": "John Doe"}
diff --git a/releasenotes/notes/add-apply_filter_policy-function-ae3152e6afe0ca57.yaml b/releasenotes/notes/add-apply_filter_policy-function-ae3152e6afe0ca57.yaml new file mode 100644 index 0000000000..c890a44297 --- /dev/null +++ b/releasenotes/notes/add-apply_filter_policy-function-ae3152e6afe0ca57.yaml @@ -0,0 +1,4 @@ +--- +enhancements: + - | + Added the apply_filter_policy function to standardize the application of filter policies across all document store-specific retrievers, allowing for consistent handling of initial and runtime filters based on the chosen policy (replace or merge).
[ { "components": [ { "doc": "Apply the filter policy to the given initial and runtime filters to determine the final set of filters used.\n\nThe function combines or replaces the initial and runtime filters based on the specified filter policy.\n\n:param filter_policy: The policy to apply when handling the filters. It can be one of the following:\n - `FilterPolicy.REPLACE`: Runtime filters will replace the initial filters.\n - `FilterPolicy.MERGE`: Runtime filters will be merged with the initial filters. If there are overlapping keys,\n values from the runtime filters will overwrite those from the initial filters.\n:param init_filters: The initial filters set during the initialization of the relevant retriever.\n:param runtime_filters: The filters provided at runtime, usually during a query operation execution. These filters\n can change for each query/retreiver run invocation.\n:returns: A dictionary containing the resulting filters based on the provided policy.", "lines": [ 39, 61 ], "name": "apply_filter_policy", "signature": "def apply_filter_policy( filter_policy: FilterPolicy, init_filters: Optional[Dict[str, Any]] = None, runtime_filters: Optional[Dict[str, Any]] = None, ) -> Optional[Dict[str, Any]]:", "type": "function" } ], "file": "haystack/document_stores/types/filter_policy.py" } ]
[ "test/document_stores/test_filter_policy.py::test_replace_policy_with_both_filters", "test/document_stores/test_filter_policy.py::test_merge_policy_with_both_filters", "test/document_stores/test_filter_policy.py::test_replace_policy_with_only_init_filters", "test/document_stores/test_filter_policy.py::test_merge_policy_with_only_init_filters", "test/document_stores/test_filter_policy.py::test_merge_policy_with_overlapping_keys" ]
[]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> feat: Add apply_filter_policy function Added the apply_filter_policy function to standardize the application of filter policies across all document store-specific retrievers, allowing for consistent handling of initial and runtime filters based on the chosen policy (replace or merge). Add unit tests for `apply_filter_policy` function ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in haystack/document_stores/types/filter_policy.py] (definition of apply_filter_policy:) def apply_filter_policy( filter_policy: FilterPolicy, init_filters: Optional[Dict[str, Any]] = None, runtime_filters: Optional[Dict[str, Any]] = None, ) -> Optional[Dict[str, Any]]: """Apply the filter policy to the given initial and runtime filters to determine the final set of filters used. The function combines or replaces the initial and runtime filters based on the specified filter policy. :param filter_policy: The policy to apply when handling the filters. It can be one of the following: - `FilterPolicy.REPLACE`: Runtime filters will replace the initial filters. - `FilterPolicy.MERGE`: Runtime filters will be merged with the initial filters. If there are overlapping keys, values from the runtime filters will overwrite those from the initial filters. :param init_filters: The initial filters set during the initialization of the relevant retriever. :param runtime_filters: The filters provided at runtime, usually during a query operation execution. These filters can change for each query/retreiver run invocation. :returns: A dictionary containing the resulting filters based on the provided policy.""" [end of new definitions in haystack/document_stores/types/filter_policy.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
f4d9c2bb917be0ffe132dffcc2ad4f1b0fcc5967
scikit-learn__scikit-learn-29210
29,210
scikit-learn/scikit-learn
1.6
51c8e0e19d042a2dbbc1f9477557c07c8a34ab96
2024-06-07T10:08:06Z
diff --git a/doc/modules/model_evaluation.rst b/doc/modules/model_evaluation.rst index eff6684458deb..080ed0c63a58c 100644 --- a/doc/modules/model_evaluation.rst +++ b/doc/modules/model_evaluation.rst @@ -605,7 +605,7 @@ The function :func:`cohen_kappa_score` computes `Cohen's kappa This measure is intended to compare labelings by different human annotators, not a classifier versus a ground truth. -The kappa score (see docstring) is a number between -1 and 1. +The kappa score is a number between -1 and 1. Scores above .8 are generally considered good agreement; zero or lower means no agreement (practically random labels). @@ -614,9 +614,9 @@ but not for multilabel problems (except by manually computing a per-label score) and not for more than two annotators. >>> from sklearn.metrics import cohen_kappa_score - >>> y_true = [2, 0, 2, 2, 0, 1] - >>> y_pred = [0, 0, 2, 2, 0, 2] - >>> cohen_kappa_score(y_true, y_pred) + >>> labeling1 = [2, 0, 2, 2, 0, 1] + >>> labeling2 = [0, 0, 2, 2, 0, 2] + >>> cohen_kappa_score(labeling1, labeling2) 0.4285714285714286 .. _confusion_matrix: diff --git a/doc/whats_new/v1.6.rst b/doc/whats_new/v1.6.rst index fd43347cf7ac8..55a669dce3a53 100644 --- a/doc/whats_new/v1.6.rst +++ b/doc/whats_new/v1.6.rst @@ -133,6 +133,11 @@ Changelog whether to raise an exception if a subset of the scorers in multimetric scoring fails or to return an error code. :pr:`28992` by :user:`Stefanie Senger <StefanieSenger>`. +- |Enhancement| Adds `zero_division` to :func:`cohen_kappa_score`. When there is a + division by zero, the metric is undefined and this value is returned. + :pr:`29210` by :user:`Marc Torrellas Socastro <marctorsoc>` and + :user:`Stefanie Senger <StefanieSenger>`. + :mod:`sklearn.model_selection` .............................. diff --git a/sklearn/metrics/_classification.py b/sklearn/metrics/_classification.py index dca3bc18bfc21..baedb5e319f8b 100644 --- a/sklearn/metrics/_classification.py +++ b/sklearn/metrics/_classification.py @@ -610,6 +610,37 @@ def multilabel_confusion_matrix( return np.array([tn, fp, fn, tp]).T.reshape(-1, 2, 2) +def _metric_handle_division(*, numerator, denominator, metric, zero_division): + """Helper to handle zero-division. + + Parameters + ---------- + numerator : numbers.Real + The numerator of the division. + denominator : numbers.Real + The denominator of the division. + metric : str + Name of the caller metric function. + zero_division : {0.0, 1.0, "warn"} + The strategy to use when encountering 0-denominator. + + Returns + ------- + result : numbers.Real + The resulting of the division + is_zero_division : bool + Whether or not we encountered a zero division. This value could be + required to early return `result` in the "caller" function. + """ + if np.isclose(denominator, 0): + if zero_division == "warn": + msg = f"{metric} is ill-defined and set to 0.0. Use the `zero_division` " + "param to control this behavior." + warnings.warn(msg, UndefinedMetricWarning, stacklevel=2) + return _check_zero_division(zero_division), True + return numerator / denominator, False + + @validate_params( { "y1": ["array-like"], @@ -617,10 +648,16 @@ def multilabel_confusion_matrix( "labels": ["array-like", None], "weights": [StrOptions({"linear", "quadratic"}), None], "sample_weight": ["array-like", None], + "zero_division": [ + StrOptions({"warn"}), + Options(Real, {0.0, 1.0, np.nan}), + ], }, prefer_skip_nested_validation=True, ) -def cohen_kappa_score(y1, y2, *, labels=None, weights=None, sample_weight=None): +def cohen_kappa_score( + y1, y2, *, labels=None, weights=None, sample_weight=None, zero_division="warn" +): r"""Compute Cohen's kappa: a statistic that measures inter-annotator agreement. This function computes Cohen's kappa [1]_, a score that expresses the level @@ -653,12 +690,20 @@ class labels [2]_. ``y1`` or ``y2`` are used. weights : {'linear', 'quadratic'}, default=None - Weighting type to calculate the score. `None` means no weighted; - "linear" means linear weighted; "quadratic" means quadratic weighted. + Weighting type to calculate the score. `None` means not weighted; + "linear" means linear weighting; "quadratic" means quadratic weighting. sample_weight : array-like of shape (n_samples,), default=None Sample weights. + zero_division : {"warn", 0.0, 1.0, np.nan}, default="warn" + Sets the return value when there is a zero division. This is the case when both + labelings `y1` and `y2` both exclusively contain the 0 class (e. g. + `[0, 0, 0, 0]`) (or if both are empty). If set to "warn", returns `0.0`, but a + warning is also raised. + + .. versionadded:: 1.6 + Returns ------- kappa : float @@ -688,7 +733,18 @@ class labels [2]_. n_classes = confusion.shape[0] sum0 = np.sum(confusion, axis=0) sum1 = np.sum(confusion, axis=1) - expected = np.outer(sum0, sum1) / np.sum(sum0) + + numerator = np.outer(sum0, sum1) + denominator = np.sum(sum0) + expected, is_zero_division = _metric_handle_division( + numerator=numerator, + denominator=denominator, + metric="cohen_kappa_score()", + zero_division=zero_division, + ) + + if is_zero_division: + return expected if weights is None: w_mat = np.ones([n_classes, n_classes], dtype=int) @@ -701,8 +757,18 @@ class labels [2]_. else: w_mat = (w_mat - w_mat.T) ** 2 - k = np.sum(w_mat * confusion) / np.sum(w_mat * expected) - return 1 - k + numerator = np.sum(w_mat * confusion) + denominator = np.sum(w_mat * expected) + score, is_zero_division = _metric_handle_division( + numerator=numerator, + denominator=denominator, + metric="cohen_kappa_score()", + zero_division=zero_division, + ) + + if is_zero_division: + return score + return 1 - score @validate_params(
diff --git a/sklearn/metrics/tests/test_classification.py b/sklearn/metrics/tests/test_classification.py index b87e76ba2fb42..aa612f73ef5c7 100644 --- a/sklearn/metrics/tests/test_classification.py +++ b/sklearn/metrics/tests/test_classification.py @@ -810,6 +810,7 @@ def test_matthews_corrcoef_nan(): partial(fbeta_score, beta=1), precision_score, recall_score, + partial(cohen_kappa_score, labels=[0, 1]), ], ) def test_zero_division_nan_no_warning(metric, y_true, y_pred, zero_division): @@ -834,6 +835,7 @@ def test_zero_division_nan_no_warning(metric, y_true, y_pred, zero_division): partial(fbeta_score, beta=1), precision_score, recall_score, + cohen_kappa_score, ], ) def test_zero_division_nan_warning(metric, y_true, y_pred):
diff --git a/doc/modules/model_evaluation.rst b/doc/modules/model_evaluation.rst index eff6684458deb..080ed0c63a58c 100644 --- a/doc/modules/model_evaluation.rst +++ b/doc/modules/model_evaluation.rst @@ -605,7 +605,7 @@ The function :func:`cohen_kappa_score` computes `Cohen's kappa This measure is intended to compare labelings by different human annotators, not a classifier versus a ground truth. -The kappa score (see docstring) is a number between -1 and 1. +The kappa score is a number between -1 and 1. Scores above .8 are generally considered good agreement; zero or lower means no agreement (practically random labels). @@ -614,9 +614,9 @@ but not for multilabel problems (except by manually computing a per-label score) and not for more than two annotators. >>> from sklearn.metrics import cohen_kappa_score - >>> y_true = [2, 0, 2, 2, 0, 1] - >>> y_pred = [0, 0, 2, 2, 0, 2] - >>> cohen_kappa_score(y_true, y_pred) + >>> labeling1 = [2, 0, 2, 2, 0, 1] + >>> labeling2 = [0, 0, 2, 2, 0, 2] + >>> cohen_kappa_score(labeling1, labeling2) 0.4285714285714286 .. _confusion_matrix: diff --git a/doc/whats_new/v1.6.rst b/doc/whats_new/v1.6.rst index fd43347cf7ac8..55a669dce3a53 100644 --- a/doc/whats_new/v1.6.rst +++ b/doc/whats_new/v1.6.rst @@ -133,6 +133,11 @@ Changelog whether to raise an exception if a subset of the scorers in multimetric scoring fails or to return an error code. :pr:`28992` by :user:`Stefanie Senger <StefanieSenger>`. +- |Enhancement| Adds `zero_division` to :func:`cohen_kappa_score`. When there is a + division by zero, the metric is undefined and this value is returned. + :pr:`29210` by :user:`Marc Torrellas Socastro <marctorsoc>` and + :user:`Stefanie Senger <StefanieSenger>`. + :mod:`sklearn.model_selection` ..............................
[ { "components": [ { "doc": "Helper to handle zero-division.\n\nParameters\n----------\nnumerator : numbers.Real\n The numerator of the division.\ndenominator : numbers.Real\n The denominator of the division.\nmetric : str\n Name of the caller metric function.\nzero_division : {0.0, 1.0, \"warn\"}\n The strategy to use when encountering 0-denominator.\n\nReturns\n-------\nresult : numbers.Real\n The resulting of the division\nis_zero_division : bool\n Whether or not we encountered a zero division. This value could be\n required to early return `result` in the \"caller\" function.", "lines": [ 613, 641 ], "name": "_metric_handle_division", "signature": "def _metric_handle_division(*, numerator, denominator, metric, zero_division):", "type": "function" } ], "file": "sklearn/metrics/_classification.py" } ]
[ "sklearn/metrics/tests/test_classification.py::test_zero_division_nan_no_warning[metric4-y_true0-y_pred0-0]", "sklearn/metrics/tests/test_classification.py::test_zero_division_nan_no_warning[metric4-y_true0-y_pred0-1]", "sklearn/metrics/tests/test_classification.py::test_zero_division_nan_no_warning[metric4-y_true0-y_pred0-nan]", "sklearn/metrics/tests/test_classification.py::test_zero_division_nan_no_warning[metric4-y_true1-y_pred1-0]", "sklearn/metrics/tests/test_classification.py::test_zero_division_nan_no_warning[metric4-y_true1-y_pred1-1]", "sklearn/metrics/tests/test_classification.py::test_zero_division_nan_no_warning[metric4-y_true1-y_pred1-nan]", "sklearn/metrics/tests/test_classification.py::test_zero_division_nan_warning[cohen_kappa_score-y_true0-y_pred0]", "sklearn/metrics/tests/test_classification.py::test_zero_division_nan_warning[cohen_kappa_score-y_true1-y_pred1]" ]
[ "sklearn/metrics/tests/test_classification.py::test_classification_report_dictionary_output", "sklearn/metrics/tests/test_classification.py::test_classification_report_output_dict_empty_input", "sklearn/metrics/tests/test_classification.py::test_classification_report_zero_division_warning[warn]", "sklearn/metrics/tests/test_classification.py::test_classification_report_zero_division_warning[0]", "sklearn/metrics/tests/test_classification.py::test_classification_report_zero_division_warning[1]", "sklearn/metrics/tests/test_classification.py::test_classification_report_zero_division_warning[nan]", "sklearn/metrics/tests/test_classification.py::test_classification_report_labels_subset_superset[labels0-True]", "sklearn/metrics/tests/test_classification.py::test_classification_report_labels_subset_superset[labels1-False]", "sklearn/metrics/tests/test_classification.py::test_classification_report_labels_subset_superset[labels2-False]", "sklearn/metrics/tests/test_classification.py::test_multilabel_accuracy_score_subset_accuracy", "sklearn/metrics/tests/test_classification.py::test_precision_recall_f1_score_binary", "sklearn/metrics/tests/test_classification.py::test_precision_recall_f_binary_single_class", "sklearn/metrics/tests/test_classification.py::test_precision_recall_f_extra_labels", "sklearn/metrics/tests/test_classification.py::test_precision_recall_f_ignored_labels", "sklearn/metrics/tests/test_classification.py::test_average_precision_score_non_binary_class", "sklearn/metrics/tests/test_classification.py::test_average_precision_score_duplicate_values[y_true0-y_score0]", "sklearn/metrics/tests/test_classification.py::test_average_precision_score_duplicate_values[y_true1-y_score1]", "sklearn/metrics/tests/test_classification.py::test_average_precision_score_tied_values[y_true0-y_score0]", "sklearn/metrics/tests/test_classification.py::test_average_precision_score_tied_values[y_true1-y_score1]", "sklearn/metrics/tests/test_classification.py::test_precision_recall_f_unused_pos_label", "sklearn/metrics/tests/test_classification.py::test_confusion_matrix_binary", "sklearn/metrics/tests/test_classification.py::test_multilabel_confusion_matrix_binary", "sklearn/metrics/tests/test_classification.py::test_multilabel_confusion_matrix_multiclass", "sklearn/metrics/tests/test_classification.py::test_multilabel_confusion_matrix_multilabel[csr_matrix-csc_matrix]", "sklearn/metrics/tests/test_classification.py::test_multilabel_confusion_matrix_multilabel[csr_matrix-csc_array]", "sklearn/metrics/tests/test_classification.py::test_multilabel_confusion_matrix_multilabel[csr_array-csc_matrix]", "sklearn/metrics/tests/test_classification.py::test_multilabel_confusion_matrix_multilabel[csr_array-csc_array]", "sklearn/metrics/tests/test_classification.py::test_multilabel_confusion_matrix_errors", "sklearn/metrics/tests/test_classification.py::test_confusion_matrix_normalize[true-f-0.333333333]", "sklearn/metrics/tests/test_classification.py::test_confusion_matrix_normalize[pred-f-0.333333333]", "sklearn/metrics/tests/test_classification.py::test_confusion_matrix_normalize[all-f-0.1111111111]", "sklearn/metrics/tests/test_classification.py::test_confusion_matrix_normalize[None-i-2]", "sklearn/metrics/tests/test_classification.py::test_confusion_matrix_normalize_single_class", "sklearn/metrics/tests/test_classification.py::test_confusion_matrix_single_label", "sklearn/metrics/tests/test_classification.py::test_likelihood_ratios_warnings[params0-samples", "sklearn/metrics/tests/test_classification.py::test_likelihood_ratios_warnings[params1-positive_likelihood_ratio", "sklearn/metrics/tests/test_classification.py::test_likelihood_ratios_warnings[params2-no", "sklearn/metrics/tests/test_classification.py::test_likelihood_ratios_warnings[params3-negative_likelihood_ratio", "sklearn/metrics/tests/test_classification.py::test_likelihood_ratios_warnings[params4-no", "sklearn/metrics/tests/test_classification.py::test_likelihood_ratios_errors[params0-class_likelihood_ratios", "sklearn/metrics/tests/test_classification.py::test_likelihood_ratios", "sklearn/metrics/tests/test_classification.py::test_cohen_kappa", "sklearn/metrics/tests/test_classification.py::test_matthews_corrcoef_nan", "sklearn/metrics/tests/test_classification.py::test_zero_division_nan_no_warning[f1_score-y_true0-y_pred0-0]", "sklearn/metrics/tests/test_classification.py::test_zero_division_nan_no_warning[f1_score-y_true0-y_pred0-1]", "sklearn/metrics/tests/test_classification.py::test_zero_division_nan_no_warning[f1_score-y_true0-y_pred0-nan]", "sklearn/metrics/tests/test_classification.py::test_zero_division_nan_no_warning[f1_score-y_true1-y_pred1-0]", "sklearn/metrics/tests/test_classification.py::test_zero_division_nan_no_warning[f1_score-y_true1-y_pred1-1]", "sklearn/metrics/tests/test_classification.py::test_zero_division_nan_no_warning[f1_score-y_true1-y_pred1-nan]", "sklearn/metrics/tests/test_classification.py::test_zero_division_nan_no_warning[metric1-y_true0-y_pred0-0]", "sklearn/metrics/tests/test_classification.py::test_zero_division_nan_no_warning[metric1-y_true0-y_pred0-1]", "sklearn/metrics/tests/test_classification.py::test_zero_division_nan_no_warning[metric1-y_true0-y_pred0-nan]", "sklearn/metrics/tests/test_classification.py::test_zero_division_nan_no_warning[metric1-y_true1-y_pred1-0]", "sklearn/metrics/tests/test_classification.py::test_zero_division_nan_no_warning[metric1-y_true1-y_pred1-1]", "sklearn/metrics/tests/test_classification.py::test_zero_division_nan_no_warning[metric1-y_true1-y_pred1-nan]", "sklearn/metrics/tests/test_classification.py::test_zero_division_nan_no_warning[precision_score-y_true0-y_pred0-0]", "sklearn/metrics/tests/test_classification.py::test_zero_division_nan_no_warning[precision_score-y_true0-y_pred0-1]", "sklearn/metrics/tests/test_classification.py::test_zero_division_nan_no_warning[precision_score-y_true0-y_pred0-nan]", "sklearn/metrics/tests/test_classification.py::test_zero_division_nan_no_warning[precision_score-y_true1-y_pred1-0]", "sklearn/metrics/tests/test_classification.py::test_zero_division_nan_no_warning[precision_score-y_true1-y_pred1-1]", "sklearn/metrics/tests/test_classification.py::test_zero_division_nan_no_warning[precision_score-y_true1-y_pred1-nan]", "sklearn/metrics/tests/test_classification.py::test_zero_division_nan_no_warning[recall_score-y_true0-y_pred0-0]", "sklearn/metrics/tests/test_classification.py::test_zero_division_nan_no_warning[recall_score-y_true0-y_pred0-1]", "sklearn/metrics/tests/test_classification.py::test_zero_division_nan_no_warning[recall_score-y_true0-y_pred0-nan]", "sklearn/metrics/tests/test_classification.py::test_zero_division_nan_no_warning[recall_score-y_true1-y_pred1-0]", "sklearn/metrics/tests/test_classification.py::test_zero_division_nan_no_warning[recall_score-y_true1-y_pred1-1]", "sklearn/metrics/tests/test_classification.py::test_zero_division_nan_no_warning[recall_score-y_true1-y_pred1-nan]", "sklearn/metrics/tests/test_classification.py::test_zero_division_nan_warning[f1_score-y_true0-y_pred0]", "sklearn/metrics/tests/test_classification.py::test_zero_division_nan_warning[f1_score-y_true1-y_pred1]", "sklearn/metrics/tests/test_classification.py::test_zero_division_nan_warning[metric1-y_true0-y_pred0]", "sklearn/metrics/tests/test_classification.py::test_zero_division_nan_warning[metric1-y_true1-y_pred1]", "sklearn/metrics/tests/test_classification.py::test_zero_division_nan_warning[precision_score-y_true0-y_pred0]", "sklearn/metrics/tests/test_classification.py::test_zero_division_nan_warning[precision_score-y_true1-y_pred1]", "sklearn/metrics/tests/test_classification.py::test_zero_division_nan_warning[recall_score-y_true0-y_pred0]", "sklearn/metrics/tests/test_classification.py::test_zero_division_nan_warning[recall_score-y_true1-y_pred1]", "sklearn/metrics/tests/test_classification.py::test_matthews_corrcoef_against_numpy_corrcoef", "sklearn/metrics/tests/test_classification.py::test_matthews_corrcoef_against_jurman", "sklearn/metrics/tests/test_classification.py::test_matthews_corrcoef", "sklearn/metrics/tests/test_classification.py::test_matthews_corrcoef_multiclass", "sklearn/metrics/tests/test_classification.py::test_matthews_corrcoef_overflow[100]", "sklearn/metrics/tests/test_classification.py::test_matthews_corrcoef_overflow[10000]", "sklearn/metrics/tests/test_classification.py::test_precision_recall_f1_score_multiclass", "sklearn/metrics/tests/test_classification.py::test_precision_refcall_f1_score_multilabel_unordered_labels[samples]", "sklearn/metrics/tests/test_classification.py::test_precision_refcall_f1_score_multilabel_unordered_labels[micro]", "sklearn/metrics/tests/test_classification.py::test_precision_refcall_f1_score_multilabel_unordered_labels[macro]", "sklearn/metrics/tests/test_classification.py::test_precision_refcall_f1_score_multilabel_unordered_labels[weighted]", "sklearn/metrics/tests/test_classification.py::test_precision_refcall_f1_score_multilabel_unordered_labels[None]", "sklearn/metrics/tests/test_classification.py::test_precision_recall_f1_score_binary_averaged", "sklearn/metrics/tests/test_classification.py::test_zero_precision_recall", "sklearn/metrics/tests/test_classification.py::test_confusion_matrix_multiclass_subset_labels", "sklearn/metrics/tests/test_classification.py::test_confusion_matrix_error[empty", "sklearn/metrics/tests/test_classification.py::test_confusion_matrix_error[unknown", "sklearn/metrics/tests/test_classification.py::test_confusion_matrix_on_zero_length_input[None]", "sklearn/metrics/tests/test_classification.py::test_confusion_matrix_on_zero_length_input[binary]", "sklearn/metrics/tests/test_classification.py::test_confusion_matrix_on_zero_length_input[multiclass]", "sklearn/metrics/tests/test_classification.py::test_confusion_matrix_dtype", "sklearn/metrics/tests/test_classification.py::test_confusion_matrix_pandas_nullable[Int64]", "sklearn/metrics/tests/test_classification.py::test_confusion_matrix_pandas_nullable[Float64]", "sklearn/metrics/tests/test_classification.py::test_confusion_matrix_pandas_nullable[boolean]", "sklearn/metrics/tests/test_classification.py::test_classification_report_multiclass", "sklearn/metrics/tests/test_classification.py::test_classification_report_multiclass_balanced", "sklearn/metrics/tests/test_classification.py::test_classification_report_multiclass_with_label_detection", "sklearn/metrics/tests/test_classification.py::test_classification_report_multiclass_with_digits", "sklearn/metrics/tests/test_classification.py::test_classification_report_multiclass_with_string_label", "sklearn/metrics/tests/test_classification.py::test_classification_report_multiclass_with_unicode_label", "sklearn/metrics/tests/test_classification.py::test_classification_report_multiclass_with_long_string_label", "sklearn/metrics/tests/test_classification.py::test_classification_report_labels_target_names_unequal_length", "sklearn/metrics/tests/test_classification.py::test_classification_report_no_labels_target_names_unequal_length", "sklearn/metrics/tests/test_classification.py::test_multilabel_classification_report", "sklearn/metrics/tests/test_classification.py::test_multilabel_zero_one_loss_subset", "sklearn/metrics/tests/test_classification.py::test_multilabel_hamming_loss", "sklearn/metrics/tests/test_classification.py::test_jaccard_score_validation", "sklearn/metrics/tests/test_classification.py::test_multilabel_jaccard_score", "sklearn/metrics/tests/test_classification.py::test_multiclass_jaccard_score", "sklearn/metrics/tests/test_classification.py::test_average_binary_jaccard_score", "sklearn/metrics/tests/test_classification.py::test_jaccard_score_zero_division_warning", "sklearn/metrics/tests/test_classification.py::test_jaccard_score_zero_division_set_value[0-0]", "sklearn/metrics/tests/test_classification.py::test_jaccard_score_zero_division_set_value[1-0.5]", "sklearn/metrics/tests/test_classification.py::test_precision_recall_f1_score_multilabel_1", "sklearn/metrics/tests/test_classification.py::test_precision_recall_f1_score_multilabel_2", "sklearn/metrics/tests/test_classification.py::test_precision_recall_f1_score_with_an_empty_prediction[warn-0]", "sklearn/metrics/tests/test_classification.py::test_precision_recall_f1_score_with_an_empty_prediction[0-0]", "sklearn/metrics/tests/test_classification.py::test_precision_recall_f1_score_with_an_empty_prediction[1-1]", "sklearn/metrics/tests/test_classification.py::test_precision_recall_f1_score_with_an_empty_prediction[nan-nan]", "sklearn/metrics/tests/test_classification.py::test_precision_recall_f1_no_labels[0-macro-1]", "sklearn/metrics/tests/test_classification.py::test_precision_recall_f1_no_labels[0-micro-1]", "sklearn/metrics/tests/test_classification.py::test_precision_recall_f1_no_labels[0-weighted-1]", "sklearn/metrics/tests/test_classification.py::test_precision_recall_f1_no_labels[0-samples-1]", "sklearn/metrics/tests/test_classification.py::test_precision_recall_f1_no_labels[1-macro-1]", "sklearn/metrics/tests/test_classification.py::test_precision_recall_f1_no_labels[1-micro-1]", "sklearn/metrics/tests/test_classification.py::test_precision_recall_f1_no_labels[1-weighted-1]", "sklearn/metrics/tests/test_classification.py::test_precision_recall_f1_no_labels[1-samples-1]", "sklearn/metrics/tests/test_classification.py::test_precision_recall_f1_no_labels[nan-macro-1]", "sklearn/metrics/tests/test_classification.py::test_precision_recall_f1_no_labels[nan-micro-1]", "sklearn/metrics/tests/test_classification.py::test_precision_recall_f1_no_labels[nan-weighted-1]", "sklearn/metrics/tests/test_classification.py::test_precision_recall_f1_no_labels[nan-samples-1]", "sklearn/metrics/tests/test_classification.py::test_precision_recall_f1_no_labels_check_warnings[macro]", "sklearn/metrics/tests/test_classification.py::test_precision_recall_f1_no_labels_check_warnings[micro]", "sklearn/metrics/tests/test_classification.py::test_precision_recall_f1_no_labels_check_warnings[weighted]", "sklearn/metrics/tests/test_classification.py::test_precision_recall_f1_no_labels_check_warnings[samples]", "sklearn/metrics/tests/test_classification.py::test_precision_recall_f1_no_labels_average_none[0]", "sklearn/metrics/tests/test_classification.py::test_precision_recall_f1_no_labels_average_none[1]", "sklearn/metrics/tests/test_classification.py::test_precision_recall_f1_no_labels_average_none[nan]", "sklearn/metrics/tests/test_classification.py::test_precision_recall_f1_no_labels_average_none_warn", "sklearn/metrics/tests/test_classification.py::test_prf_warnings", "sklearn/metrics/tests/test_classification.py::test_prf_no_warnings_if_zero_division_set[0]", "sklearn/metrics/tests/test_classification.py::test_prf_no_warnings_if_zero_division_set[1]", "sklearn/metrics/tests/test_classification.py::test_prf_no_warnings_if_zero_division_set[nan]", "sklearn/metrics/tests/test_classification.py::test_recall_warnings[warn]", "sklearn/metrics/tests/test_classification.py::test_recall_warnings[0]", "sklearn/metrics/tests/test_classification.py::test_recall_warnings[1]", "sklearn/metrics/tests/test_classification.py::test_recall_warnings[nan]", "sklearn/metrics/tests/test_classification.py::test_precision_warnings[warn]", "sklearn/metrics/tests/test_classification.py::test_precision_warnings[0]", "sklearn/metrics/tests/test_classification.py::test_precision_warnings[1]", "sklearn/metrics/tests/test_classification.py::test_precision_warnings[nan]", "sklearn/metrics/tests/test_classification.py::test_fscore_warnings[warn]", "sklearn/metrics/tests/test_classification.py::test_fscore_warnings[0]", "sklearn/metrics/tests/test_classification.py::test_fscore_warnings[1]", "sklearn/metrics/tests/test_classification.py::test_fscore_warnings[nan]", "sklearn/metrics/tests/test_classification.py::test_prf_average_binary_data_non_binary", "sklearn/metrics/tests/test_classification.py::test__check_targets", "sklearn/metrics/tests/test_classification.py::test__check_targets_multiclass_with_both_y_true_and_y_pred_binary", "sklearn/metrics/tests/test_classification.py::test_hinge_loss_binary", "sklearn/metrics/tests/test_classification.py::test_hinge_loss_multiclass", "sklearn/metrics/tests/test_classification.py::test_hinge_loss_multiclass_missing_labels_with_labels_none", "sklearn/metrics/tests/test_classification.py::test_hinge_loss_multiclass_no_consistent_pred_decision_shape", "sklearn/metrics/tests/test_classification.py::test_hinge_loss_multiclass_with_missing_labels", "sklearn/metrics/tests/test_classification.py::test_hinge_loss_multiclass_missing_labels_only_two_unq_in_y_true", "sklearn/metrics/tests/test_classification.py::test_hinge_loss_multiclass_invariance_lists", "sklearn/metrics/tests/test_classification.py::test_log_loss", "sklearn/metrics/tests/test_classification.py::test_log_loss_eps[float64]", "sklearn/metrics/tests/test_classification.py::test_log_loss_eps[float32]", "sklearn/metrics/tests/test_classification.py::test_log_loss_eps[float16]", "sklearn/metrics/tests/test_classification.py::test_log_loss_not_probabilities_warning[float64]", "sklearn/metrics/tests/test_classification.py::test_log_loss_not_probabilities_warning[float32]", "sklearn/metrics/tests/test_classification.py::test_log_loss_not_probabilities_warning[float16]", "sklearn/metrics/tests/test_classification.py::test_log_loss_perfect_predictions[y_true0-y_pred0]", "sklearn/metrics/tests/test_classification.py::test_log_loss_perfect_predictions[y_true1-y_pred1]", "sklearn/metrics/tests/test_classification.py::test_log_loss_perfect_predictions[y_true2-y_pred2]", "sklearn/metrics/tests/test_classification.py::test_log_loss_pandas_input", "sklearn/metrics/tests/test_classification.py::test_brier_score_loss", "sklearn/metrics/tests/test_classification.py::test_balanced_accuracy_score_unseen", "sklearn/metrics/tests/test_classification.py::test_balanced_accuracy_score[y_true0-y_pred0]", "sklearn/metrics/tests/test_classification.py::test_balanced_accuracy_score[y_true1-y_pred1]", "sklearn/metrics/tests/test_classification.py::test_balanced_accuracy_score[y_true2-y_pred2]", "sklearn/metrics/tests/test_classification.py::test_classification_metric_pos_label_types[classes0-jaccard_score]", "sklearn/metrics/tests/test_classification.py::test_classification_metric_pos_label_types[classes0-f1_score]", "sklearn/metrics/tests/test_classification.py::test_classification_metric_pos_label_types[classes0-metric2]", "sklearn/metrics/tests/test_classification.py::test_classification_metric_pos_label_types[classes0-precision_recall_fscore_support]", "sklearn/metrics/tests/test_classification.py::test_classification_metric_pos_label_types[classes0-precision_score]", "sklearn/metrics/tests/test_classification.py::test_classification_metric_pos_label_types[classes0-recall_score]", "sklearn/metrics/tests/test_classification.py::test_classification_metric_pos_label_types[classes0-brier_score_loss]", "sklearn/metrics/tests/test_classification.py::test_classification_metric_pos_label_types[classes1-jaccard_score]", "sklearn/metrics/tests/test_classification.py::test_classification_metric_pos_label_types[classes1-f1_score]", "sklearn/metrics/tests/test_classification.py::test_classification_metric_pos_label_types[classes1-metric2]", "sklearn/metrics/tests/test_classification.py::test_classification_metric_pos_label_types[classes1-precision_recall_fscore_support]", "sklearn/metrics/tests/test_classification.py::test_classification_metric_pos_label_types[classes1-precision_score]", "sklearn/metrics/tests/test_classification.py::test_classification_metric_pos_label_types[classes1-recall_score]", "sklearn/metrics/tests/test_classification.py::test_classification_metric_pos_label_types[classes1-brier_score_loss]", "sklearn/metrics/tests/test_classification.py::test_classification_metric_pos_label_types[classes2-jaccard_score]", "sklearn/metrics/tests/test_classification.py::test_classification_metric_pos_label_types[classes2-f1_score]", "sklearn/metrics/tests/test_classification.py::test_classification_metric_pos_label_types[classes2-metric2]", "sklearn/metrics/tests/test_classification.py::test_classification_metric_pos_label_types[classes2-precision_recall_fscore_support]", "sklearn/metrics/tests/test_classification.py::test_classification_metric_pos_label_types[classes2-precision_score]", "sklearn/metrics/tests/test_classification.py::test_classification_metric_pos_label_types[classes2-recall_score]", "sklearn/metrics/tests/test_classification.py::test_classification_metric_pos_label_types[classes2-brier_score_loss]", "sklearn/metrics/tests/test_classification.py::test_classification_metric_pos_label_types[classes3-jaccard_score]", "sklearn/metrics/tests/test_classification.py::test_classification_metric_pos_label_types[classes3-f1_score]", "sklearn/metrics/tests/test_classification.py::test_classification_metric_pos_label_types[classes3-metric2]", "sklearn/metrics/tests/test_classification.py::test_classification_metric_pos_label_types[classes3-precision_recall_fscore_support]", "sklearn/metrics/tests/test_classification.py::test_classification_metric_pos_label_types[classes3-precision_score]", "sklearn/metrics/tests/test_classification.py::test_classification_metric_pos_label_types[classes3-recall_score]", "sklearn/metrics/tests/test_classification.py::test_classification_metric_pos_label_types[classes3-brier_score_loss]", "sklearn/metrics/tests/test_classification.py::test_f1_for_small_binary_inputs_with_zero_division[y_true0-y_pred0-0.0]", "sklearn/metrics/tests/test_classification.py::test_f1_for_small_binary_inputs_with_zero_division[y_true1-y_pred1-1.0]", "sklearn/metrics/tests/test_classification.py::test_f1_for_small_binary_inputs_with_zero_division[y_true2-y_pred2-0.0]", "sklearn/metrics/tests/test_classification.py::test_f1_for_small_binary_inputs_with_zero_division[y_true3-y_pred3-1.0]", "sklearn/metrics/tests/test_classification.py::test_classification_metric_division_by_zero_nan_validaton[scoring0]", "sklearn/metrics/tests/test_classification.py::test_classification_metric_division_by_zero_nan_validaton[scoring1]", "sklearn/metrics/tests/test_classification.py::test_classification_metric_division_by_zero_nan_validaton[scoring2]", "sklearn/metrics/tests/test_classification.py::test_classification_metric_division_by_zero_nan_validaton[scoring3]", "sklearn/metrics/tests/test_classification.py::test_brier_score_loss_deprecation_warning", "sklearn/metrics/tests/test_classification.py::test_d2_log_loss_score", "sklearn/metrics/tests/test_classification.py::test_d2_log_loss_score_raises" ]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> ENH Add zero_division param to `cohen_kappa_score` #### Reference Issues/PRs towards #29048 #### What does this implement/fix? Explain your changes. Extracts the part for adding a `zero_division` param to the `cohen_kappa_score` from the original PR #23183 by @marctorsoc, that we go through in #29048. ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in sklearn/metrics/_classification.py] (definition of _metric_handle_division:) def _metric_handle_division(*, numerator, denominator, metric, zero_division): """Helper to handle zero-division. Parameters ---------- numerator : numbers.Real The numerator of the division. denominator : numbers.Real The denominator of the division. metric : str Name of the caller metric function. zero_division : {0.0, 1.0, "warn"} The strategy to use when encountering 0-denominator. Returns ------- result : numbers.Real The resulting of the division is_zero_division : bool Whether or not we encountered a zero division. This value could be required to early return `result` in the "caller" function.""" [end of new definitions in sklearn/metrics/_classification.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
18dc8630a7cbe1b591c12774949058b12157a39a
tobymao__sqlglot-3602
3,602
tobymao/sqlglot
null
f920014709c2d3ccb7ec18fb622ecd6b6ee0afcd
2024-06-05T13:00:58Z
diff --git a/sqlglot/dialects/postgres.py b/sqlglot/dialects/postgres.py index 25a02b0dcb..7ad1f90e02 100644 --- a/sqlglot/dialects/postgres.py +++ b/sqlglot/dialects/postgres.py @@ -8,6 +8,7 @@ Dialect, JSON_EXTRACT_TYPE, any_value_to_max_sql, + binary_from_function, bool_xor_sql, datestrtodate_sql, build_formatted_time, @@ -329,6 +330,7 @@ class Tokenizer(tokens.Tokenizer): "REGTYPE": TokenType.OBJECT_IDENTIFIER, "FLOAT": TokenType.DOUBLE, } + KEYWORDS.pop("DIV") SINGLE_TOKENS = { **tokens.Tokenizer.SINGLE_TOKENS, @@ -347,6 +349,9 @@ class Parser(parser.Parser): FUNCTIONS = { **parser.Parser.FUNCTIONS, "DATE_TRUNC": build_timestamp_trunc, + "DIV": lambda args: exp.cast( + binary_from_function(exp.IntDiv)(args), exp.DataType.Type.DECIMAL + ), "GENERATE_SERIES": _build_generate_series, "JSON_EXTRACT_PATH": build_json_extract_path(exp.JSONExtract), "JSON_EXTRACT_PATH_TEXT": build_json_extract_path(exp.JSONExtractScalar), @@ -494,6 +499,7 @@ class Generator(generator.Generator): exp.DateSub: _date_add_sql("-"), exp.Explode: rename_func("UNNEST"), exp.GroupConcat: _string_agg_sql, + exp.IntDiv: rename_func("DIV"), exp.JSONExtract: _json_extract_sql("JSON_EXTRACT_PATH", "->"), exp.JSONExtractScalar: _json_extract_sql("JSON_EXTRACT_PATH_TEXT", "->>"), exp.JSONBExtract: lambda self, e: self.binary(e, "#>"), @@ -621,3 +627,12 @@ def datatype_sql(self, expression: exp.DataType) -> str: return f"{self.expressions(expression, flat=True)}[{values}]" return "ARRAY" return super().datatype_sql(expression) + + def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str: + this = expression.this + + # Postgres casts DIV() to decimal for transpilation but when roundtripping it's superfluous + if isinstance(this, exp.IntDiv) and expression.to == exp.DataType.build("decimal"): + return self.sql(this) + + return super().cast_sql(expression, safe_prefix=safe_prefix)
diff --git a/tests/dialects/test_postgres.py b/tests/dialects/test_postgres.py index 74753beb61..50ba605351 100644 --- a/tests/dialects/test_postgres.py +++ b/tests/dialects/test_postgres.py @@ -724,6 +724,28 @@ def test_postgres(self): self.validate_identity("cast(a as FLOAT8)", "CAST(a AS DOUBLE PRECISION)") self.validate_identity("cast(a as FLOAT4)", "CAST(a AS REAL)") + self.validate_all( + "1 / DIV(4, 2)", + read={ + "postgres": "1 / DIV(4, 2)", + }, + write={ + "sqlite": "1 / CAST(CAST(CAST(4 AS REAL) / 2 AS INTEGER) AS REAL)", + "duckdb": "1 / CAST(4 // 2 AS DECIMAL)", + "bigquery": "1 / CAST(DIV(4, 2) AS NUMERIC)", + }, + ) + self.validate_all( + "CAST(DIV(4, 2) AS DECIMAL(5, 3))", + read={ + "duckdb": "CAST(4 // 2 AS DECIMAL(5, 3))", + }, + write={ + "duckdb": "CAST(CAST(4 // 2 AS DECIMAL) AS DECIMAL(5, 3))", + "postgres": "CAST(DIV(4, 2) AS DECIMAL(5, 3))", + }, + ) + def test_ddl(self): # Checks that user-defined types are parsed into DataType instead of Identifier self.parse_one("CREATE TABLE t (a udt)").this.expressions[0].args["kind"].assert_is(
[ { "components": [ { "doc": "", "lines": [ 631, 638 ], "name": "Postgres.Generator.cast_sql", "signature": "def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str:", "type": "function" } ], "file": "sqlglot/dialects/postgres.py" } ]
[ "tests/dialects/test_postgres.py::TestPostgres::test_postgres" ]
[ "tests/dialects/test_postgres.py::TestPostgres::test_array_offset", "tests/dialects/test_postgres.py::TestPostgres::test_bool_or", "tests/dialects/test_postgres.py::TestPostgres::test_ddl", "tests/dialects/test_postgres.py::TestPostgres::test_operator", "tests/dialects/test_postgres.py::TestPostgres::test_regexp_binary", "tests/dialects/test_postgres.py::TestPostgres::test_string_concat", "tests/dialects/test_postgres.py::TestPostgres::test_unnest", "tests/dialects/test_postgres.py::TestPostgres::test_unnest_json_array", "tests/dialects/test_postgres.py::TestPostgres::test_variance" ]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> feat(postgres): Support DIV() func for integer division Fixes #3601 This PR introduces support for Postgres's `DIV()` function which performs integer division. It mirrors the BigQuery implementation which stores the args in `exp.IntDiv` and generates it back to the function representation. [Postgres Div](https://www.postgresqltutorial.com/postgresql-math-functions/postgresql-div/) ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in sqlglot/dialects/postgres.py] (definition of Postgres.Generator.cast_sql:) def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str: [end of new definitions in sqlglot/dialects/postgres.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
Here is the discussion in the issues of the pull request. <issues> parsing div() for postgresql throws error **Summary** Trying to parse a sql statement using the DIV() method but encountering an error. **Sample Code** ```python from sqlglot import parse_one parsed_content = parse_one('select div(9,4)', read='postgres') ``` **Error** sqlglot.errors.ParseError: Required keyword: 'expressions' missing for <class 'sqlglot.expressions.Aliases'>. Line 1, Col: 12. select div(9,4) ---------- -------------------- </issues>
ceb42fabad60312699e4b15936aeebac00e22e4d
astropy__astropy-16516
16,516
astropy/astropy
v5.3
fb4ff546ebca64c4d92a573e400873aeba1f5766
2024-05-30T15:25:34Z
diff --git a/astropy/units/equivalencies.py b/astropy/units/equivalencies.py index f77b195df97d..b6968fc701ea 100644 --- a/astropy/units/equivalencies.py +++ b/astropy/units/equivalencies.py @@ -34,6 +34,7 @@ "molar_mass_amu", "pixel_scale", "plate_scale", + "magnetic_flux_field", "Equivalency", ] @@ -873,3 +874,47 @@ def plate_scale(platescale): "plate_scale", {"platescale": platescale}, ) + + +def magnetic_flux_field(mu_r=1): + r""" + Convert magnetic field between magnetic field strength :math:`(\mathbf{H})` and + magnetic flux density :math:`(\mathbf{B})` using the relationship: + + .. math:: + + \mathbf{B} = \mu_r \mu_0 \mathbf{H} + + where: + - :math:`\mu_0` is the vacuum permeability, a physical constant. + - :math:`\mu_r` is the relative permeability of the medium, a dimensionless + quantity. + + The default setting (:math:`\mu_r=1`) represents conditions in a vacuum. + + Parameters + ---------- + mu_r : float, optional + The relative magnetic permeability of the medium. This is a dimensionless quantity + and has a default value of :math:`\mu_r=1` which corresponds to free space (vacuum). + + Examples + -------- + >>> import astropy.units as u + >>> H = 1 * u.Oe + >>> H.to(u.G, equivalencies=u.magnetic_flux_field()) # doctest: +FLOAT_CMP + <Quantity 1. G> + >>> H.to(u.G, equivalencies=u.magnetic_flux_field(mu_r=0.8)) # doctest: +FLOAT_CMP + <Quantity 0.8 G> + >>> B = 1 * u.T + >>> B.to(u.A / u.m, equivalencies=u.magnetic_flux_field()) # doctest: +FLOAT_CMP + <Quantity 795774.71502628 A / m> + >>> B.to(u.A / u.m, equivalencies=u.magnetic_flux_field(mu_r=0.8)) # doctest: +FLOAT_CMP + <Quantity 994718.39378285 A / m> + + """ + mu0 = _si.mu0.value + return Equivalency( + [(si.T, si.A / si.m, lambda x: x / (mu_r * mu0), lambda x: x * mu_r * mu0)], + "magnetic_flux_field", + ) diff --git a/docs/changes/units/16516.feature.rst b/docs/changes/units/16516.feature.rst new file mode 100644 index 000000000000..4fa419d8579b --- /dev/null +++ b/docs/changes/units/16516.feature.rst @@ -0,0 +1,2 @@ +Add ``magnetic_flux_field`` equivalency to convert magnetic field between +magnetic field strength (H) and magnetic flux density (B). diff --git a/docs/units/equivalencies.rst b/docs/units/equivalencies.rst index 6093d1c529e5..20647e927f01 100644 --- a/docs/units/equivalencies.rst +++ b/docs/units/equivalencies.rst @@ -529,6 +529,46 @@ for more information. .. EXAMPLE END +Magnetic Flux Density and Field Strength Equivalency +---------------------------------------------------- + +The :func:`~astropy.units.equivalencies.magnetic_flux_field` equivalency allows +conversion between Magnetic Flux Density (B) and its equivalent Magnetic Field +Strength (H), governed by the equation + +.. math:: + + \mathbf{B} = \mu_r \mu_0 \mathbf{H}. + +Where :math:`\mu_0` is the vacuum permeability and :math:`\mu_r` is the +relative permeability of the medium. For a vacuum, :math:`\mu_r=1`. + +Example +^^^^^^^ + +.. EXAMPLE START: Magnetic Flux Density Magnetic Field Strength Equivalency + +To convert between Magnetic Flux Density (B) and its equivalent Magnetic Field +Strength (H) in a vacuum. + + >>> H = 1 * u.Oe + >>> H.to(u.G, u.magnetic_flux_field()) # doctest: +FLOAT_CMP + <Quantity 1. G> + >>> H.to(u.T, u.magnetic_flux_field()) # doctest: +FLOAT_CMP + <Quantity 0.0001 T> + >>> B = 1 * u.T + >>> B.to(u.A / u.m, equivalencies=u.magnetic_flux_field()) # doctest: +FLOAT_CMP + <Quantity 795774.71502628 A / m> + +Conversion in a medium with :math:`\mu_r=0.9`:: + + >>> H.to(u.G, u.magnetic_flux_field(mu_r=0.9)) # doctest: +FLOAT_CMP + <Quantity 0.9 G> + >>> B.to(u.A / u.m, equivalencies=u.magnetic_flux_field(mu_r=0.9)) # doctest: +FLOAT_CMP + <Quantity 884194.12780697 A / m> + +.. EXAMPLE END + Writing New Equivalencies =========================
diff --git a/astropy/units/tests/test_equivalencies.py b/astropy/units/tests/test_equivalencies.py index bd13257194eb..7aab96eb16cd 100644 --- a/astropy/units/tests/test_equivalencies.py +++ b/astropy/units/tests/test_equivalencies.py @@ -1013,3 +1013,17 @@ def test_spectral_density_factor_deprecation(): u.erg / u.Hz / u.cm**2 / u.s, 1, u.spectral_density(u.AA, factor=3500) ) assert_quantity_allclose(a, 4.086160166177361e-12) + + +def test_magnetic_flux_field(): + H = 1 * u.A / u.m + B = (H * constants.mu0).to(u.T) + assert_allclose(H.to_value(u.T, u.magnetic_flux_field()), B.value) + assert_allclose(B.to_value(u.A / u.m, u.magnetic_flux_field()), H.value) + + H = 1 * u.Oe + B = 1 * u.G + assert_allclose(H.to_value(u.G, u.magnetic_flux_field()), 1) + assert_allclose(B.to_value(u.Oe, u.magnetic_flux_field()), 1) + assert_allclose(H.to_value(u.G, u.magnetic_flux_field(mu_r=0.8)), 0.8) + assert_allclose(B.to_value(u.Oe, u.magnetic_flux_field(mu_r=0.8)), 1.25)
diff --git a/docs/changes/units/16516.feature.rst b/docs/changes/units/16516.feature.rst new file mode 100644 index 000000000000..4fa419d8579b --- /dev/null +++ b/docs/changes/units/16516.feature.rst @@ -0,0 +1,2 @@ +Add ``magnetic_flux_field`` equivalency to convert magnetic field between +magnetic field strength (H) and magnetic flux density (B). diff --git a/docs/units/equivalencies.rst b/docs/units/equivalencies.rst index 6093d1c529e5..20647e927f01 100644 --- a/docs/units/equivalencies.rst +++ b/docs/units/equivalencies.rst @@ -529,6 +529,46 @@ for more information. .. EXAMPLE END +Magnetic Flux Density and Field Strength Equivalency +---------------------------------------------------- + +The :func:`~astropy.units.equivalencies.magnetic_flux_field` equivalency allows +conversion between Magnetic Flux Density (B) and its equivalent Magnetic Field +Strength (H), governed by the equation + +.. math:: + + \mathbf{B} = \mu_r \mu_0 \mathbf{H}. + +Where :math:`\mu_0` is the vacuum permeability and :math:`\mu_r` is the +relative permeability of the medium. For a vacuum, :math:`\mu_r=1`. + +Example +^^^^^^^ + +.. EXAMPLE START: Magnetic Flux Density Magnetic Field Strength Equivalency + +To convert between Magnetic Flux Density (B) and its equivalent Magnetic Field +Strength (H) in a vacuum. + + >>> H = 1 * u.Oe + >>> H.to(u.G, u.magnetic_flux_field()) # doctest: +FLOAT_CMP + <Quantity 1. G> + >>> H.to(u.T, u.magnetic_flux_field()) # doctest: +FLOAT_CMP + <Quantity 0.0001 T> + >>> B = 1 * u.T + >>> B.to(u.A / u.m, equivalencies=u.magnetic_flux_field()) # doctest: +FLOAT_CMP + <Quantity 795774.71502628 A / m> + +Conversion in a medium with :math:`\mu_r=0.9`:: + + >>> H.to(u.G, u.magnetic_flux_field(mu_r=0.9)) # doctest: +FLOAT_CMP + <Quantity 0.9 G> + >>> B.to(u.A / u.m, equivalencies=u.magnetic_flux_field(mu_r=0.9)) # doctest: +FLOAT_CMP + <Quantity 884194.12780697 A / m> + +.. EXAMPLE END + Writing New Equivalencies =========================
[ { "components": [ { "doc": "Convert magnetic field between magnetic field strength :math:`(\\mathbf{H})` and\nmagnetic flux density :math:`(\\mathbf{B})` using the relationship:\n\n.. math::\n\n \\mathbf{B} = \\mu_r \\mu_0 \\mathbf{H}\n\nwhere:\n - :math:`\\mu_0` is the vacuum permeability, a physical constant.\n - :math:`\\mu_r` is the relative permeability of the medium, a dimensionless\n quantity.\n\nThe default setting (:math:`\\mu_r=1`) represents conditions in a vacuum.\n\nParameters\n----------\nmu_r : float, optional\n The relative magnetic permeability of the medium. This is a dimensionless quantity\n and has a default value of :math:`\\mu_r=1` which corresponds to free space (vacuum).\n\nExamples\n--------\n>>> import astropy.units as u\n>>> H = 1 * u.Oe\n>>> H.to(u.G, equivalencies=u.magnetic_flux_field()) # doctest: +FLOAT_CMP\n<Quantity 1. G>\n>>> H.to(u.G, equivalencies=u.magnetic_flux_field(mu_r=0.8)) # doctest: +FLOAT_CMP\n<Quantity 0.8 G>\n>>> B = 1 * u.T\n>>> B.to(u.A / u.m, equivalencies=u.magnetic_flux_field()) # doctest: +FLOAT_CMP\n<Quantity 795774.71502628 A / m>\n>>> B.to(u.A / u.m, equivalencies=u.magnetic_flux_field(mu_r=0.8)) # doctest: +FLOAT_CMP\n<Quantity 994718.39378285 A / m>", "lines": [ 879, 919 ], "name": "magnetic_flux_field", "signature": "def magnetic_flux_field(mu_r=1):", "type": "function" } ], "file": "astropy/units/equivalencies.py" } ]
[ "astropy/units/tests/test_equivalencies.py::test_magnetic_flux_field" ]
[ "astropy/units/tests/test_equivalencies.py::test_find_equivalent_units", "astropy/units/tests/test_equivalencies.py::test_dimensionless_angles", "astropy/units/tests/test_equivalencies.py::test_logarithmic[log_unit0]", "astropy/units/tests/test_equivalencies.py::test_logarithmic[log_unit1]", "astropy/units/tests/test_equivalencies.py::test_logarithmic[log_unit2]", "astropy/units/tests/test_equivalencies.py::test_doppler_frequency_0[doppler_optical]", "astropy/units/tests/test_equivalencies.py::test_doppler_frequency_0[doppler_radio]", "astropy/units/tests/test_equivalencies.py::test_doppler_frequency_0[doppler_relativistic]", "astropy/units/tests/test_equivalencies.py::test_doppler_wavelength_0[doppler_optical]", "astropy/units/tests/test_equivalencies.py::test_doppler_wavelength_0[doppler_radio]", "astropy/units/tests/test_equivalencies.py::test_doppler_wavelength_0[doppler_relativistic]", "astropy/units/tests/test_equivalencies.py::test_doppler_energy_0[doppler_optical]", "astropy/units/tests/test_equivalencies.py::test_doppler_energy_0[doppler_radio]", "astropy/units/tests/test_equivalencies.py::test_doppler_energy_0[doppler_relativistic]", "astropy/units/tests/test_equivalencies.py::test_doppler_frequency_circle[doppler_optical]", "astropy/units/tests/test_equivalencies.py::test_doppler_frequency_circle[doppler_radio]", "astropy/units/tests/test_equivalencies.py::test_doppler_frequency_circle[doppler_relativistic]", "astropy/units/tests/test_equivalencies.py::test_doppler_wavelength_circle[doppler_optical]", "astropy/units/tests/test_equivalencies.py::test_doppler_wavelength_circle[doppler_radio]", "astropy/units/tests/test_equivalencies.py::test_doppler_wavelength_circle[doppler_relativistic]", "astropy/units/tests/test_equivalencies.py::test_doppler_energy_circle[doppler_optical]", "astropy/units/tests/test_equivalencies.py::test_doppler_energy_circle[doppler_radio]", "astropy/units/tests/test_equivalencies.py::test_doppler_energy_circle[doppler_relativistic]", "astropy/units/tests/test_equivalencies.py::test_30kms[doppler_optical-999.899940784289]", "astropy/units/tests/test_equivalencies.py::test_30kms[doppler_radio-999.8999307714406]", "astropy/units/tests/test_equivalencies.py::test_30kms[doppler_relativistic-999.8999357778647]", "astropy/units/tests/test_equivalencies.py::test_bad_restfreqs[doppler_optical-5]", "astropy/units/tests/test_equivalencies.py::test_bad_restfreqs[doppler_radio-value1]", "astropy/units/tests/test_equivalencies.py::test_bad_restfreqs[doppler_relativistic-None]", "astropy/units/tests/test_equivalencies.py::test_doppler_redshift[0-rv_ans0]", "astropy/units/tests/test_equivalencies.py::test_doppler_redshift[0.001-rv_ans1]", "astropy/units/tests/test_equivalencies.py::test_doppler_redshift[-1-rv_ans2]", "astropy/units/tests/test_equivalencies.py::test_doppler_redshift_no_cosmology", "astropy/units/tests/test_equivalencies.py::test_massenergy", "astropy/units/tests/test_equivalencies.py::test_is_equivalent", "astropy/units/tests/test_equivalencies.py::test_parallax", "astropy/units/tests/test_equivalencies.py::test_parallax2", "astropy/units/tests/test_equivalencies.py::test_spectral", "astropy/units/tests/test_equivalencies.py::test_spectral2", "astropy/units/tests/test_equivalencies.py::test_spectral3", "astropy/units/tests/test_equivalencies.py::test_spectral4[in_val0-in_unit0]", "astropy/units/tests/test_equivalencies.py::test_spectral4[in_val1-in_unit1]", "astropy/units/tests/test_equivalencies.py::test_spectral4[in_val2-in_unit2]", "astropy/units/tests/test_equivalencies.py::test_spectral4[in_val3-in_unit3]", "astropy/units/tests/test_equivalencies.py::test_spectraldensity2[wav0]", "astropy/units/tests/test_equivalencies.py::test_spectraldensity2[wav1]", "astropy/units/tests/test_equivalencies.py::test_spectraldensity2[wav2]", "astropy/units/tests/test_equivalencies.py::test_spectraldensity2[wav3]", "astropy/units/tests/test_equivalencies.py::test_spectraldensity3", "astropy/units/tests/test_equivalencies.py::test_spectraldensity4", "astropy/units/tests/test_equivalencies.py::test_spectraldensity5", "astropy/units/tests/test_equivalencies.py::test_spectraldensity6", "astropy/units/tests/test_equivalencies.py::test_spectraldensity_not_allowed[from_unit0-to_unit0]", "astropy/units/tests/test_equivalencies.py::test_spectraldensity_not_allowed[from_unit1-to_unit1]", "astropy/units/tests/test_equivalencies.py::test_spectraldensity_not_allowed[from_unit2-to_unit2]", "astropy/units/tests/test_equivalencies.py::test_spectraldensity_not_allowed[from_unit3-to_unit3]", "astropy/units/tests/test_equivalencies.py::test_equivalent_units", "astropy/units/tests/test_equivalencies.py::test_equivalent_units2", "astropy/units/tests/test_equivalencies.py::test_trivial_equivalency", "astropy/units/tests/test_equivalencies.py::test_invalid_equivalency", "astropy/units/tests/test_equivalencies.py::test_irrelevant_equivalency", "astropy/units/tests/test_equivalencies.py::test_brightness_temperature", "astropy/units/tests/test_equivalencies.py::test_surfacebrightness", "astropy/units/tests/test_equivalencies.py::test_beam", "astropy/units/tests/test_equivalencies.py::test_thermodynamic_temperature", "astropy/units/tests/test_equivalencies.py::test_equivalency_context", "astropy/units/tests/test_equivalencies.py::test_equivalency_context_manager", "astropy/units/tests/test_equivalencies.py::test_temperature", "astropy/units/tests/test_equivalencies.py::test_temperature_energy", "astropy/units/tests/test_equivalencies.py::test_molar_mass_amu", "astropy/units/tests/test_equivalencies.py::test_compose_equivalencies", "astropy/units/tests/test_equivalencies.py::test_pixel_scale", "astropy/units/tests/test_equivalencies.py::test_pixel_scale_invalid_scale_unit", "astropy/units/tests/test_equivalencies.py::test_pixel_scale_acceptable_scale_unit", "astropy/units/tests/test_equivalencies.py::test_plate_scale", "astropy/units/tests/test_equivalencies.py::test_equivelency", "astropy/units/tests/test_equivalencies.py::test_add_equivelencies", "astropy/units/tests/test_equivalencies.py::test_pprint", "astropy/units/tests/test_equivalencies.py::test_spectral_density_factor_deprecation" ]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> Magnetic flux field equivalency <!-- These comments are hidden when you submit the pull request, so you do not need to remove them! --> <!-- Please be sure to check out our contributing guidelines, https://github.com/astropy/astropy/blob/main/CONTRIBUTING.md . Please be sure to check out our code of conduct, https://github.com/astropy/astropy/blob/main/CODE_OF_CONDUCT.md . --> <!-- If you are new or need to be re-acquainted with Astropy contributing workflow, please see http://docs.astropy.org/en/latest/development/workflow/development_workflow.html . There is even a practical example at https://docs.astropy.org/en/latest/development/workflow/git_edit_workflow_examples.html#astropy-fix-example . --> <!-- Please just have a quick search on GitHub to see if a similar pull request has already been posted. We have old closed pull requests that might provide useful code or ideas that directly tie in with your pull request. --> <!-- We have several automatic features that run when a pull request is open. They can appear daunting but do not worry because maintainers will help you navigate them, if necessary. --> ### Description <!-- Provide a general description of what your pull request does. Complete the following sentence and add relevant details as you see fit. --> <!-- In addition please ensure that the pull request title is descriptive and allows maintainers to infer the applicable subpackage(s). --> <!-- READ THIS FOR MANUAL BACKPORT FROM A MAINTAINER: Apply "skip-basebranch-check" label **before** you open the PR! --> Add functionality to Astropy to convert between two very common measures of magnetic field: magnetic flux density and magnetic field strength. The relation between these two quantities is straight forward in a vacuum: ```math \mathbf{B} = \mu_0 \mathbf{H} ``` References: https://www.e-magnetica.pl/doku.php/confusion_between_b_and_h (Summary of equations) <!-- If the pull request closes any open issues you can add this. If you replace <Issue Number> with a number, GitHub will automatically link it. If this pull request is unrelated to any issues, please remove the following line. --> Fixes #<Issue Number> <!-- Optional opt-out --> - [ ] By checking this box, the PR author has requested that maintainers do **NOT** use the "Squash and Merge" button. Maintainers should respect this when possible; however, the final decision is at the discretion of the maintainer that merges the PR. ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in astropy/units/equivalencies.py] (definition of magnetic_flux_field:) def magnetic_flux_field(mu_r=1): """Convert magnetic field between magnetic field strength :math:`(\mathbf{H})` and magnetic flux density :math:`(\mathbf{B})` using the relationship: .. math:: \mathbf{B} = \mu_r \mu_0 \mathbf{H} where: - :math:`\mu_0` is the vacuum permeability, a physical constant. - :math:`\mu_r` is the relative permeability of the medium, a dimensionless quantity. The default setting (:math:`\mu_r=1`) represents conditions in a vacuum. Parameters ---------- mu_r : float, optional The relative magnetic permeability of the medium. This is a dimensionless quantity and has a default value of :math:`\mu_r=1` which corresponds to free space (vacuum). Examples -------- >>> import astropy.units as u >>> H = 1 * u.Oe >>> H.to(u.G, equivalencies=u.magnetic_flux_field()) # doctest: +FLOAT_CMP <Quantity 1. G> >>> H.to(u.G, equivalencies=u.magnetic_flux_field(mu_r=0.8)) # doctest: +FLOAT_CMP <Quantity 0.8 G> >>> B = 1 * u.T >>> B.to(u.A / u.m, equivalencies=u.magnetic_flux_field()) # doctest: +FLOAT_CMP <Quantity 795774.71502628 A / m> >>> B.to(u.A / u.m, equivalencies=u.magnetic_flux_field(mu_r=0.8)) # doctest: +FLOAT_CMP <Quantity 994718.39378285 A / m>""" [end of new definitions in astropy/units/equivalencies.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
2d281019494aaebf522f6626c0dae37510c16688
scikit-learn__scikit-learn-29136
29,136
scikit-learn/scikit-learn
1.6
65c00c72507b48ae2f57ed2328560748db8b01f0
2024-05-30T10:01:41Z
diff --git a/doc/metadata_routing.rst b/doc/metadata_routing.rst index 27000a192ab21..d8a47927512e4 100644 --- a/doc/metadata_routing.rst +++ b/doc/metadata_routing.rst @@ -276,6 +276,7 @@ Meta-estimators and functions supporting metadata routing: - :class:`sklearn.calibration.CalibratedClassifierCV` - :class:`sklearn.compose.ColumnTransformer` +- :class:`sklearn.compose.TransformedTargetRegressor` - :class:`sklearn.covariance.GraphicalLassoCV` - :class:`sklearn.ensemble.StackingClassifier` - :class:`sklearn.ensemble.StackingRegressor` @@ -316,7 +317,6 @@ Meta-estimators and functions supporting metadata routing: Meta-estimators and tools not supporting metadata routing yet: -- :class:`sklearn.compose.TransformedTargetRegressor` - :class:`sklearn.ensemble.AdaBoostClassifier` - :class:`sklearn.ensemble.AdaBoostRegressor` - :class:`sklearn.feature_selection.RFE` diff --git a/doc/whats_new/v1.6.rst b/doc/whats_new/v1.6.rst index 3fd07fd51578e..adc2cd259085d 100644 --- a/doc/whats_new/v1.6.rst +++ b/doc/whats_new/v1.6.rst @@ -60,6 +60,11 @@ more details. ``**fit_params`` to the underlying estimators via their `fit` methods. :pr:`28701` by :user:`Stefanie Senger <StefanieSenger>`. +- |Feature| :class:`compose.TransformedTargetRegressor` now supports metadata + routing in its `fit` and `predict` methods and routes the corresponding + params to the underlying regressor. + :pr:`29136` by :user:`Omar Salman <OmarManzoor>`. + Dropping official support for PyPy ---------------------------------- diff --git a/sklearn/compose/_target.py b/sklearn/compose/_target.py index 3e6c94df8267a..4db174770e333 100644 --- a/sklearn/compose/_target.py +++ b/sklearn/compose/_target.py @@ -8,12 +8,18 @@ from ..base import BaseEstimator, RegressorMixin, _fit_context, clone from ..exceptions import NotFittedError +from ..linear_model import LinearRegression from ..preprocessing import FunctionTransformer -from ..utils import _safe_indexing, check_array +from ..utils import Bunch, _safe_indexing, check_array +from ..utils._metadata_requests import ( + MetadataRouter, + MethodMapping, + _routing_enabled, + process_routing, +) from ..utils._param_validation import HasMethods from ..utils._tags import _safe_tags from ..utils.metadata_routing import ( - _raise_for_unsupported_routing, _RoutingNotSupportedMixin, ) from ..utils.validation import check_is_fitted @@ -230,15 +236,25 @@ def fit(self, X, y, **fit_params): Target values. **fit_params : dict - Parameters passed to the `fit` method of the underlying - regressor. + - If `enable_metadata_routing=False` (default): + + Parameters directly passed to the `fit` method of the + underlying regressor. + + - If `enable_metadata_routing=True`: + + Parameters safely routed to the `fit` method of the + underlying regressor. + + .. versionchanged:: 1.6 + See :ref:`Metadata Routing User Guide <metadata_routing>` for + more details. Returns ------- self : object Fitted estimator. """ - _raise_for_unsupported_routing(self, "fit", **fit_params) if y is None: raise ValueError( f"This {self.__class__.__name__} estimator " @@ -274,14 +290,13 @@ def fit(self, X, y, **fit_params): if y_trans.ndim == 2 and y_trans.shape[1] == 1: y_trans = y_trans.squeeze(axis=1) - if self.regressor is None: - from ..linear_model import LinearRegression - - self.regressor_ = LinearRegression() + self.regressor_ = self._get_regressor(get_clone=True) + if _routing_enabled(): + routed_params = process_routing(self, "fit", **fit_params) else: - self.regressor_ = clone(self.regressor) + routed_params = Bunch(regressor=Bunch(fit=fit_params)) - self.regressor_.fit(X, y_trans, **fit_params) + self.regressor_.fit(X, y_trans, **routed_params.regressor.fit) if hasattr(self.regressor_, "feature_names_in_"): self.feature_names_in_ = self.regressor_.feature_names_in_ @@ -300,8 +315,19 @@ def predict(self, X, **predict_params): Samples. **predict_params : dict of str -> object - Parameters passed to the `predict` method of the underlying - regressor. + - If `enable_metadata_routing=False` (default): + + Parameters directly passed to the `predict` method of the + underlying regressor. + + - If `enable_metadata_routing=True`: + + Parameters safely routed to the `predict` method of the + underlying regressor. + + .. versionchanged:: 1.6 + See :ref:`Metadata Routing User Guide <metadata_routing>` + for more details. Returns ------- @@ -309,7 +335,12 @@ def predict(self, X, **predict_params): Predicted values. """ check_is_fitted(self) - pred = self.regressor_.predict(X, **predict_params) + if _routing_enabled(): + routed_params = process_routing(self, "predict", **predict_params) + else: + routed_params = Bunch(regressor=Bunch(predict=predict_params)) + + pred = self.regressor_.predict(X, **routed_params.regressor.predict) if pred.ndim == 1: pred_trans = self.transformer_.inverse_transform(pred.reshape(-1, 1)) else: @@ -324,11 +355,7 @@ def predict(self, X, **predict_params): return pred_trans def _more_tags(self): - regressor = self.regressor - if regressor is None: - from ..linear_model import LinearRegression - - regressor = LinearRegression() + regressor = self._get_regressor() return { "poor_score": True, @@ -350,3 +377,31 @@ def n_features_in_(self): ) from nfe return self.regressor_.n_features_in_ + + def get_metadata_routing(self): + """Get metadata routing of this object. + + Please check :ref:`User Guide <metadata_routing>` on how the routing + mechanism works. + + .. versionadded:: 1.6 + + Returns + ------- + routing : MetadataRouter + A :class:`~sklearn.utils.metadata_routing.MetadataRouter` encapsulating + routing information. + """ + router = MetadataRouter(owner=self.__class__.__name__).add( + regressor=self._get_regressor(), + method_mapping=MethodMapping() + .add(caller="fit", callee="fit") + .add(caller="predict", callee="predict"), + ) + return router + + def _get_regressor(self, get_clone=False): + if self.regressor is None: + return LinearRegression() + + return clone(self.regressor) if get_clone else self.regressor
diff --git a/sklearn/tests/test_metaestimators_metadata_routing.py b/sklearn/tests/test_metaestimators_metadata_routing.py index 8bfb7b0663c18..a1cc807bd2a7e 100644 --- a/sklearn/tests/test_metaestimators_metadata_routing.py +++ b/sklearn/tests/test_metaestimators_metadata_routing.py @@ -382,6 +382,14 @@ def enable_slep006(): "cv_name": "cv", "cv_routing_methods": ["fit"], }, + { + "metaestimator": TransformedTargetRegressor, + "estimator": "regressor", + "estimator_name": "regressor", + "X": X, + "y": y, + "estimator_routing_methods": ["fit", "predict"], + }, ] """List containing all metaestimators to be tested and their settings @@ -427,7 +435,6 @@ def enable_slep006(): RFECV(ConsumingClassifier()), SelfTrainingClassifier(ConsumingClassifier()), SequentialFeatureSelector(ConsumingClassifier()), - TransformedTargetRegressor(), ]
diff --git a/doc/metadata_routing.rst b/doc/metadata_routing.rst index 27000a192ab21..d8a47927512e4 100644 --- a/doc/metadata_routing.rst +++ b/doc/metadata_routing.rst @@ -276,6 +276,7 @@ Meta-estimators and functions supporting metadata routing: - :class:`sklearn.calibration.CalibratedClassifierCV` - :class:`sklearn.compose.ColumnTransformer` +- :class:`sklearn.compose.TransformedTargetRegressor` - :class:`sklearn.covariance.GraphicalLassoCV` - :class:`sklearn.ensemble.StackingClassifier` - :class:`sklearn.ensemble.StackingRegressor` @@ -316,7 +317,6 @@ Meta-estimators and functions supporting metadata routing: Meta-estimators and tools not supporting metadata routing yet: -- :class:`sklearn.compose.TransformedTargetRegressor` - :class:`sklearn.ensemble.AdaBoostClassifier` - :class:`sklearn.ensemble.AdaBoostRegressor` - :class:`sklearn.feature_selection.RFE` diff --git a/doc/whats_new/v1.6.rst b/doc/whats_new/v1.6.rst index 3fd07fd51578e..adc2cd259085d 100644 --- a/doc/whats_new/v1.6.rst +++ b/doc/whats_new/v1.6.rst @@ -60,6 +60,11 @@ more details. ``**fit_params`` to the underlying estimators via their `fit` methods. :pr:`28701` by :user:`Stefanie Senger <StefanieSenger>`. +- |Feature| :class:`compose.TransformedTargetRegressor` now supports metadata + routing in its `fit` and `predict` methods and routes the corresponding + params to the underlying regressor. + :pr:`29136` by :user:`Omar Salman <OmarManzoor>`. + Dropping official support for PyPy ----------------------------------
[ { "components": [ { "doc": "Get metadata routing of this object.\n\nPlease check :ref:`User Guide <metadata_routing>` on how the routing\nmechanism works.\n\n.. versionadded:: 1.6\n\nReturns\n-------\nrouting : MetadataRouter\n A :class:`~sklearn.utils.metadata_routing.MetadataRouter` encapsulating\n routing information.", "lines": [ 381, 401 ], "name": "TransformedTargetRegressor.get_metadata_routing", "signature": "def get_metadata_routing(self):", "type": "function" }, { "doc": "", "lines": [ 403, 407 ], "name": "TransformedTargetRegressor._get_regressor", "signature": "def _get_regressor(self, get_clone=False):", "type": "function" } ], "file": "sklearn/compose/_target.py" } ]
[ "sklearn/tests/test_metaestimators_metadata_routing.py::test_default_request[TransformedTargetRegressor]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_error_on_missing_requests_for_sub_estimator[TransformedTargetRegressor]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_setting_request_on_sub_estimator_removes_error[TransformedTargetRegressor]" ]
[ "sklearn/tests/test_metaestimators_metadata_routing.py::test_unsupported_estimators_get_metadata_routing[estimator0]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_unsupported_estimators_get_metadata_routing[estimator1]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_unsupported_estimators_get_metadata_routing[estimator2]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_unsupported_estimators_get_metadata_routing[estimator3]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_unsupported_estimators_get_metadata_routing[estimator4]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_unsupported_estimators_get_metadata_routing[estimator5]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_unsupported_estimators_fit_with_metadata[estimator0]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_unsupported_estimators_fit_with_metadata[estimator1]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_unsupported_estimators_fit_with_metadata[estimator2]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_unsupported_estimators_fit_with_metadata[estimator3]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_unsupported_estimators_fit_with_metadata[estimator4]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_unsupported_estimators_fit_with_metadata[estimator5]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_registry_copy", "sklearn/tests/test_metaestimators_metadata_routing.py::test_default_request[MultiOutputRegressor]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_default_request[MultiOutputClassifier]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_default_request[CalibratedClassifierCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_default_request[ClassifierChain]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_default_request[RegressorChain]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_default_request[LogisticRegressionCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_default_request[GridSearchCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_default_request[RandomizedSearchCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_default_request[HalvingGridSearchCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_default_request[HalvingRandomSearchCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_default_request[FixedThresholdClassifier]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_default_request[TunedThresholdClassifierCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_default_request[OneVsRestClassifier]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_default_request[OneVsOneClassifier]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_default_request[OutputCodeClassifier]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_default_request[SelectFromModel]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_default_request[OrthogonalMatchingPursuitCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_default_request[ElasticNetCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_default_request[LassoCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_default_request[MultiTaskElasticNetCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_default_request[MultiTaskLassoCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_default_request[LarsCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_default_request[LassoLarsCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_default_request[RANSACRegressor]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_default_request[IterativeImputer]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_default_request[BaggingClassifier]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_default_request[BaggingRegressor]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_default_request[RidgeCV0]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_default_request[RidgeClassifierCV0]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_default_request[RidgeCV1]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_default_request[RidgeClassifierCV1]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_default_request[GraphicalLassoCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_error_on_missing_requests_for_sub_estimator[MultiOutputRegressor]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_error_on_missing_requests_for_sub_estimator[MultiOutputClassifier]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_error_on_missing_requests_for_sub_estimator[CalibratedClassifierCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_error_on_missing_requests_for_sub_estimator[ClassifierChain]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_error_on_missing_requests_for_sub_estimator[RegressorChain]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_error_on_missing_requests_for_sub_estimator[LogisticRegressionCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_error_on_missing_requests_for_sub_estimator[GridSearchCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_error_on_missing_requests_for_sub_estimator[RandomizedSearchCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_error_on_missing_requests_for_sub_estimator[HalvingGridSearchCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_error_on_missing_requests_for_sub_estimator[HalvingRandomSearchCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_error_on_missing_requests_for_sub_estimator[FixedThresholdClassifier]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_error_on_missing_requests_for_sub_estimator[TunedThresholdClassifierCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_error_on_missing_requests_for_sub_estimator[OneVsRestClassifier]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_error_on_missing_requests_for_sub_estimator[OneVsOneClassifier]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_error_on_missing_requests_for_sub_estimator[OutputCodeClassifier]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_error_on_missing_requests_for_sub_estimator[SelectFromModel]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_error_on_missing_requests_for_sub_estimator[OrthogonalMatchingPursuitCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_error_on_missing_requests_for_sub_estimator[ElasticNetCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_error_on_missing_requests_for_sub_estimator[LassoCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_error_on_missing_requests_for_sub_estimator[MultiTaskElasticNetCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_error_on_missing_requests_for_sub_estimator[MultiTaskLassoCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_error_on_missing_requests_for_sub_estimator[LarsCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_error_on_missing_requests_for_sub_estimator[LassoLarsCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_error_on_missing_requests_for_sub_estimator[RANSACRegressor]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_error_on_missing_requests_for_sub_estimator[IterativeImputer]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_error_on_missing_requests_for_sub_estimator[BaggingClassifier]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_error_on_missing_requests_for_sub_estimator[BaggingRegressor]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_error_on_missing_requests_for_sub_estimator[RidgeCV0]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_error_on_missing_requests_for_sub_estimator[RidgeClassifierCV0]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_error_on_missing_requests_for_sub_estimator[RidgeCV1]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_error_on_missing_requests_for_sub_estimator[RidgeClassifierCV1]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_error_on_missing_requests_for_sub_estimator[GraphicalLassoCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_setting_request_on_sub_estimator_removes_error[MultiOutputRegressor]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_setting_request_on_sub_estimator_removes_error[MultiOutputClassifier]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_setting_request_on_sub_estimator_removes_error[CalibratedClassifierCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_setting_request_on_sub_estimator_removes_error[ClassifierChain]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_setting_request_on_sub_estimator_removes_error[RegressorChain]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_setting_request_on_sub_estimator_removes_error[LogisticRegressionCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_setting_request_on_sub_estimator_removes_error[GridSearchCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_setting_request_on_sub_estimator_removes_error[RandomizedSearchCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_setting_request_on_sub_estimator_removes_error[HalvingGridSearchCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_setting_request_on_sub_estimator_removes_error[HalvingRandomSearchCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_setting_request_on_sub_estimator_removes_error[FixedThresholdClassifier]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_setting_request_on_sub_estimator_removes_error[TunedThresholdClassifierCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_setting_request_on_sub_estimator_removes_error[OneVsRestClassifier]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_setting_request_on_sub_estimator_removes_error[OneVsOneClassifier]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_setting_request_on_sub_estimator_removes_error[OutputCodeClassifier]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_setting_request_on_sub_estimator_removes_error[SelectFromModel]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_setting_request_on_sub_estimator_removes_error[OrthogonalMatchingPursuitCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_setting_request_on_sub_estimator_removes_error[ElasticNetCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_setting_request_on_sub_estimator_removes_error[LassoCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_setting_request_on_sub_estimator_removes_error[MultiTaskElasticNetCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_setting_request_on_sub_estimator_removes_error[MultiTaskLassoCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_setting_request_on_sub_estimator_removes_error[LarsCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_setting_request_on_sub_estimator_removes_error[LassoLarsCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_setting_request_on_sub_estimator_removes_error[RANSACRegressor]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_setting_request_on_sub_estimator_removes_error[IterativeImputer]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_setting_request_on_sub_estimator_removes_error[BaggingClassifier]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_setting_request_on_sub_estimator_removes_error[BaggingRegressor]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_setting_request_on_sub_estimator_removes_error[RidgeCV0]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_setting_request_on_sub_estimator_removes_error[RidgeClassifierCV0]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_setting_request_on_sub_estimator_removes_error[RidgeCV1]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_setting_request_on_sub_estimator_removes_error[RidgeClassifierCV1]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_setting_request_on_sub_estimator_removes_error[GraphicalLassoCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_non_consuming_estimator_works[MultiOutputRegressor]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_non_consuming_estimator_works[MultiOutputClassifier]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_non_consuming_estimator_works[CalibratedClassifierCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_non_consuming_estimator_works[ClassifierChain]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_non_consuming_estimator_works[RegressorChain]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_non_consuming_estimator_works[LogisticRegressionCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_non_consuming_estimator_works[GridSearchCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_non_consuming_estimator_works[RandomizedSearchCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_non_consuming_estimator_works[HalvingGridSearchCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_non_consuming_estimator_works[HalvingRandomSearchCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_non_consuming_estimator_works[FixedThresholdClassifier]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_non_consuming_estimator_works[TunedThresholdClassifierCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_non_consuming_estimator_works[OneVsRestClassifier]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_non_consuming_estimator_works[OneVsOneClassifier]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_non_consuming_estimator_works[OutputCodeClassifier]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_non_consuming_estimator_works[SelectFromModel]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_non_consuming_estimator_works[OrthogonalMatchingPursuitCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_non_consuming_estimator_works[ElasticNetCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_non_consuming_estimator_works[LassoCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_non_consuming_estimator_works[MultiTaskElasticNetCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_non_consuming_estimator_works[MultiTaskLassoCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_non_consuming_estimator_works[LarsCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_non_consuming_estimator_works[LassoLarsCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_non_consuming_estimator_works[RANSACRegressor]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_non_consuming_estimator_works[IterativeImputer]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_non_consuming_estimator_works[BaggingClassifier]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_non_consuming_estimator_works[BaggingRegressor]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_non_consuming_estimator_works[RidgeCV0]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_non_consuming_estimator_works[RidgeClassifierCV0]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_non_consuming_estimator_works[RidgeCV1]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_non_consuming_estimator_works[RidgeClassifierCV1]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_non_consuming_estimator_works[GraphicalLassoCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_non_consuming_estimator_works[TransformedTargetRegressor]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_metadata_is_routed_correctly_to_scorer[MultiOutputRegressor]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_metadata_is_routed_correctly_to_scorer[MultiOutputClassifier]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_metadata_is_routed_correctly_to_scorer[CalibratedClassifierCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_metadata_is_routed_correctly_to_scorer[ClassifierChain]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_metadata_is_routed_correctly_to_scorer[RegressorChain]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_metadata_is_routed_correctly_to_scorer[LogisticRegressionCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_metadata_is_routed_correctly_to_scorer[GridSearchCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_metadata_is_routed_correctly_to_scorer[RandomizedSearchCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_metadata_is_routed_correctly_to_scorer[HalvingGridSearchCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_metadata_is_routed_correctly_to_scorer[HalvingRandomSearchCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_metadata_is_routed_correctly_to_scorer[FixedThresholdClassifier]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_metadata_is_routed_correctly_to_scorer[TunedThresholdClassifierCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_metadata_is_routed_correctly_to_scorer[OneVsRestClassifier]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_metadata_is_routed_correctly_to_scorer[OneVsOneClassifier]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_metadata_is_routed_correctly_to_scorer[OutputCodeClassifier]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_metadata_is_routed_correctly_to_scorer[SelectFromModel]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_metadata_is_routed_correctly_to_scorer[OrthogonalMatchingPursuitCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_metadata_is_routed_correctly_to_scorer[ElasticNetCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_metadata_is_routed_correctly_to_scorer[LassoCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_metadata_is_routed_correctly_to_scorer[MultiTaskElasticNetCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_metadata_is_routed_correctly_to_scorer[MultiTaskLassoCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_metadata_is_routed_correctly_to_scorer[LarsCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_metadata_is_routed_correctly_to_scorer[LassoLarsCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_metadata_is_routed_correctly_to_scorer[RANSACRegressor]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_metadata_is_routed_correctly_to_scorer[IterativeImputer]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_metadata_is_routed_correctly_to_scorer[BaggingClassifier]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_metadata_is_routed_correctly_to_scorer[BaggingRegressor]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_metadata_is_routed_correctly_to_scorer[RidgeCV0]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_metadata_is_routed_correctly_to_scorer[RidgeClassifierCV0]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_metadata_is_routed_correctly_to_scorer[RidgeCV1]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_metadata_is_routed_correctly_to_scorer[RidgeClassifierCV1]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_metadata_is_routed_correctly_to_scorer[GraphicalLassoCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_metadata_is_routed_correctly_to_scorer[TransformedTargetRegressor]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_metadata_is_routed_correctly_to_splitter[MultiOutputRegressor]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_metadata_is_routed_correctly_to_splitter[MultiOutputClassifier]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_metadata_is_routed_correctly_to_splitter[CalibratedClassifierCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_metadata_is_routed_correctly_to_splitter[ClassifierChain]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_metadata_is_routed_correctly_to_splitter[RegressorChain]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_metadata_is_routed_correctly_to_splitter[LogisticRegressionCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_metadata_is_routed_correctly_to_splitter[GridSearchCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_metadata_is_routed_correctly_to_splitter[RandomizedSearchCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_metadata_is_routed_correctly_to_splitter[HalvingGridSearchCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_metadata_is_routed_correctly_to_splitter[HalvingRandomSearchCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_metadata_is_routed_correctly_to_splitter[FixedThresholdClassifier]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_metadata_is_routed_correctly_to_splitter[TunedThresholdClassifierCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_metadata_is_routed_correctly_to_splitter[OneVsRestClassifier]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_metadata_is_routed_correctly_to_splitter[OneVsOneClassifier]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_metadata_is_routed_correctly_to_splitter[OutputCodeClassifier]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_metadata_is_routed_correctly_to_splitter[SelectFromModel]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_metadata_is_routed_correctly_to_splitter[OrthogonalMatchingPursuitCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_metadata_is_routed_correctly_to_splitter[ElasticNetCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_metadata_is_routed_correctly_to_splitter[LassoCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_metadata_is_routed_correctly_to_splitter[MultiTaskElasticNetCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_metadata_is_routed_correctly_to_splitter[MultiTaskLassoCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_metadata_is_routed_correctly_to_splitter[LarsCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_metadata_is_routed_correctly_to_splitter[LassoLarsCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_metadata_is_routed_correctly_to_splitter[RANSACRegressor]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_metadata_is_routed_correctly_to_splitter[IterativeImputer]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_metadata_is_routed_correctly_to_splitter[BaggingClassifier]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_metadata_is_routed_correctly_to_splitter[BaggingRegressor]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_metadata_is_routed_correctly_to_splitter[RidgeCV0]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_metadata_is_routed_correctly_to_splitter[RidgeClassifierCV0]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_metadata_is_routed_correctly_to_splitter[RidgeCV1]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_metadata_is_routed_correctly_to_splitter[RidgeClassifierCV1]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_metadata_is_routed_correctly_to_splitter[GraphicalLassoCV]", "sklearn/tests/test_metaestimators_metadata_routing.py::test_metadata_is_routed_correctly_to_splitter[TransformedTargetRegressor]" ]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> FEA Add metadata routing for TransformedTargetRegressor <!-- Thanks for contributing a pull request! Please ensure you have taken a look at the contribution guidelines: https://github.com/scikit-learn/scikit-learn/blob/main/CONTRIBUTING.md --> #### Reference Issues/PRs <!-- Example: Fixes #1234. See also #3456. Please use keywords (e.g., Fixes) to create link to the issues or pull requests you resolved, so that they will automatically be closed when your pull request is merged. See https://github.com/blog/1506-closing-issues-via-pull-requests --> Towards #22893 #### What does this implement/fix? Explain your changes. - Adds metadata routing to TransformedTargetRegressor #### Any other comments? CC: @adrinjalali <!-- Please be aware that we are a loose team of volunteers so patience is necessary; assistance handling other issues is very welcome. We value all user contributions, no matter how minor they are. If we are slow to review, either the pull request needs some benchmarking, tinkering, convincing, etc. or more likely the reviewers are simply busy. In either case, we ask for your understanding during the review process. For more information, see our FAQ on this topic: https://scikit-learn.org/dev/faq.html#why-is-my-pull-request-not-getting-any-attention. Thanks for contributing! --> ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in sklearn/compose/_target.py] (definition of TransformedTargetRegressor.get_metadata_routing:) def get_metadata_routing(self): """Get metadata routing of this object. Please check :ref:`User Guide <metadata_routing>` on how the routing mechanism works. .. versionadded:: 1.6 Returns ------- routing : MetadataRouter A :class:`~sklearn.utils.metadata_routing.MetadataRouter` encapsulating routing information.""" (definition of TransformedTargetRegressor._get_regressor:) def _get_regressor(self, get_clone=False): [end of new definitions in sklearn/compose/_target.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
18dc8630a7cbe1b591c12774949058b12157a39a
tobymao__sqlglot-3560
3,560
tobymao/sqlglot
null
eae3c5165c16b61c7b524a55776bdb1127005c7d
2024-05-28T17:15:28Z
diff --git a/sqlglot/schema.py b/sqlglot/schema.py index cb3fd00b24..50646c868e 100644 --- a/sqlglot/schema.py +++ b/sqlglot/schema.py @@ -155,13 +155,16 @@ def table_parts(self, table: exp.Table) -> t.List[str]: return [table.this.name] return [table.text(part) for part in exp.TABLE_PARTS if table.text(part)] - def find(self, table: exp.Table, raise_on_missing: bool = True) -> t.Optional[t.Any]: + def find( + self, table: exp.Table, raise_on_missing: bool = True, ensure_data_types: bool = False + ) -> t.Optional[t.Any]: """ Returns the schema of a given table. Args: table: the target table. raise_on_missing: whether to raise in case the schema is not found. + ensure_data_types: whether to convert `str` types to their `DataType` equivalents. Returns: The schema of the target table. @@ -239,6 +242,20 @@ def from_mapping_schema(cls, mapping_schema: MappingSchema) -> MappingSchema: normalize=mapping_schema.normalize, ) + def find( + self, table: exp.Table, raise_on_missing: bool = True, ensure_data_types: bool = False + ) -> t.Optional[t.Any]: + schema = super().find( + table, raise_on_missing=raise_on_missing, ensure_data_types=ensure_data_types + ) + if ensure_data_types and isinstance(schema, dict) and dict_depth(schema) == 1: + schema = { + col: self._to_data_type(dtype) if isinstance(dtype, str) else dtype + for col, dtype in schema.items() + } + + return schema + def copy(self, **kwargs) -> MappingSchema: return MappingSchema( **{ # type: ignore
diff --git a/tests/test_schema.py b/tests/test_schema.py index 5b5086738d..21b59fd3e5 100644 --- a/tests/test_schema.py +++ b/tests/test_schema.py @@ -303,3 +303,10 @@ def test_has_column(self): schema = MappingSchema({"x": {"c": "int"}}) self.assertTrue(schema.has_column("x", exp.column("c"))) self.assertFalse(schema.has_column("x", exp.column("k"))) + + def test_find(self): + schema = MappingSchema({"x": {"c": "int"}}) + found = schema.find(exp.to_table("x")) + self.assertEqual(found, {"c": "int"}) + found = schema.find(exp.to_table("x"), ensure_data_types=True) + self.assertEqual(found, {"c": exp.DataType.build("int")})
[ { "components": [ { "doc": "", "lines": [ 245, 257 ], "name": "MappingSchema.find", "signature": "def find( self, table: exp.Table, raise_on_missing: bool = True, ensure_data_types: bool = False ) -> t.Optional[t.Any]:", "type": "function" } ], "file": "sqlglot/schema.py" } ]
[ "tests/test_schema.py::TestSchema::test_find" ]
[ "tests/test_schema.py::TestSchema::test_has_column", "tests/test_schema.py::TestSchema::test_same_number_of_qualifiers", "tests/test_schema.py::TestSchema::test_schema", "tests/test_schema.py::TestSchema::test_schema_add_table_with_and_without_mapping", "tests/test_schema.py::TestSchema::test_schema_catalog", "tests/test_schema.py::TestSchema::test_schema_db", "tests/test_schema.py::TestSchema::test_schema_get_column_type", "tests/test_schema.py::TestSchema::test_schema_normalization" ]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> Feat: add option in schema's find method to ensure types are DataTypes The motivation behind this is that in SQLMesh we have a mapping schema where types are stored as strings, but [we need them](https://github.com/TobikoData/sqlmesh/blob/main/sqlmesh/core/macros.py#L405-L420) to be `DataType`s instead. I added this here instead of in SQLMesh to leverage the existing in-memory `DataType` cache [used](https://github.com/tobymao/sqlglot/blob/main/sqlglot/schema.py#L447-L448) in the `MappingSchema` definition. ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in sqlglot/schema.py] (definition of MappingSchema.find:) def find( self, table: exp.Table, raise_on_missing: bool = True, ensure_data_types: bool = False ) -> t.Optional[t.Any]: [end of new definitions in sqlglot/schema.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
ceb42fabad60312699e4b15936aeebac00e22e4d
roboflow__supervision-1237
1,237
roboflow/supervision
null
9bc2907c4907714da5b469fdfee7800f4cf9f09e
2024-05-28T07:42:20Z
diff --git a/supervision/detection/core.py b/supervision/detection/core.py index be6104820..f93aed1c4 100644 --- a/supervision/detection/core.py +++ b/supervision/detection/core.py @@ -23,7 +23,7 @@ xywh_to_xyxy, ) from supervision.geometry.core import Position -from supervision.utils.internal import deprecated +from supervision.utils.internal import deprecated, get_instance_variables from supervision.validators import validate_detections_fields @@ -1379,7 +1379,7 @@ def validate_fields_both_defined_or_none( Raises: ValueError: If one field is None and the other is not, for any of the fields. """ - attributes = ["mask", "confidence", "class_id", "tracker_id"] + attributes = get_instance_variables(detections_1) for attribute in attributes: value_1 = getattr(detections_1, attribute) value_2 = getattr(detections_2, attribute) diff --git a/supervision/utils/internal.py b/supervision/utils/internal.py index 978a14485..072c03b79 100644 --- a/supervision/utils/internal.py +++ b/supervision/utils/internal.py @@ -1,7 +1,8 @@ import functools +import inspect import os import warnings -from typing import Callable +from typing import Any, Callable, Set class SupervisionWarnings(Warning): @@ -141,3 +142,42 @@ def __get__(self, owner_self: object, owner_cls: type) -> object: The result of calling the function stored in 'fget' with 'owner_cls'. """ return self.fget(owner_cls) + + +def get_instance_variables(instance: Any, include_properties=False) -> Set[str]: + """ + Get the public variables of a class instance. + + Args: + instance (Any): The instance of a class + include_properties (bool): Whether to include properties in the result + + Usage: + ```python + detections = Detections(xyxy=np.array([1,2,3,4])) + variables = get_class_variables(detections) + # ["xyxy", "mask", "confidence", ..., "data"] + ``` + """ + if isinstance(instance, type): + raise ValueError("Only class instances are supported, not classes.") + + fields = set( + ( + name + for name, val in inspect.getmembers(instance) + if not callable(val) and not name.startswith("_") + ) + ) + + if not include_properties: + properties = set( + ( + name + for name, val in inspect.getmembers(instance.__class__) + if isinstance(val, property) + ) + ) + fields -= properties + + return fields
diff --git a/test/utils/test_internal.py b/test/utils/test_internal.py new file mode 100644 index 000000000..eee614e6c --- /dev/null +++ b/test/utils/test_internal.py @@ -0,0 +1,193 @@ +from contextlib import ExitStack as DoesNotRaise +from dataclasses import dataclass, field +from typing import Any, Set + +import numpy as np +import pytest + +from supervision.detection.core import Detections +from supervision.utils.internal import get_instance_variables + + +class MockClass: + def __init__(self): + self.public = 0 + self._protected = 1 + self.__private = 2 + + def public_method(self): + pass + + def _protected_method(self): + pass + + def __private_method(self): + pass + + @property + def public_property(self): + return 0 + + @property + def _protected_property(self): + return 1 + + @property + def __private_property(self): + return 2 + + +@dataclass +class MockDataclass: + public: int = 0 + _protected: int = 1 + __private: int = 2 + + public_field: int = field(default=0) + _protected_field: int = field(default=1) + __private_field: int = field(default=2) + + public_field_with_factory: dict = field(default_factory=dict) + _protected_field_with_factory: dict = field(default_factory=dict) + __private_field_with_factory: dict = field(default_factory=dict) + + def public_method(self): + pass + + def _protected_method(self): + pass + + def __private_method(self): + pass + + @property + def public_property(self): + return 0 + + @property + def _protected_property(self): + return 1 + + @property + def __private_property(self): + return 2 + + +@pytest.mark.parametrize( + "input_instance, include_properties, expected, exception", + [ + ( + MockClass, + False, + None, + pytest.raises(ValueError), + ), + ( + MockClass(), + False, + {"public"}, + DoesNotRaise(), + ), + ( + MockClass(), + True, + {"public", "public_property"}, + DoesNotRaise(), + ), + ( + MockDataclass(), + False, + {"public", "public_field", "public_field_with_factory"}, + DoesNotRaise(), + ), + ( + MockDataclass(), + True, + {"public", "public_field", "public_field_with_factory", "public_property"}, + DoesNotRaise(), + ), + ( + Detections, + False, + None, + pytest.raises(ValueError), + ), + ( + Detections, + True, + None, + pytest.raises(ValueError), + ), + ( + Detections.empty(), + False, + {"xyxy", "class_id", "confidence", "mask", "tracker_id", "data"}, + DoesNotRaise(), + ), + ( + Detections.empty(), + True, + { + "xyxy", + "class_id", + "confidence", + "mask", + "tracker_id", + "data", + "area", + "box_area", + }, + DoesNotRaise(), + ), + ( + Detections(xyxy=np.array([[1, 2, 3, 4]])), + False, + { + "xyxy", + "class_id", + "confidence", + "mask", + "tracker_id", + "data", + }, + DoesNotRaise(), + ), + ( + Detections( + xyxy=np.array([[1, 2, 3, 4], [5, 6, 7, 8]]), + class_id=np.array([1, 2]), + confidence=np.array([0.1, 0.2]), + mask=np.array([[[1]], [[2]]]), + tracker_id=np.array([1, 2]), + data={"key_1": [1, 2], "key_2": [3, 4]}, + ), + False, + { + "xyxy", + "class_id", + "confidence", + "mask", + "tracker_id", + "data", + }, + DoesNotRaise(), + ), + ( + Detections.empty(), + False, + {"xyxy", "class_id", "confidence", "mask", "tracker_id", "data"}, + DoesNotRaise(), + ), + ], +) +def test_get_instance_variables( + input_instance: Any, + include_properties: bool, + expected: Set[str], + exception: Exception, +) -> None: + with exception: + result = get_instance_variables( + input_instance, include_properties=include_properties + ) + assert result == expected
[ { "components": [ { "doc": "Get the public variables of a class instance.\n\nArgs:\n instance (Any): The instance of a class\n include_properties (bool): Whether to include properties in the result\n\nUsage:\n ```python\n detections = Detections(xyxy=np.array([1,2,3,4]))\n variables = get_class_variables(detections)\n # [\"xyxy\", \"mask\", \"confidence\", ..., \"data\"]\n ```", "lines": [ 147, 183 ], "name": "get_instance_variables", "signature": "def get_instance_variables(instance: Any, include_properties=False) -> Set[str]:", "type": "function" } ], "file": "supervision/utils/internal.py" } ]
[ "test/utils/test_internal.py::test_get_instance_variables[MockClass-False-None-exception0]", "test/utils/test_internal.py::test_get_instance_variables[input_instance1-False-expected1-exception1]", "test/utils/test_internal.py::test_get_instance_variables[input_instance2-True-expected2-exception2]", "test/utils/test_internal.py::test_get_instance_variables[input_instance3-False-expected3-exception3]", "test/utils/test_internal.py::test_get_instance_variables[input_instance4-True-expected4-exception4]", "test/utils/test_internal.py::test_get_instance_variables[Detections-False-None-exception5]", "test/utils/test_internal.py::test_get_instance_variables[Detections-True-None-exception6]", "test/utils/test_internal.py::test_get_instance_variables[input_instance7-False-expected7-exception7]", "test/utils/test_internal.py::test_get_instance_variables[input_instance8-True-expected8-exception8]", "test/utils/test_internal.py::test_get_instance_variables[input_instance9-False-expected9-exception9]", "test/utils/test_internal.py::test_get_instance_variables[input_instance10-False-expected10-exception10]", "test/utils/test_internal.py::test_get_instance_variables[input_instance11-False-expected11-exception11]" ]
[]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> Dynamically select Detections member variables # Description When checking if both fields are `None` or defined in two detection to be merged, we'd hardcode the fields. This change allows getting the programmatically. Note that it requires an instance of the class. ## Type of change Please delete options that are not relevant. - [ ] Bug fix (non-breaking change which fixes an issue) - [x] New feature (non-breaking change which adds functionality) - [ ] This change requires a documentation update ## How has this change been tested, please provide a testcase or example of how you tested the change? Ran locally, added and ran very basic tests. Colab: https://colab.research.google.com/drive/193L8OHsEsdhQEenDNwKbGdtPyE68cUbW?usp=sharing ## Any specific deployment considerations None ## Docs - [ ] Docs updated? What were the changes: ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in supervision/utils/internal.py] (definition of get_instance_variables:) def get_instance_variables(instance: Any, include_properties=False) -> Set[str]: """Get the public variables of a class instance. Args: instance (Any): The instance of a class include_properties (bool): Whether to include properties in the result Usage: ```python detections = Detections(xyxy=np.array([1,2,3,4])) variables = get_class_variables(detections) # ["xyxy", "mask", "confidence", ..., "data"] ```""" [end of new definitions in supervision/utils/internal.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
3eb5c0b024e3e46877b7fe4fd66e6177d1308ba0
conan-io__conan-16231
16,231
conan-io/conan
null
80fee05d5811608511bbb30a965afd66bdc13311
2024-05-09T12:29:23Z
diff --git a/conan/tools/cmake/cmakedeps/templates/__init__.py b/conan/tools/cmake/cmakedeps/templates/__init__.py index 64e90955bf1..f1cd8ba1b49 100644 --- a/conan/tools/cmake/cmakedeps/templates/__init__.py +++ b/conan/tools/cmake/cmakedeps/templates/__init__.py @@ -24,6 +24,12 @@ def root_target_name(self): def file_name(self): return self.cmakedeps.get_cmake_package_name(self.conanfile, module_mode=self.generating_module) + self.suffix + @property + def additional_variables_prefixes(self): + prefix_list = ( + self.cmakedeps.get_property("cmake_additional_variables_prefixes", self.conanfile) or []) + return list(set([self.file_name] + prefix_list)) + @property def suffix(self): if not self.require.build: diff --git a/conan/tools/cmake/cmakedeps/templates/config.py b/conan/tools/cmake/cmakedeps/templates/config.py index ea01844579a..a4df8a399cc 100644 --- a/conan/tools/cmake/cmakedeps/templates/config.py +++ b/conan/tools/cmake/cmakedeps/templates/config.py @@ -28,7 +28,8 @@ def context(self): targets_include += "{}Targets.cmake".format(self.file_name) return {"is_module": self.generating_module, "version": self.conanfile.ref.version, - "file_name": self.file_name, + "file_name": self.file_name, + "additional_variables_prefixes": self.additional_variables_prefixes, "pkg_name": self.pkg_name, "config_suffix": self.config_suffix, "check_components_exist": self.cmakedeps.check_components_exist, @@ -67,11 +68,14 @@ def template(self): endif() endforeach() - set({{ file_name }}_VERSION_STRING "{{ version }}") - set({{ file_name }}_INCLUDE_DIRS {{ pkg_var(pkg_name, 'INCLUDE_DIRS', config_suffix) }} ) - set({{ file_name }}_INCLUDE_DIR {{ pkg_var(pkg_name, 'INCLUDE_DIRS', config_suffix) }} ) - set({{ file_name }}_LIBRARIES {{ pkg_var(pkg_name, 'LIBRARIES', config_suffix) }} ) - set({{ file_name }}_DEFINITIONS {{ pkg_var(pkg_name, 'DEFINITIONS', config_suffix) }} ) + {% for prefix in additional_variables_prefixes %} + set({{ prefix }}_VERSION_STRING "{{ version }}") + set({{ prefix }}_INCLUDE_DIRS {{ pkg_var(pkg_name, 'INCLUDE_DIRS', config_suffix) }} ) + set({{ prefix }}_INCLUDE_DIR {{ pkg_var(pkg_name, 'INCLUDE_DIRS', config_suffix) }} ) + set({{ prefix }}_LIBRARIES {{ pkg_var(pkg_name, 'LIBRARIES', config_suffix) }} ) + set({{ prefix }}_DEFINITIONS {{ pkg_var(pkg_name, 'DEFINITIONS', config_suffix) }} ) + + {% endfor %} # Only the first installed configuration is included to avoid the collision foreach(_BUILD_MODULE {{ pkg_var(pkg_name, 'BUILD_MODULES_PATHS', config_suffix) }} )
diff --git a/conans/test/integration/toolchains/cmake/cmakedeps/test_cmakedeps.py b/conans/test/integration/toolchains/cmake/cmakedeps/test_cmakedeps.py index f8a7eddf5b1..53dee803222 100644 --- a/conans/test/integration/toolchains/cmake/cmakedeps/test_cmakedeps.py +++ b/conans/test/integration/toolchains/cmake/cmakedeps/test_cmakedeps.py @@ -707,3 +707,38 @@ def generate(self): assert 'set(dep_NO_SONAME_MODE_RELEASE TRUE)' in dep other = c.load("app/other-release-data.cmake") assert 'set(other_other_mycomp1_NO_SONAME_MODE_RELEASE TRUE)' in other + +def test_cmakedeps_set_legacy_variable_name(): + client = TestClient() + base_conanfile = str(GenConanfile("dep", "1.0")) + conanfile = base_conanfile + """ + def package_info(self): + self.cpp_info.set_property("cmake_file_name", "CMakeFileName") + """ + client.save({"dep/conanfile.py": conanfile}) + client.run("create dep") + client.run("install --requires=dep/1.0 -g CMakeDeps") + + # Check that all the CMake variables are generated with the file_name + dep_config = client.load("CMakeFileNameConfig.cmake") + cmake_variables = ["VERSION_STRING", "INCLUDE_DIRS", "INCLUDE_DIR", "LIBRARIES", "DEFINITIONS"] + for variable in cmake_variables: + assert f"CMakeFileName_{variable}" in dep_config + + conanfile = base_conanfile + """ + def package_info(self): + self.cpp_info.set_property("cmake_file_name", "NewCMakeFileName") + self.cpp_info.set_property("cmake_additional_variables_prefixes", ["PREFIX", "prefix", "PREFIX"]) + """ + client.save({"dep/conanfile.py": conanfile}) + client.run("create dep") + client.run("install --requires=dep/1.0 -g CMakeDeps") + + # Check that all the CMake variables are generated with the file_name and both prefixes + dep_config = client.load("NewCMakeFileNameConfig.cmake") + for variable in cmake_variables: + assert f"NewCMakeFileName_{variable}" in dep_config + assert f"PREFIX_{variable}" in dep_config + assert f"prefix_{variable}" in dep_config + # Check that variables are not duplicated + assert dep_config.count("PREFIX_VERSION") == 1
[ { "components": [ { "doc": "", "lines": [ 28, 31 ], "name": "CMakeDepsFileTemplate.additional_variables_prefixes", "signature": "def additional_variables_prefixes(self):", "type": "function" } ], "file": "conan/tools/cmake/cmakedeps/templates/__init__.py" } ]
[ "conans/test/integration/toolchains/cmake/cmakedeps/test_cmakedeps.py::test_cmakedeps_set_legacy_variable_name" ]
[ "conans/test/integration/toolchains/cmake/cmakedeps/test_cmakedeps.py::test_package_from_system", "conans/test/integration/toolchains/cmake/cmakedeps/test_cmakedeps.py::test_test_package", "conans/test/integration/toolchains/cmake/cmakedeps/test_cmakedeps.py::test_components_error", "conans/test/integration/toolchains/cmake/cmakedeps/test_cmakedeps.py::test_cpp_info_component_objects", "conans/test/integration/toolchains/cmake/cmakedeps/test_cmakedeps.py::test_cpp_info_component_error_aggregate", "conans/test/integration/toolchains/cmake/cmakedeps/test_cmakedeps.py::test_cmakedeps_cppinfo_complex_strings", "conans/test/integration/toolchains/cmake/cmakedeps/test_cmakedeps.py::test_dependency_props_from_consumer", "conans/test/integration/toolchains/cmake/cmakedeps/test_cmakedeps.py::test_props_from_consumer_build_context_activated", "conans/test/integration/toolchains/cmake/cmakedeps/test_cmakedeps.py::test_skip_transitive_components", "conans/test/integration/toolchains/cmake/cmakedeps/test_cmakedeps.py::test_error_missing_config_build_context", "conans/test/integration/toolchains/cmake/cmakedeps/test_cmakedeps.py::test_using_package_module", "conans/test/integration/toolchains/cmake/cmakedeps/test_cmakedeps.py::test_system_libs_transitivity", "conans/test/integration/toolchains/cmake/cmakedeps/test_cmakedeps.py::TestCMakeVersionConfigCompat::test_cmake_version_config_compatibility", "conans/test/integration/toolchains/cmake/cmakedeps/test_cmakedeps.py::TestCMakeVersionConfigCompat::test_cmake_version_config_compatibility_error", "conans/test/integration/toolchains/cmake/cmakedeps/test_cmakedeps.py::TestCMakeVersionConfigCompat::test_cmake_version_config_compatibility_consumer", "conans/test/integration/toolchains/cmake/cmakedeps/test_cmakedeps.py::TestSystemPackageVersion::test_component_version", "conans/test/integration/toolchains/cmake/cmakedeps/test_cmakedeps.py::TestSystemPackageVersion::test_component_version_consumer", "conans/test/integration/toolchains/cmake/cmakedeps/test_cmakedeps.py::test_cmakedeps_set_property_overrides" ]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> Add property to change the CMake variable names generated with CMakeDeps Changelog: Feature: Add `cmake_additional_variables_prefixes` variable to CMakeDeps generator to allow adding extra names for declared CMake variables. Docs: https://github.com/conan-io/docs/pull/3721 Created new property for CMakeDeps generator: `cmake_legacy_variable_prefix` that can be set in `package_info()` of the conanfile. It allows changing the prefix used when creating CMake variables instead of the package name that was currently being used. Closes: https://github.com/conan-io/conan/issues/14788 - [x] Refer to the issue that supports this Pull Request. - [x] If the issue has missing info, explain the purpose/use case/pain/need that covers this Pull Request. - [x] I've read the [Contributing guide](https://github.com/conan-io/conan/blob/develop2/.github/CONTRIBUTING.md). - [x] I've followed the PEP8 style guides for Python code. - [x] I've opened another PR in the Conan docs repo to the ``develop`` branch, documenting this one. ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in conan/tools/cmake/cmakedeps/templates/__init__.py] (definition of CMakeDepsFileTemplate.additional_variables_prefixes:) def additional_variables_prefixes(self): [end of new definitions in conan/tools/cmake/cmakedeps/templates/__init__.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
4a5b19a75db9225316c8cb022a2dfb9705a2af34
scikit-learn__scikit-learn-28936
28,936
scikit-learn/scikit-learn
1.6
0f27a26d0f78b07245158f5997066a3b2c1d76ba
2024-05-02T20:19:03Z
diff --git a/doc/api_reference.py b/doc/api_reference.py index 1aa6455fb7e44..583909cdcac65 100644 --- a/doc/api_reference.py +++ b/doc/api_reference.py @@ -121,6 +121,7 @@ def _get_submodule(module_name, submodule_name): "TransformerMixin", "clone", "is_classifier", + "is_clusterer", "is_regressor", ], } diff --git a/doc/whats_new/v1.6.rst b/doc/whats_new/v1.6.rst index 0e6844155c6fa..53b0eb017fc57 100644 --- a/doc/whats_new/v1.6.rst +++ b/doc/whats_new/v1.6.rst @@ -74,6 +74,13 @@ Changelog :pr:`123456` by :user:`Joe Bloggs <joeongithub>`. where 123455 is the *pull request* number, not the issue number. +:mod:`sklearn.base` +................... + +- |Enhancement| Added a function :func:`base.is_clusterer` which determines + whether a given estimator is of category clusterer. + :pr:`28936` by :user:`Christian Veenhuis <ChVeen>`. + Thanks to everyone who has contributed to the maintenance and improvement of the project since version 1.5, including: diff --git a/sklearn/base.py b/sklearn/base.py index 0aa7af1041368..d4245ade4e499 100644 --- a/sklearn/base.py +++ b/sklearn/base.py @@ -1374,13 +1374,17 @@ def is_classifier(estimator): Examples -------- >>> from sklearn.base import is_classifier + >>> from sklearn.cluster import KMeans >>> from sklearn.svm import SVC, SVR >>> classifier = SVC() >>> regressor = SVR() + >>> kmeans = KMeans() >>> is_classifier(classifier) True >>> is_classifier(regressor) False + >>> is_classifier(kmeans) + False """ return getattr(estimator, "_estimator_type", None) == "classifier" @@ -1401,17 +1405,54 @@ def is_regressor(estimator): Examples -------- >>> from sklearn.base import is_regressor + >>> from sklearn.cluster import KMeans >>> from sklearn.svm import SVC, SVR >>> classifier = SVC() >>> regressor = SVR() + >>> kmeans = KMeans() >>> is_regressor(classifier) False >>> is_regressor(regressor) True + >>> is_regressor(kmeans) + False """ return getattr(estimator, "_estimator_type", None) == "regressor" +def is_clusterer(estimator): + """Return True if the given estimator is (probably) a clusterer. + + .. versionadded:: 1.6 + + Parameters + ---------- + estimator : object + Estimator object to test. + + Returns + ------- + out : bool + True if estimator is a clusterer and False otherwise. + + Examples + -------- + >>> from sklearn.base import is_clusterer + >>> from sklearn.cluster import KMeans + >>> from sklearn.svm import SVC, SVR + >>> classifier = SVC() + >>> regressor = SVR() + >>> kmeans = KMeans() + >>> is_clusterer(classifier) + False + >>> is_clusterer(regressor) + False + >>> is_clusterer(kmeans) + True + """ + return getattr(estimator, "_estimator_type", None) == "clusterer" + + def is_outlier_detector(estimator): """Return True if the given estimator is (probably) an outlier detector.
diff --git a/sklearn/tests/test_base.py b/sklearn/tests/test_base.py index a1cd3b8fc8c7b..917da863ece3b 100644 --- a/sklearn/tests/test_base.py +++ b/sklearn/tests/test_base.py @@ -18,13 +18,16 @@ TransformerMixin, clone, is_classifier, + is_clusterer, + is_regressor, ) +from sklearn.cluster import KMeans from sklearn.decomposition import PCA from sklearn.exceptions import InconsistentVersionWarning from sklearn.model_selection import GridSearchCV from sklearn.pipeline import Pipeline from sklearn.preprocessing import StandardScaler -from sklearn.svm import SVC +from sklearn.svm import SVC, SVR from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor from sklearn.utils._mocking import MockDataFrame from sklearn.utils._set_output import _get_output_config @@ -259,12 +262,55 @@ def test_get_params(): test.set_params(a__a=2) -def test_is_classifier(): - svc = SVC() - assert is_classifier(svc) - assert is_classifier(GridSearchCV(svc, {"C": [0.1, 1]})) - assert is_classifier(Pipeline([("svc", svc)])) - assert is_classifier(Pipeline([("svc_cv", GridSearchCV(svc, {"C": [0.1, 1]}))])) +@pytest.mark.parametrize( + "estimator, expected_result", + [ + (SVC(), True), + (GridSearchCV(SVC(), {"C": [0.1, 1]}), True), + (Pipeline([("svc", SVC())]), True), + (Pipeline([("svc_cv", GridSearchCV(SVC(), {"C": [0.1, 1]}))]), True), + (SVR(), False), + (GridSearchCV(SVR(), {"C": [0.1, 1]}), False), + (Pipeline([("svr", SVR())]), False), + (Pipeline([("svr_cv", GridSearchCV(SVR(), {"C": [0.1, 1]}))]), False), + ], +) +def test_is_classifier(estimator, expected_result): + assert is_classifier(estimator) == expected_result + + +@pytest.mark.parametrize( + "estimator, expected_result", + [ + (SVR(), True), + (GridSearchCV(SVR(), {"C": [0.1, 1]}), True), + (Pipeline([("svr", SVR())]), True), + (Pipeline([("svr_cv", GridSearchCV(SVR(), {"C": [0.1, 1]}))]), True), + (SVC(), False), + (GridSearchCV(SVC(), {"C": [0.1, 1]}), False), + (Pipeline([("svc", SVC())]), False), + (Pipeline([("svc_cv", GridSearchCV(SVC(), {"C": [0.1, 1]}))]), False), + ], +) +def test_is_regressor(estimator, expected_result): + assert is_regressor(estimator) == expected_result + + +@pytest.mark.parametrize( + "estimator, expected_result", + [ + (KMeans(), True), + (GridSearchCV(KMeans(), {"n_clusters": [3, 8]}), True), + (Pipeline([("km", KMeans())]), True), + (Pipeline([("km_cv", GridSearchCV(KMeans(), {"n_clusters": [3, 8]}))]), True), + (SVC(), False), + (GridSearchCV(SVC(), {"C": [0.1, 1]}), False), + (Pipeline([("svc", SVC())]), False), + (Pipeline([("svc_cv", GridSearchCV(SVC(), {"C": [0.1, 1]}))]), False), + ], +) +def test_is_clusterer(estimator, expected_result): + assert is_clusterer(estimator) == expected_result def test_set_params():
diff --git a/doc/whats_new/v1.6.rst b/doc/whats_new/v1.6.rst index 0e6844155c6fa..53b0eb017fc57 100644 --- a/doc/whats_new/v1.6.rst +++ b/doc/whats_new/v1.6.rst @@ -74,6 +74,13 @@ Changelog :pr:`123456` by :user:`Joe Bloggs <joeongithub>`. where 123455 is the *pull request* number, not the issue number. +:mod:`sklearn.base` +................... + +- |Enhancement| Added a function :func:`base.is_clusterer` which determines + whether a given estimator is of category clusterer. + :pr:`28936` by :user:`Christian Veenhuis <ChVeen>`. + Thanks to everyone who has contributed to the maintenance and improvement of the project since version 1.5, including:
[ { "components": [ { "doc": "Return True if the given estimator is (probably) a clusterer.\n\n.. versionadded:: 1.6\n\nParameters\n----------\nestimator : object\n Estimator object to test.\n\nReturns\n-------\nout : bool\n True if estimator is a clusterer and False otherwise.\n\nExamples\n--------\n>>> from sklearn.base import is_clusterer\n>>> from sklearn.cluster import KMeans\n>>> from sklearn.svm import SVC, SVR\n>>> classifier = SVC()\n>>> regressor = SVR()\n>>> kmeans = KMeans()\n>>> is_clusterer(classifier)\nFalse\n>>> is_clusterer(regressor)\nFalse\n>>> is_clusterer(kmeans)\nTrue", "lines": [ 1423, 1453 ], "name": "is_clusterer", "signature": "def is_clusterer(estimator):", "type": "function" } ], "file": "sklearn/base.py" } ]
[ "sklearn/tests/test_base.py::test_clone", "sklearn/tests/test_base.py::test_clone_2", "sklearn/tests/test_base.py::test_clone_buggy", "sklearn/tests/test_base.py::test_clone_empty_array", "sklearn/tests/test_base.py::test_clone_nan", "sklearn/tests/test_base.py::test_clone_dict", "sklearn/tests/test_base.py::test_clone_sparse_matrices", "sklearn/tests/test_base.py::test_clone_estimator_types", "sklearn/tests/test_base.py::test_clone_class_rather_than_instance", "sklearn/tests/test_base.py::test_repr", "sklearn/tests/test_base.py::test_str", "sklearn/tests/test_base.py::test_get_params", "sklearn/tests/test_base.py::test_is_classifier[estimator0-True]", "sklearn/tests/test_base.py::test_is_classifier[estimator1-True]", "sklearn/tests/test_base.py::test_is_classifier[estimator2-True]", "sklearn/tests/test_base.py::test_is_classifier[estimator3-True]", "sklearn/tests/test_base.py::test_is_classifier[estimator4-False]", "sklearn/tests/test_base.py::test_is_classifier[estimator5-False]", "sklearn/tests/test_base.py::test_is_classifier[estimator6-False]", "sklearn/tests/test_base.py::test_is_classifier[estimator7-False]", "sklearn/tests/test_base.py::test_is_regressor[estimator0-True]", "sklearn/tests/test_base.py::test_is_regressor[estimator1-True]", "sklearn/tests/test_base.py::test_is_regressor[estimator2-True]", "sklearn/tests/test_base.py::test_is_regressor[estimator3-True]", "sklearn/tests/test_base.py::test_is_regressor[estimator4-False]", "sklearn/tests/test_base.py::test_is_regressor[estimator5-False]", "sklearn/tests/test_base.py::test_is_regressor[estimator6-False]", "sklearn/tests/test_base.py::test_is_regressor[estimator7-False]", "sklearn/tests/test_base.py::test_is_clusterer[estimator0-True]", "sklearn/tests/test_base.py::test_is_clusterer[estimator1-True]", "sklearn/tests/test_base.py::test_is_clusterer[estimator2-True]", "sklearn/tests/test_base.py::test_is_clusterer[estimator3-True]", "sklearn/tests/test_base.py::test_is_clusterer[estimator4-False]", "sklearn/tests/test_base.py::test_is_clusterer[estimator5-False]", "sklearn/tests/test_base.py::test_is_clusterer[estimator6-False]", "sklearn/tests/test_base.py::test_is_clusterer[estimator7-False]", "sklearn/tests/test_base.py::test_set_params", "sklearn/tests/test_base.py::test_set_params_passes_all_parameters", "sklearn/tests/test_base.py::test_set_params_updates_valid_params", "sklearn/tests/test_base.py::test_score_sample_weight[tree0-dataset0]", "sklearn/tests/test_base.py::test_score_sample_weight[tree1-dataset1]", "sklearn/tests/test_base.py::test_clone_pandas_dataframe", "sklearn/tests/test_base.py::test_clone_protocol", "sklearn/tests/test_base.py::test_pickle_version_warning_is_not_raised_with_matching_version", "sklearn/tests/test_base.py::test_pickle_version_warning_is_issued_upon_different_version", "sklearn/tests/test_base.py::test_pickle_version_warning_is_issued_when_no_version_info_in_pickle", "sklearn/tests/test_base.py::test_pickle_version_no_warning_is_issued_with_non_sklearn_estimator", "sklearn/tests/test_base.py::test_pickling_when_getstate_is_overwritten_by_mixin", "sklearn/tests/test_base.py::test_pickling_when_getstate_is_overwritten_by_mixin_outside_of_sklearn", "sklearn/tests/test_base.py::test_pickling_works_when_getstate_is_overwritten_in_the_child_class", "sklearn/tests/test_base.py::test_tag_inheritance", "sklearn/tests/test_base.py::test_raises_on_get_params_non_attribute", "sklearn/tests/test_base.py::test_repr_mimebundle_", "sklearn/tests/test_base.py::test_repr_html_wraps", "sklearn/tests/test_base.py::test_n_features_in_validation", "sklearn/tests/test_base.py::test_n_features_in_no_validation", "sklearn/tests/test_base.py::test_feature_names_in", "sklearn/tests/test_base.py::test_validate_data_cast_to_ndarray", "sklearn/tests/test_base.py::test_clone_keeps_output_config", "sklearn/tests/test_base.py::test_estimator_empty_instance_dict[estimator0]", "sklearn/tests/test_base.py::test_estimator_empty_instance_dict[estimator1]", "sklearn/tests/test_base.py::test_estimator_getstate_using_slots_error_message", "sklearn/tests/test_base.py::test_dataframe_protocol[dataframe-1.5.0]", "sklearn/tests/test_base.py::test_transformer_fit_transform_with_metadata_in_transform", "sklearn/tests/test_base.py::test_outlier_mixin_fit_predict_with_metadata_in_predict" ]
[]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> ENH Add missing `base.is_clusterer()` function #### Reference Issues/PRs Fixes https://github.com/scikit-learn/scikit-learn/issues/28960 #### What does this implement/fix? Explain your changes. This PR proposes to add the missing `base.is_clusterer()` function analogously to `base.is_classifier()`. There is a user demand for this as can be seen in discussion <https://github.com/scikit-learn/scikit-learn/discussions/28904>. The missing unit test for `base.is_regressor()` is added as well. #### Any other comments? ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in sklearn/base.py] (definition of is_clusterer:) def is_clusterer(estimator): """Return True if the given estimator is (probably) a clusterer. .. versionadded:: 1.6 Parameters ---------- estimator : object Estimator object to test. Returns ------- out : bool True if estimator is a clusterer and False otherwise. Examples -------- >>> from sklearn.base import is_clusterer >>> from sklearn.cluster import KMeans >>> from sklearn.svm import SVC, SVR >>> classifier = SVC() >>> regressor = SVR() >>> kmeans = KMeans() >>> is_clusterer(classifier) False >>> is_clusterer(regressor) False >>> is_clusterer(kmeans) True""" [end of new definitions in sklearn/base.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
18dc8630a7cbe1b591c12774949058b12157a39a
pgmpy__pgmpy-1753
1,753
pgmpy/pgmpy
null
7ed0659107c9b3768208d17890a28778001320e9
2024-04-30T06:51:14Z
diff --git a/pgmpy/utils/__init__.py b/pgmpy/utils/__init__.py index 7803135af..adf8bb667 100644 --- a/pgmpy/utils/__init__.py +++ b/pgmpy/utils/__init__.py @@ -1,9 +1,8 @@ -from .mathext import cartesian, sample_discrete -from .state_name import StateNameMixin from .check_functions import _check_1d_array_object, _check_length_equal +from .mathext import cartesian, sample_discrete from .optimizer import optimize, pinverse -from .utils import get_example_model - +from .state_name import StateNameMixin +from .utils import discretize, get_example_model __all__ = [ "cartesian", @@ -14,4 +13,5 @@ "optimize", "pinverse", "get_example_model", + "discretize", ] diff --git a/pgmpy/utils/utils.py b/pgmpy/utils/utils.py index 7d53e1927..35b465a8c 100644 --- a/pgmpy/utils/utils.py +++ b/pgmpy/utils/utils.py @@ -1,5 +1,7 @@ import gzip +import pandas as pd + try: from importlib.resources import files except: @@ -112,3 +114,64 @@ def get_example_model(model): content = f.read() reader = BIFReader(string=content.decode("utf-8"), n_jobs=1) return reader.get_model() + + +def discretize(data, cardinality, labels=dict(), method="rounding"): + """ + Discretizes a given continuous dataset. + + Parameters + ---------- + data: pandas.DataFrame + The dataset to discretize. All columns must have continuous values. + + cardinality: dict + A dictionary of the form (str: int) representing the number of bins + to create for each of the variables. + + labels: dict (default: None) + A dictionary of the form (str: list) representing the label names for + each variable in the discretized dataframe. + + method: rounding or quantile + If rounding, equal width bins are created and data is discretized into these bins. Refer pandas.cut for more details. + If quantile, creates bins such that each bin has an equal number of datapoints. Refer pandas.qcut for more details. + + Examples + -------- + >>> import numpy as np + >>> from pgmpy.utils import discretize + >>> rng = np.random.default_rng(42) + >>> X = rng.standard_normal(1000) + >>> Y = 0.2 * X + rng.standard_normal(1000) + >>> Z = 0.4 * X + 0.5 * Y + rng.standard_normal(1000) + >>> df = pd.DataFrame({"X": X, "Y": Y, "Z": Z}) + >>> df_disc = discretize(df, cardinality={'X': 3, 'Y': 3, 'Z': 3}, labels={'X': ['low', 'mid', 'high'], 'Y': ['low', 'mid', 'high'], 'Z': ['low', 'mid', 'high']}) + >>> df_disc.head() + X Y Z + 0 mid mid mid + 1 mid mid low + 2 mid mid mid + 3 high mid mid + 4 low mid low + + Returns + ------- + pandas.DataFrame: A discretized dataframe. + """ + df_copy = data.copy() + if method == "rounding": + for column in data.columns: + df_copy[column] = pd.cut( + df_copy[column], + bins=cardinality[column], + include_lowest=True, + labels=labels.get(column), + ) + elif method == "quantile": + for column in data.columns: + df_copy[column] = pd.qcut( + df_copy[column], q=cardinality[column], labels=labels.get(column) + ) + + return df_copy
diff --git a/pgmpy/tests/test_utils/test_utils.py b/pgmpy/tests/test_utils/test_utils.py index 505d14de1..1ab6e78a0 100644 --- a/pgmpy/tests/test_utils/test_utils.py +++ b/pgmpy/tests/test_utils/test_utils.py @@ -1,9 +1,11 @@ -import unittest import random +import unittest +import numpy as np +import pandas as pd from tqdm.auto import tqdm -from pgmpy.utils import get_example_model +from pgmpy.utils import discretize, get_example_model class TestDAGCreation(unittest.TestCase): @@ -40,3 +42,28 @@ def test_get_example_model(self): for model in tqdm(choices): m = get_example_model(model=model) del m + + +class TestDiscretization(unittest.TestCase): + def setUp(self): + rng = np.random.default_rng(42) + X = rng.standard_normal(1000) + Y = 0.2 * X + rng.standard_normal(1000) + Z = 0.4 * X + 0.5 * Y + rng.standard_normal(1000) + + self.data = pd.DataFrame({"X": X, "Y": Y, "Z": Z}) + + def test_rounding_disc(self): + df_disc = discretize( + data=self.data, cardinality={"X": 5, "Y": 4, "Z": 3}, method="rounding" + ) + self.assertEqual(df_disc["X"].nunique(), 5) + self.assertEqual(df_disc["Y"].nunique(), 4) + self.assertEqual(df_disc["Z"].nunique(), 3) + + df_disc = discretize( + data=self.data, cardinality={"X": 5, "Y": 4, "Z": 3}, method="quantile" + ) + self.assertEqual(df_disc["X"].nunique(), 5) + self.assertEqual(df_disc["Y"].nunique(), 4) + self.assertEqual(df_disc["Z"].nunique(), 3)
[ { "components": [ { "doc": "Discretizes a given continuous dataset.\n\nParameters\n----------\ndata: pandas.DataFrame\n The dataset to discretize. All columns must have continuous values.\n\ncardinality: dict\n A dictionary of the form (str: int) representing the number of bins\n to create for each of the variables.\n\nlabels: dict (default: None)\n A dictionary of the form (str: list) representing the label names for\n each variable in the discretized dataframe.\n\nmethod: rounding or quantile\n If rounding, equal width bins are created and data is discretized into these bins. Refer pandas.cut for more details.\n If quantile, creates bins such that each bin has an equal number of datapoints. Refer pandas.qcut for more details.\n\nExamples\n--------\n>>> import numpy as np\n>>> from pgmpy.utils import discretize\n>>> rng = np.random.default_rng(42)\n>>> X = rng.standard_normal(1000)\n>>> Y = 0.2 * X + rng.standard_normal(1000)\n>>> Z = 0.4 * X + 0.5 * Y + rng.standard_normal(1000)\n>>> df = pd.DataFrame({\"X\": X, \"Y\": Y, \"Z\": Z})\n>>> df_disc = discretize(df, cardinality={'X': 3, 'Y': 3, 'Z': 3}, labels={'X': ['low', 'mid', 'high'], 'Y': ['low', 'mid', 'high'], 'Z': ['low', 'mid', 'high']})\n>>> df_disc.head()\n X Y Z\n0 mid mid mid\n1 mid mid low\n2 mid mid mid\n3 high mid mid\n4 low mid low\n\nReturns\n-------\npandas.DataFrame: A discretized dataframe.", "lines": [ 119, 177 ], "name": "discretize", "signature": "def discretize(data, cardinality, labels=dict(), method=\"rounding\"):", "type": "function" } ], "file": "pgmpy/utils/utils.py" } ]
[ "pgmpy/tests/test_utils/test_utils.py::TestDAGCreation::test_get_example_model", "pgmpy/tests/test_utils/test_utils.py::TestDiscretization::test_rounding_disc" ]
[]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> Adds a function for discretization ### Your checklist for this pull request Please review the [guidelines for contributing](CONTRIBUTING.md) to this repository. - [ ] Make sure you are requesting to **pull a topic/feature/bugfix branch** (right side). Don't request your master! - [ ] Make sure you are making a pull request against the **dev branch** (left side). Also you should start *your branch* off *our dev*. - [ ] Check the commit's or even all commits' message styles matches our requested structure. ### Issue number(s) that this pull request fixes - Ref #1752 ### List of changes to the codebase in this pull request - - - ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in pgmpy/utils/utils.py] (definition of discretize:) def discretize(data, cardinality, labels=dict(), method="rounding"): """Discretizes a given continuous dataset. Parameters ---------- data: pandas.DataFrame The dataset to discretize. All columns must have continuous values. cardinality: dict A dictionary of the form (str: int) representing the number of bins to create for each of the variables. labels: dict (default: None) A dictionary of the form (str: list) representing the label names for each variable in the discretized dataframe. method: rounding or quantile If rounding, equal width bins are created and data is discretized into these bins. Refer pandas.cut for more details. If quantile, creates bins such that each bin has an equal number of datapoints. Refer pandas.qcut for more details. Examples -------- >>> import numpy as np >>> from pgmpy.utils import discretize >>> rng = np.random.default_rng(42) >>> X = rng.standard_normal(1000) >>> Y = 0.2 * X + rng.standard_normal(1000) >>> Z = 0.4 * X + 0.5 * Y + rng.standard_normal(1000) >>> df = pd.DataFrame({"X": X, "Y": Y, "Z": Z}) >>> df_disc = discretize(df, cardinality={'X': 3, 'Y': 3, 'Z': 3}, labels={'X': ['low', 'mid', 'high'], 'Y': ['low', 'mid', 'high'], 'Z': ['low', 'mid', 'high']}) >>> df_disc.head() X Y Z 0 mid mid mid 1 mid mid low 2 mid mid mid 3 high mid mid 4 low mid low Returns ------- pandas.DataFrame: A discretized dataframe.""" [end of new definitions in pgmpy/utils/utils.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
cf8d0f12e2e5be62b01ff8fded85f3f64eab1e84
google-deepmind__optax-897
897
google-deepmind/optax
null
246f002a64e21bcc8f0b1a3390eb4ee13da83ed5
2024-04-01T20:30:36Z
diff --git a/docs/api/losses.rst b/docs/api/losses.rst index 95cef9f99..41ceab134 100644 --- a/docs/api/losses.rst +++ b/docs/api/losses.rst @@ -14,6 +14,7 @@ Losses kl_divergence l2_loss log_cosh + ntxent safe_softmax_cross_entropy sigmoid_binary_cross_entropy sigmoid_focal_loss @@ -61,6 +62,10 @@ Log hyperbolic cosine loss ~~~~~~~~~~~~~~~~~~~~~~~~~~ .. autofunction:: log_cosh +Normalized temperature scaled cross-entropy (NT-Xent) loss +~~~~~~~~~~~~~~~~ +.. autofunction:: ntxent + Sigmoid binary cross-entropy ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. autofunction:: sigmoid_binary_cross_entropy diff --git a/optax/__init__.py b/optax/__init__.py index 5edae96d1..4225d7ef2 100644 --- a/optax/__init__.py +++ b/optax/__init__.py @@ -203,6 +203,7 @@ kl_divergence = losses.kl_divergence l2_loss = losses.l2_loss log_cosh = losses.log_cosh +ntxent = losses.ntxent sigmoid_binary_cross_entropy = losses.sigmoid_binary_cross_entropy smooth_labels = losses.smooth_labels softmax_cross_entropy = losses.softmax_cross_entropy @@ -306,6 +307,7 @@ "MultiTransformState", "nadam", "nadamw", + "ntxent", "noisy_sgd", "novograd", "NonNegativeParamsState", diff --git a/optax/losses/__init__.py b/optax/losses/__init__.py index 8393dc310..65c171f24 100644 --- a/optax/losses/__init__.py +++ b/optax/losses/__init__.py @@ -35,3 +35,4 @@ from optax.losses._regression import log_cosh from optax.losses._regression import squared_error from optax.losses._smoothing import smooth_labels +from optax.losses._self_supervised import ntxent diff --git a/optax/losses/_self_supervised.py b/optax/losses/_self_supervised.py new file mode 100644 index 000000000..8c756a591 --- /dev/null +++ b/optax/losses/_self_supervised.py @@ -0,0 +1,86 @@ +# Copyright 2024 DeepMind Technologies Limited. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Self supervised losses.""" + +import chex +from jax import lax +import jax.numpy as jnp +from optax.losses._regression import cosine_similarity + + +def ntxent( + embeddings: chex.Array, + labels: chex.Array, + temperature: chex.Numeric = 0.07 +) -> chex.Numeric: + """Normalized temperature scaled cross entropy loss (NT-Xent). + + References: + T. Chen et al `A Simple Framework for Contrastive Learning of Visual + Representations <http://arxiv.org/abs/2002.05709>`_, 2020 + kevinmusgrave.github.io/pytorch-metric-learning/losses/#ntxentloss + + Args: + emeddings: batch of embeddings, with shape [batch, feature_length] + labels: labels for groups that are positive pairs. e.g. if you have + a batch of 4 embeddings and the first two and last two were positive + pairs your `labels` should look like [0, 0, 1, 1]. labels SHOULD NOT + be all the same (e.g. [0, 0, 0, 0]) you will get a NaN result. + Shape [batch] + temperature: temperature scaling parameter. + + Returns: + A scalar loss value of NT-Xent values averaged over all positive + pairs + + .. versionadded:: 0.2.3 + """ + chex.assert_type([embeddings], float) + if labels.shape[0] != embeddings.shape[0]: + raise ValueError( + 'label dimension should match batch dimension in embeddings' + ) + + # cosine similarity matrix + xcs = cosine_similarity( + embeddings[None, :, :], embeddings[:, None, :] + ) / temperature + + # finding positive and negative pairs + labels1 = jnp.expand_dims(labels, axis=1) + labels2 = jnp.expand_dims(labels, axis=0) + matches = labels1 == labels2 + diffs = matches ^ 1 + matches = jnp.bool_(matches - jnp.eye(matches.shape[0])) # no self cos + + # replace 0 with -inf + xcs_diffs = jnp.where(diffs == 1, xcs, -jnp.inf) + xcs_matches = jnp.where(matches == 1, xcs, -jnp.inf) + + # shifting for numeric stability + comb = jnp.concatenate((xcs_diffs, xcs_matches), axis=-1) + xcs_max = jnp.max(comb, axis=1, keepdims=True) + xcs_shift_diffs = xcs_diffs - lax.stop_gradient(xcs_max) + xcs_shift_matches = xcs_matches - lax.stop_gradient(xcs_max) + + # calc loss + numer = xcs_shift_matches + numer_exp = jnp.exp(xcs_shift_matches) + denom = jnp.sum(jnp.exp(xcs_shift_diffs), axis=1, keepdims=True) + denom += numer_exp + log_softm = numer - jnp.log(denom) + loss = -jnp.where(matches == 1, log_softm, 0.0).sum() / matches.sum() + + return loss
diff --git a/optax/losses/_classification_test.py b/optax/losses/_classification_test.py index b87d520ea..b75f3a088 100644 --- a/optax/losses/_classification_test.py +++ b/optax/losses/_classification_test.py @@ -862,6 +862,5 @@ def test_ignore_negative(self): assert all(ce_loss[self.ts == 0] > 0) assert all(focal_loss[self.ts == 0] == 0) - if __name__ == '__main__': absltest.main() diff --git a/optax/losses/_self_supervised_test.py b/optax/losses/_self_supervised_test.py new file mode 100644 index 000000000..43823f6a3 --- /dev/null +++ b/optax/losses/_self_supervised_test.py @@ -0,0 +1,51 @@ +# Copyright 2024 DeepMind Technologies Limited. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Tests for optax.losses._self_supervised.""" + +from absl.testing import parameterized + +import chex +import jax.numpy as jnp +import numpy as np + +from optax.losses import _self_supervised + + +class NtxentTest(parameterized.TestCase): + + def setUp(self): + super().setUp() + self.ys = jnp.array([ + [-1.9540, 1.0780], + [ 0.2380, -0.5703], + [ 1.8745, -0.0195], + [-0.6719, -1.9210], + ]) + self.ts_1 = jnp.array([0,0,1,1]) + self.ts_2 = jnp.array([0,0,0,1]) + # Calculated expected output + self.exp_1 = jnp.array(14.01032) + self.exp_2 = jnp.array(8.968544) + + @chex.all_variants + def test_batched(self): + """Tests for a full batch.""" + np.testing.assert_allclose( + self.variant(_self_supervised.ntxent)(self.ys, self.ts_1), + self.exp_1, atol=1e-4) + + np.testing.assert_allclose( + self.variant(_self_supervised.ntxent)(self.ys, self.ts_2), + self.exp_2, atol=1e-4)
diff --git a/docs/api/losses.rst b/docs/api/losses.rst index 95cef9f99..41ceab134 100644 --- a/docs/api/losses.rst +++ b/docs/api/losses.rst @@ -14,6 +14,7 @@ Losses kl_divergence l2_loss log_cosh + ntxent safe_softmax_cross_entropy sigmoid_binary_cross_entropy sigmoid_focal_loss @@ -61,6 +62,10 @@ Log hyperbolic cosine loss ~~~~~~~~~~~~~~~~~~~~~~~~~~ .. autofunction:: log_cosh +Normalized temperature scaled cross-entropy (NT-Xent) loss +~~~~~~~~~~~~~~~~ +.. autofunction:: ntxent + Sigmoid binary cross-entropy ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. autofunction:: sigmoid_binary_cross_entropy
[ { "components": [ { "doc": "Normalized temperature scaled cross entropy loss (NT-Xent).\n\nReferences:\n T. Chen et al `A Simple Framework for Contrastive Learning of Visual \n Representations <http://arxiv.org/abs/2002.05709>`_, 2020\n kevinmusgrave.github.io/pytorch-metric-learning/losses/#ntxentloss\n\nArgs:\n emeddings: batch of embeddings, with shape [batch, feature_length]\n labels: labels for groups that are positive pairs. e.g. if you have\n a batch of 4 embeddings and the first two and last two were positive\n pairs your `labels` should look like [0, 0, 1, 1]. labels SHOULD NOT\n be all the same (e.g. [0, 0, 0, 0]) you will get a NaN result. \n Shape [batch]\n temperature: temperature scaling parameter.\n\nReturns:\n A scalar loss value of NT-Xent values averaged over all positive\n pairs\n\n.. versionadded:: 0.2.3", "lines": [ 23, 86 ], "name": "ntxent", "signature": "def ntxent( embeddings: chex.Array, labels: chex.Array, temperature: chex.Numeric = 0.07 ) -> chex.Numeric:", "type": "function" } ], "file": "optax/losses/_self_supervised.py" } ]
[ "optax/losses/_classification_test.py::SoftmaxCrossEntropyTest::test_batched__with_device", "optax/losses/_classification_test.py::SoftmaxCrossEntropyTest::test_batched__with_jit", "optax/losses/_classification_test.py::SoftmaxCrossEntropyTest::test_batched__without_device", "optax/losses/_classification_test.py::SoftmaxCrossEntropyTest::test_batched__without_jit", "optax/losses/_classification_test.py::SoftmaxCrossEntropyTest::test_gradient", "optax/losses/_classification_test.py::SoftmaxCrossEntropyTest::test_scalar__with_device", "optax/losses/_classification_test.py::SoftmaxCrossEntropyTest::test_scalar__with_jit", "optax/losses/_classification_test.py::SoftmaxCrossEntropyTest::test_scalar__without_device", "optax/losses/_classification_test.py::SoftmaxCrossEntropyTest::test_scalar__without_jit", "optax/losses/_classification_test.py::SafeSoftmaxCrossEntropyTest::test_against_plain_implementation", "optax/losses/_classification_test.py::SafeSoftmaxCrossEntropyTest::test_batched__with_device", "optax/losses/_classification_test.py::SafeSoftmaxCrossEntropyTest::test_batched__with_jit", "optax/losses/_classification_test.py::SafeSoftmaxCrossEntropyTest::test_batched__without_device", "optax/losses/_classification_test.py::SafeSoftmaxCrossEntropyTest::test_batched__without_jit", "optax/losses/_classification_test.py::SafeSoftmaxCrossEntropyTest::test_gradient", "optax/losses/_classification_test.py::SafeSoftmaxCrossEntropyTest::test_scalar__with_device", "optax/losses/_classification_test.py::SafeSoftmaxCrossEntropyTest::test_scalar__with_jit", "optax/losses/_classification_test.py::SafeSoftmaxCrossEntropyTest::test_scalar__without_device", "optax/losses/_classification_test.py::SafeSoftmaxCrossEntropyTest::test_scalar__without_jit", "optax/losses/_classification_test.py::SoftmaxCrossEntropyWithIntegerLabelsTest::test_consistent_with_softmax_cross_entropy_batched__with_device", "optax/losses/_classification_test.py::SoftmaxCrossEntropyWithIntegerLabelsTest::test_consistent_with_softmax_cross_entropy_batched__with_jit", "optax/losses/_classification_test.py::SoftmaxCrossEntropyWithIntegerLabelsTest::test_consistent_with_softmax_cross_entropy_batched__without_device", "optax/losses/_classification_test.py::SoftmaxCrossEntropyWithIntegerLabelsTest::test_consistent_with_softmax_cross_entropy_batched__without_jit", "optax/losses/_classification_test.py::SoftmaxCrossEntropyWithIntegerLabelsTest::test_consistent_with_softmax_cross_entropy_scalar__with_device", "optax/losses/_classification_test.py::SoftmaxCrossEntropyWithIntegerLabelsTest::test_consistent_with_softmax_cross_entropy_scalar__with_jit", "optax/losses/_classification_test.py::SoftmaxCrossEntropyWithIntegerLabelsTest::test_consistent_with_softmax_cross_entropy_scalar__without_device", "optax/losses/_classification_test.py::SoftmaxCrossEntropyWithIntegerLabelsTest::test_consistent_with_softmax_cross_entropy_scalar__without_jit", "optax/losses/_classification_test.py::SoftmaxCrossEntropyWithIntegerLabelsTest::test_gradient", "optax/losses/_classification_test.py::SigmoidCrossEntropyTest::testSigmoidCrossEntropy0", "optax/losses/_classification_test.py::SigmoidCrossEntropyTest::testSigmoidCrossEntropy1", "optax/losses/_classification_test.py::SigmoidCrossEntropyTest::testSigmoidCrossEntropy2", "optax/losses/_classification_test.py::SigmoidCrossEntropyTest::testSigmoidCrossEntropy3", "optax/losses/_classification_test.py::SigmoidCrossEntropyTest::testSigmoidCrossEntropy4", "optax/losses/_classification_test.py::SigmoidCrossEntropyTest::testSigmoidCrossEntropy5", "optax/losses/_classification_test.py::SigmoidCrossEntropyTest::testSigmoidCrossEntropy6", "optax/losses/_classification_test.py::SigmoidCrossEntropyTest::testSigmoidCrossEntropy7", "optax/losses/_classification_test.py::SigmoidCrossEntropyTest::testSigmoidCrossEntropy8", "optax/losses/_classification_test.py::SigmoidCrossEntropyTest::testSigmoidCrossEntropy9", "optax/losses/_classification_test.py::PolyLossTest::test_batched_(eps=-0.5,", "optax/losses/_classification_test.py::PolyLossTest::test_batched_(eps=0,", "optax/losses/_classification_test.py::PolyLossTest::test_batched_(eps=1,", "optax/losses/_classification_test.py::PolyLossTest::test_batched_(eps=1.15,", "optax/losses/_classification_test.py::PolyLossTest::test_batched_(eps=1.214,", "optax/losses/_classification_test.py::PolyLossTest::test_batched_(eps=2,", "optax/losses/_classification_test.py::PolyLossTest::test_batched_(eps=5.45,", "optax/losses/_classification_test.py::PolyLossTest::test_equals_to_cross_entropy_when_eps0_(logits=array([0.314]),", "optax/losses/_classification_test.py::PolyLossTest::test_equals_to_cross_entropy_when_eps0_(logits=array([1.89,", "optax/losses/_classification_test.py::PolyLossTest::test_equals_to_cross_entropy_when_eps0_(logits=array([[4.", "optax/losses/_classification_test.py::PolyLossTest::test_equals_to_cross_entropy_when_eps0_(logits=array([[4.,", "optax/losses/_classification_test.py::PolyLossTest::test_scalar_(eps=-0.5,", "optax/losses/_classification_test.py::PolyLossTest::test_scalar_(eps=-1,", "optax/losses/_classification_test.py::PolyLossTest::test_scalar_(eps=0,", "optax/losses/_classification_test.py::PolyLossTest::test_scalar_(eps=1,", "optax/losses/_classification_test.py::PolyLossTest::test_scalar_(eps=1.15,", "optax/losses/_classification_test.py::PolyLossTest::test_scalar_(eps=1.214,", "optax/losses/_classification_test.py::PolyLossTest::test_scalar_(eps=2,", "optax/losses/_classification_test.py::PolyLossTest::test_scalar_(eps=5.45,", "optax/losses/_classification_test.py::HingeTest::test_batched_binary", "optax/losses/_classification_test.py::HingeTest::test_batched_multi_class", "optax/losses/_classification_test.py::HingeTest::test_binary", "optax/losses/_classification_test.py::HingeTest::test_multi_class", "optax/losses/_classification_test.py::SparsemaxTest::test_batched_binary", "optax/losses/_classification_test.py::SparsemaxTest::test_binary", "optax/losses/_classification_test.py::ConvexKLDivergenceTest::test_batched__with_device", "optax/losses/_classification_test.py::ConvexKLDivergenceTest::test_batched__with_jit", "optax/losses/_classification_test.py::ConvexKLDivergenceTest::test_batched__without_device", "optax/losses/_classification_test.py::ConvexKLDivergenceTest::test_batched__without_jit", "optax/losses/_classification_test.py::ConvexKLDivergenceTest::test_scalar__with_device", "optax/losses/_classification_test.py::ConvexKLDivergenceTest::test_scalar__with_jit", "optax/losses/_classification_test.py::ConvexKLDivergenceTest::test_scalar__without_device", "optax/losses/_classification_test.py::ConvexKLDivergenceTest::test_scalar__without_jit", "optax/losses/_classification_test.py::PerceptronTest::test_batched_binary", "optax/losses/_classification_test.py::PerceptronTest::test_batched_multi_class", "optax/losses/_classification_test.py::PerceptronTest::test_binary", "optax/losses/_classification_test.py::PerceptronTest::test_multi_class", "optax/losses/_classification_test.py::KLDivergenceTest::test_batched__with_device", "optax/losses/_classification_test.py::KLDivergenceTest::test_batched__with_jit", "optax/losses/_classification_test.py::KLDivergenceTest::test_batched__without_device", "optax/losses/_classification_test.py::KLDivergenceTest::test_batched__without_jit", "optax/losses/_classification_test.py::KLDivergenceTest::test_scalar__with_device", "optax/losses/_classification_test.py::KLDivergenceTest::test_scalar__with_jit", "optax/losses/_classification_test.py::KLDivergenceTest::test_scalar__without_device", "optax/losses/_classification_test.py::KLDivergenceTest::test_scalar__without_jit", "optax/losses/_classification_test.py::KLDivergenceWithLogTargetsTest::test_batched__with_device", "optax/losses/_classification_test.py::KLDivergenceWithLogTargetsTest::test_batched__with_jit", "optax/losses/_classification_test.py::KLDivergenceWithLogTargetsTest::test_batched__without_device", "optax/losses/_classification_test.py::KLDivergenceWithLogTargetsTest::test_batched__without_jit", "optax/losses/_classification_test.py::KLDivergenceWithLogTargetsTest::test_scalar__with_device", "optax/losses/_classification_test.py::KLDivergenceWithLogTargetsTest::test_scalar__with_jit", "optax/losses/_classification_test.py::KLDivergenceWithLogTargetsTest::test_scalar__without_device", "optax/losses/_classification_test.py::KLDivergenceWithLogTargetsTest::test_scalar__without_jit", "optax/losses/_classification_test.py::CTCTest::test_repeat_with_one_to_one_alignment__with_device", "optax/losses/_classification_test.py::CTCTest::test_repeat_with_one_to_one_alignment__with_jit", "optax/losses/_classification_test.py::CTCTest::test_repeat_with_one_to_one_alignment__without_device", "optax/losses/_classification_test.py::CTCTest::test_repeat_with_one_to_one_alignment__without_jit", "optax/losses/_classification_test.py::CTCTest::test_with_one_to_one_alignment__with_device", "optax/losses/_classification_test.py::CTCTest::test_with_one_to_one_alignment__with_jit", "optax/losses/_classification_test.py::CTCTest::test_with_one_to_one_alignment__without_device", "optax/losses/_classification_test.py::CTCTest::test_with_one_to_one_alignment__without_jit", "optax/losses/_classification_test.py::CTCTest::test_with_one_to_one_alignment_and_paddings__with_device", "optax/losses/_classification_test.py::CTCTest::test_with_one_to_one_alignment_and_paddings__with_jit", "optax/losses/_classification_test.py::CTCTest::test_with_one_to_one_alignment_and_paddings__without_device", "optax/losses/_classification_test.py::CTCTest::test_with_one_to_one_alignment_and_paddings__without_jit", "optax/losses/_classification_test.py::SigmoidFocalLossTest::test_alpha_one__with_device", "optax/losses/_classification_test.py::SigmoidFocalLossTest::test_alpha_one__with_jit", "optax/losses/_classification_test.py::SigmoidFocalLossTest::test_alpha_one__without_device", "optax/losses/_classification_test.py::SigmoidFocalLossTest::test_alpha_one__without_jit", "optax/losses/_classification_test.py::SigmoidFocalLossTest::test_focal_equals_ce__with_device", "optax/losses/_classification_test.py::SigmoidFocalLossTest::test_focal_equals_ce__with_jit", "optax/losses/_classification_test.py::SigmoidFocalLossTest::test_focal_equals_ce__without_device", "optax/losses/_classification_test.py::SigmoidFocalLossTest::test_focal_equals_ce__without_jit", "optax/losses/_classification_test.py::SigmoidFocalLossTest::test_ignore_negative__with_device", "optax/losses/_classification_test.py::SigmoidFocalLossTest::test_ignore_negative__with_jit", "optax/losses/_classification_test.py::SigmoidFocalLossTest::test_ignore_negative__without_device", "optax/losses/_classification_test.py::SigmoidFocalLossTest::test_ignore_negative__without_jit", "optax/losses/_classification_test.py::SigmoidFocalLossTest::test_ignore_positive__with_device", "optax/losses/_classification_test.py::SigmoidFocalLossTest::test_ignore_positive__with_jit", "optax/losses/_classification_test.py::SigmoidFocalLossTest::test_ignore_positive__without_device", "optax/losses/_classification_test.py::SigmoidFocalLossTest::test_ignore_positive__without_jit", "optax/losses/_classification_test.py::SigmoidFocalLossTest::test_large_logit_fl_less_than_ce__with_device", "optax/losses/_classification_test.py::SigmoidFocalLossTest::test_large_logit_fl_less_than_ce__with_jit", "optax/losses/_classification_test.py::SigmoidFocalLossTest::test_large_logit_fl_less_than_ce__without_device", "optax/losses/_classification_test.py::SigmoidFocalLossTest::test_large_logit_fl_less_than_ce__without_jit", "optax/losses/_classification_test.py::SigmoidFocalLossTest::test_scale__with_device", "optax/losses/_classification_test.py::SigmoidFocalLossTest::test_scale__with_jit", "optax/losses/_classification_test.py::SigmoidFocalLossTest::test_scale__without_device", "optax/losses/_classification_test.py::SigmoidFocalLossTest::test_scale__without_jit", "optax/losses/_classification_test.py::SigmoidFocalLossTest::test_small_logit_fl_less_than_ce__with_device", "optax/losses/_classification_test.py::SigmoidFocalLossTest::test_small_logit_fl_less_than_ce__with_jit", "optax/losses/_classification_test.py::SigmoidFocalLossTest::test_small_logit_fl_less_than_ce__without_device", "optax/losses/_classification_test.py::SigmoidFocalLossTest::test_small_logit_fl_less_than_ce__without_jit", "optax/losses/_self_supervised_test.py::NtxentTest::test_batched__with_device", "optax/losses/_self_supervised_test.py::NtxentTest::test_batched__with_jit", "optax/losses/_self_supervised_test.py::NtxentTest::test_batched__without_device", "optax/losses/_self_supervised_test.py::NtxentTest::test_batched__without_jit" ]
[]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> Added a NTXent loss An normalized temperature scaled cross entropy (NTXent) loss for a contrastive learning objective. I am fairly new to submitting pull requests to public repos, so I didn't add a ton of tests for this outside a batched test. Let me know if there is anything else I should add! ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in optax/losses/_self_supervised.py] (definition of ntxent:) def ntxent( embeddings: chex.Array, labels: chex.Array, temperature: chex.Numeric = 0.07 ) -> chex.Numeric: """Normalized temperature scaled cross entropy loss (NT-Xent). References: T. Chen et al `A Simple Framework for Contrastive Learning of Visual Representations <http://arxiv.org/abs/2002.05709>`_, 2020 kevinmusgrave.github.io/pytorch-metric-learning/losses/#ntxentloss Args: emeddings: batch of embeddings, with shape [batch, feature_length] labels: labels for groups that are positive pairs. e.g. if you have a batch of 4 embeddings and the first two and last two were positive pairs your `labels` should look like [0, 0, 1, 1]. labels SHOULD NOT be all the same (e.g. [0, 0, 0, 0]) you will get a NaN result. Shape [batch] temperature: temperature scaling parameter. Returns: A scalar loss value of NT-Xent values averaged over all positive pairs .. versionadded:: 0.2.3""" [end of new definitions in optax/losses/_self_supervised.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
1e08bccf195ac54e7d9d766eb5e69345bf0e3230
tobymao__sqlglot-3145
3,145
tobymao/sqlglot
null
d6bac3e54c6445c52daa04015b1b2e4a6933e682
2024-03-14T14:27:31Z
diff --git a/sqlglot/dialects/tsql.py b/sqlglot/dialects/tsql.py index 45855772cb..755360cc16 100644 --- a/sqlglot/dialects/tsql.py +++ b/sqlglot/dialects/tsql.py @@ -810,6 +810,22 @@ class Generator(generator.Generator): exp.VolatileProperty: exp.Properties.Location.UNSUPPORTED, } + def select_sql(self, expression: exp.Select) -> str: + if expression.args.get("offset"): + if not expression.args.get("order"): + # ORDER BY is required in order to use OFFSET in a query, so we use + # a noop order by, since we don't really care about the order. + # See: https://www.microsoftpressstore.com/articles/article.aspx?p=2314819 + expression.order_by(exp.select(exp.null()).subquery(), copy=False) + + limit = expression.args.get("limit") + if isinstance(limit, exp.Limit): + # TOP and OFFSET can't be combined, we need use FETCH instead of TOP + # we replace here because otherwise TOP would be generated in select_sql + limit.replace(exp.Fetch(direction="FIRST", count=limit.expression)) + + return super().select_sql(expression) + def convert_sql(self, expression: exp.Convert) -> str: name = "TRY_CONVERT" if expression.args.get("safe") else "CONVERT" return self.func( diff --git a/sqlglot/generator.py b/sqlglot/generator.py index ed3b2c7272..1198aaaf43 100644 --- a/sqlglot/generator.py +++ b/sqlglot/generator.py @@ -2125,24 +2125,13 @@ def matchrecognize_sql(self, expression: exp.MatchRecognize) -> str: return f"{self.seg('MATCH_RECOGNIZE')} {self.wrap(body)}{alias}" def query_modifiers(self, expression: exp.Expression, *sqls: str) -> str: - limit: t.Optional[exp.Fetch | exp.Limit] = expression.args.get("limit") - - # If the limit is generated as TOP, we need to ensure it's not generated twice - with_offset_limit_modifiers = not isinstance(limit, exp.Limit) or not self.LIMIT_IS_TOP + limit = expression.args.get("limit") if self.LIMIT_FETCH == "LIMIT" and isinstance(limit, exp.Fetch): limit = exp.Limit(expression=exp.maybe_copy(limit.args.get("count"))) elif self.LIMIT_FETCH == "FETCH" and isinstance(limit, exp.Limit): limit = exp.Fetch(direction="FIRST", count=exp.maybe_copy(limit.expression)) - fetch = isinstance(limit, exp.Fetch) - - offset_limit_modifiers = ( - self.offset_limit_modifiers(expression, fetch, limit) - if with_offset_limit_modifiers - else [] - ) - options = self.expressions(expression, key="options") if options: options = f" OPTION{self.wrap(options)}" @@ -2159,7 +2148,7 @@ def query_modifiers(self, expression: exp.Expression, *sqls: str) -> str: self.sql(expression, "having"), *[gen(self, expression) for gen in self.AFTER_HAVING_MODIFIER_TRANSFORMS.values()], self.sql(expression, "order"), - *offset_limit_modifiers, + *self.offset_limit_modifiers(expression, isinstance(limit, exp.Fetch), limit), *self.after_limit_modifiers(expression), options, sep="", @@ -2190,12 +2179,13 @@ def select_sql(self, expression: exp.Select) -> str: distinct = self.sql(expression, "distinct") distinct = f" {distinct}" if distinct else "" kind = self.sql(expression, "kind") + limit = expression.args.get("limit") - top = ( - self.limit_sql(limit, top=True) - if isinstance(limit, exp.Limit) and self.LIMIT_IS_TOP - else "" - ) + if isinstance(limit, exp.Limit) and self.LIMIT_IS_TOP: + top = self.limit_sql(limit, top=True) + limit.pop() + else: + top = "" expressions = self.expressions(expression)
diff --git a/tests/dialects/test_tsql.py b/tests/dialects/test_tsql.py index ed474fd1af..1d2f03b631 100644 --- a/tests/dialects/test_tsql.py +++ b/tests/dialects/test_tsql.py @@ -272,6 +272,28 @@ def test_tsql(self): "SELECT [x].[y] FROM foo", ) + self.validate_all( + "SELECT * FROM t ORDER BY (SELECT NULL) OFFSET 2 ROWS", + read={ + "postgres": "SELECT * FROM t OFFSET 2", + }, + write={ + "postgres": "SELECT * FROM t ORDER BY (SELECT NULL) NULLS FIRST OFFSET 2", + "tsql": "SELECT * FROM t ORDER BY (SELECT NULL) OFFSET 2 ROWS", + }, + ) + self.validate_all( + "SELECT * FROM t ORDER BY (SELECT NULL) OFFSET 5 ROWS FETCH FIRST 10 ROWS ONLY", + read={ + "duckdb": "SELECT * FROM t LIMIT 10 OFFSET 5", + "sqlite": "SELECT * FROM t LIMIT 5, 10", + "tsql": "SELECT * FROM t ORDER BY (SELECT NULL) OFFSET 5 ROWS FETCH FIRST 10 ROWS ONLY", + }, + write={ + "duckdb": "SELECT * FROM t ORDER BY (SELECT NULL) NULLS FIRST LIMIT 10 OFFSET 5", + "sqlite": "SELECT * FROM t ORDER BY (SELECT NULL) LIMIT 10 OFFSET 5", + }, + ) self.validate_all( "SELECT CAST([a].[b] AS SMALLINT) FROM foo", write={
[ { "components": [ { "doc": "", "lines": [ 813, 827 ], "name": "TSQL.Generator.select_sql", "signature": "def select_sql(self, expression: exp.Select) -> str:", "type": "function" } ], "file": "sqlglot/dialects/tsql.py" } ]
[ "tests/dialects/test_tsql.py::TestTSQL::test_tsql" ]
[ "tests/dialects/test_tsql.py::TestTSQL::test__types_ints", "tests/dialects/test_tsql.py::TestTSQL::test_add_date", "tests/dialects/test_tsql.py::TestTSQL::test_charindex", "tests/dialects/test_tsql.py::TestTSQL::test_commit", "tests/dialects/test_tsql.py::TestTSQL::test_convert", "tests/dialects/test_tsql.py::TestTSQL::test_current_user", "tests/dialects/test_tsql.py::TestTSQL::test_date_diff", "tests/dialects/test_tsql.py::TestTSQL::test_datefromparts", "tests/dialects/test_tsql.py::TestTSQL::test_datename", "tests/dialects/test_tsql.py::TestTSQL::test_datepart", "tests/dialects/test_tsql.py::TestTSQL::test_ddl", "tests/dialects/test_tsql.py::TestTSQL::test_eomonth", "tests/dialects/test_tsql.py::TestTSQL::test_format", "tests/dialects/test_tsql.py::TestTSQL::test_fullproc", "tests/dialects/test_tsql.py::TestTSQL::test_hints", "tests/dialects/test_tsql.py::TestTSQL::test_identifier_prefixes", "tests/dialects/test_tsql.py::TestTSQL::test_insert_cte", "tests/dialects/test_tsql.py::TestTSQL::test_isnull", "tests/dialects/test_tsql.py::TestTSQL::test_json", "tests/dialects/test_tsql.py::TestTSQL::test_lateral_subquery", "tests/dialects/test_tsql.py::TestTSQL::test_lateral_table_valued_function", "tests/dialects/test_tsql.py::TestTSQL::test_len", "tests/dialects/test_tsql.py::TestTSQL::test_openjson", "tests/dialects/test_tsql.py::TestTSQL::test_option", "tests/dialects/test_tsql.py::TestTSQL::test_procedure_keywords", "tests/dialects/test_tsql.py::TestTSQL::test_qualify_derived_table_outputs", "tests/dialects/test_tsql.py::TestTSQL::test_replicate", "tests/dialects/test_tsql.py::TestTSQL::test_rollback", "tests/dialects/test_tsql.py::TestTSQL::test_set", "tests/dialects/test_tsql.py::TestTSQL::test_string", "tests/dialects/test_tsql.py::TestTSQL::test_system_time", "tests/dialects/test_tsql.py::TestTSQL::test_temp_table", "tests/dialects/test_tsql.py::TestTSQL::test_temporal_table", "tests/dialects/test_tsql.py::TestTSQL::test_top", "tests/dialects/test_tsql.py::TestTSQL::test_transaction", "tests/dialects/test_tsql.py::TestTSQL::test_types", "tests/dialects/test_tsql.py::TestTSQL::test_types_bin", "tests/dialects/test_tsql.py::TestTSQL::test_types_date", "tests/dialects/test_tsql.py::TestTSQL::test_types_decimals", "tests/dialects/test_tsql.py::TestTSQL::test_types_string", "tests/dialects/test_tsql.py::TestTSQL::test_udf" ]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> Feat(tsql): transpile LIMIT with OFFSET properly Fixes #3144 Reference: - https://www.microsoftpressstore.com/articles/article.aspx?p=2314819 - https://learn.microsoft.com/en-us/sql/t-sql/queries/select-order-by-clause-transact-sql?view=sql-server-ver16 ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in sqlglot/dialects/tsql.py] (definition of TSQL.Generator.select_sql:) def select_sql(self, expression: exp.Select) -> str: [end of new definitions in sqlglot/dialects/tsql.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
Here is the discussion in the issues of the pull request. <issues> Concerns about Translating SQLite Queries to TSQL 1. **Offset Issue:** When attempting to convert an SQLite query to TSQL using the provided code snippet: ```python import sqlglot sql_a = "SELECT name, (SELECT COUNT(*) FROM orders WHERE orders.customer_id = customers.id) AS order_count FROM customers LIMIT 5, 10" sql_b = sqlglot.transpile(sql_a, read="sqlite", write="tsql")[0] print(sql_b) ``` The resulting TSQL output is as follows: ```sql SELECT TOP 10 name, (SELECT COUNT(*) FROM orders WHERE orders.customer_id = customers.id) AS order_count FROM customers ``` It appears that the translated TSQL does not include information about the offset of 5. Instead, it only selects the top 10 rows, neglecting the fact that it should select 10 rows after an offset of 5. Could you please verify if this behavior is intended? 2. **Completeness of Translation:** I had a question about the thoroughness of the translation process from SQLite to TSQL. Does the transpiler cover all possible cases of SQLite queries that are incompatible with TSQL syntax? Are there any known clauses or scenarios where the transpiler fails to convert the syntax accurately? ---------- Hey, thanks for the report. I'll take a look, this seems like a bug. > I had a question about the thoroughness of the translation process from SQLite to TSQL. Does the transpiler cover all possible cases of SQLite queries that are incompatible with TSQL syntax? Are there any known clauses or scenarios where the transpiler fails to convert the syntax accurately? The transpiler probably does not cover all possible cases as both dialects are huge and there may even be features that are not transpilable at all. It does cover a very large surface though, so I expect that for more "standard" queries you won't have any issues. There's no documentation about missing functionality, but feel free to file issues and / or PRs if you come across bugs in the future so we can improve. -------------------- </issues>
ceb42fabad60312699e4b15936aeebac00e22e4d
EleutherAI__lm-evaluation-harness-1566
1,566
EleutherAI/lm-evaluation-harness
null
49695e8d94c3ab011b7ae8814d809de30b1b1182
2024-03-12T17:35:39Z
diff --git a/lm_eval/__main__.py b/lm_eval/__main__.py index 489c1662d4..18c243d431 100644 --- a/lm_eval/__main__.py +++ b/lm_eval/__main__.py @@ -53,13 +53,30 @@ def parse_value(item): return items -def parse_eval_args() -> argparse.Namespace: +def check_argument_types(parser: argparse.ArgumentParser): + """ + Check to make sure all CLI args are typed, raises error if not + """ + for action in parser._actions: + if action.dest != "help" and not action.const: + if action.type is None: + raise ValueError( + f"Argument '{action.dest}' doesn't have a type specified." + ) + else: + continue + + +def setup_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter) - parser.add_argument("--model", "-m", default="hf", help="Name of model e.g. `hf`") + parser.add_argument( + "--model", "-m", type=str, default="hf", help="Name of model e.g. `hf`" + ) parser.add_argument( "--tasks", "-t", default=None, + type=str, metavar="task1,task2", help="To get full list of tasks, use the command lm-eval --tasks list", ) @@ -67,6 +84,7 @@ def parse_eval_args() -> argparse.Namespace: "--model_args", "-a", default="", + type=str, help="Comma separated string arguments for model, e.g. `pretrained=EleutherAI/pythia-160m,dtype=float32`", ) parser.add_argument( @@ -164,6 +182,7 @@ def parse_eval_args() -> argparse.Namespace: ) parser.add_argument( "--gen_kwargs", + type=dict, default=None, help=( "String arguments for model generation on greedy_until tasks," @@ -180,6 +199,7 @@ def parse_eval_args() -> argparse.Namespace: ) parser.add_argument( "--wandb_args", + type=str, default="", help="Comma separated string arguments passed to wandb.init, e.g. `project=lm-eval,job_type=eval", ) @@ -209,13 +229,19 @@ def parse_eval_args() -> argparse.Namespace: help="Sets trust_remote_code to True to execute code to create HF Datasets from the Hub", ) + return parser + + +def parse_eval_args(parser: argparse.ArgumentParser) -> argparse.Namespace: + check_argument_types(parser) return parser.parse_args() def cli_evaluate(args: Union[argparse.Namespace, None] = None) -> None: if not args: # we allow for args to be passed externally, else we parse them ourselves - args = parse_eval_args() + parser = setup_parser() + args = parse_eval_args(parser) if args.wandb_args: wandb_logger = WandbLogger(**simple_parse_args_string(args.wandb_args))
diff --git a/tests/test_cli.py b/tests/test_cli.py new file mode 100644 index 0000000000..feaa7340d6 --- /dev/null +++ b/tests/test_cli.py @@ -0,0 +1,43 @@ +import argparse + +import pytest + +import lm_eval.__main__ + + +def test_cli_parse_error(): + """ + Assert error raised if cli args argument doesn't have type + """ + with pytest.raises(ValueError): + parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter) + parser.add_argument( + "--model", "-m", type=str, default="hf", help="Name of model e.g. `hf`" + ) + parser.add_argument( + "--tasks", + "-t", + default=None, + metavar="task1,task2", + help="To get full list of tasks, use the command lm-eval --tasks list", + ) + lm_eval.__main__.check_argument_types(parser) + + +def test_cli_parse_no_error(): + """ + Assert typed arguments are parsed correctly + """ + parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter) + parser.add_argument( + "--model", "-m", type=str, default="hf", help="Name of model e.g. `hf`" + ) + parser.add_argument( + "--tasks", + "-t", + type=str, + default=None, + metavar="task1,task2", + help="To get full list of tasks, use the command lm-eval --tasks list", + ) + lm_eval.__main__.check_argument_types(parser)
[ { "components": [ { "doc": "Check to make sure all CLI args are typed, raises error if not", "lines": [ 56, 67 ], "name": "check_argument_types", "signature": "def check_argument_types(parser: argparse.ArgumentParser):", "type": "function" }, { "doc": "", "lines": [ 70, 232 ], "name": "setup_parser", "signature": "def setup_parser() -> argparse.ArgumentParser:", "type": "function" } ], "file": "lm_eval/__main__.py" } ]
[ "tests/test_cli.py::test_cli_parse_error", "tests/test_cli.py::test_cli_parse_no_error" ]
[]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> Proposed approach for testing CLI arg parsing See discussion here: https://github.com/EleutherAI/lm-evaluation-harness/issues/1518 Here's an approach to start testing CLI argument parsing: 1. Separate out setting up the argument parser in `parse_eval_args` into a separate method, `setup_parser` that gets called in `parse_eval_args` 2. Create unit tests that call the parser for each of the command line arguments 3. Adding specific TypeError exceptions at each argument entrypoint in the `cli_evaluate` method Let me know what you think about this approach. If it seems reasonable, I'll add the tests for the rest of the methods and exceptions where it's reasonable. @LSinev @haileyschoelkopf ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in lm_eval/__main__.py] (definition of check_argument_types:) def check_argument_types(parser: argparse.ArgumentParser): """Check to make sure all CLI args are typed, raises error if not""" (definition of setup_parser:) def setup_parser() -> argparse.ArgumentParser: [end of new definitions in lm_eval/__main__.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
decc533d02222f3b866d9a89263277fe0cc2fcb2
astropy__astropy-16135
16,135
astropy/astropy
v5.3
ea875472867f296eee3ed75989ed402d55587940
2024-02-29T23:40:43Z
diff --git a/astropy/coordinates/representation/cylindrical.py b/astropy/coordinates/representation/cylindrical.py index 9127fb2dcb08..acd9ab936953 100644 --- a/astropy/coordinates/representation/cylindrical.py +++ b/astropy/coordinates/representation/cylindrical.py @@ -11,7 +11,7 @@ from .base import BaseDifferential, BaseRepresentation from .cartesian import CartesianRepresentation -from .spherical import _spherical_op_funcs +from .spherical import PhysicsSphericalRepresentation, _spherical_op_funcs class CylindricalRepresentation(BaseRepresentation): @@ -135,6 +135,22 @@ def _scale_operation(self, op, *args): result.differentials[key] = differential.__class__(*new_comps, copy=False) return result + def represent_as(self, other_class, differential_class=None): + if isinstance(other_class, type): + if issubclass(other_class, PhysicsSphericalRepresentation): + diffs = self._re_represent_differentials( + other_class, differential_class + ) + r = np.hypot(self.rho, self.z) + return other_class( + r=r, + theta=np.arccos(self.z / r), + phi=self.phi, + differentials=diffs, + ) + + return super().represent_as(other_class, differential_class) + class CylindricalDifferential(BaseDifferential): """Differential(s) of points in cylindrical coordinates. diff --git a/astropy/coordinates/representation/spherical.py b/astropy/coordinates/representation/spherical.py index 5ef93c8f4a00..dba9c7e1f9bc 100644 --- a/astropy/coordinates/representation/spherical.py +++ b/astropy/coordinates/representation/spherical.py @@ -750,6 +750,19 @@ def represent_as(self, other_class, differential_class=None): differentials=diffs, copy=False, ) + from .cylindrical import CylindricalRepresentation + + if issubclass(other_class, CylindricalRepresentation): + diffs = self._re_represent_differentials( + other_class, differential_class + ) + return other_class( + rho=self.r * np.sin(self.theta), + phi=self.phi, + z=self.r * np.cos(self.theta), + differentials=diffs, + copy=False, + ) return super().represent_as(other_class, differential_class)
diff --git a/astropy/coordinates/tests/test_representation.py b/astropy/coordinates/tests/test_representation.py index d2d257e30a6f..2f84236bdd5e 100644 --- a/astropy/coordinates/tests/test_representation.py +++ b/astropy/coordinates/tests/test_representation.py @@ -842,6 +842,25 @@ def test_representation_shortcuts(self): ) assert representation_equal_up_to_angular_type(got, expected) + got = sph.represent_as(CylindricalRepresentation, CylindricalDifferential) + assert np.may_share_memory(sph.phi, got.phi) + expected = BaseRepresentation.represent_as( + sph, CylindricalRepresentation, CylindricalDifferential + ) + assert_allclose_quantity(got.rho, expected.rho, atol=5e-17 * u.kpc) + assert_allclose_quantity(got.phi, expected.phi, atol=3e-16 * u.deg) + assert_array_equal(got.z, expected.z) + + def test_to_cylindrical_at_the_origin(self): + """Test that the transformation to cylindrical at the origin preserves phi.""" + sph = PhysicsSphericalRepresentation( + phi=270 * u.deg, theta=45 * u.deg, r=0 * u.kpc + ) + cyl = sph.represent_as(CylindricalRepresentation) + assert cyl.rho == 0.0 * u.kpc + assert cyl.z == 0.0 * u.kpc + assert cyl.phi == 270 * u.deg # phi is preserved exactly + def test_initialize_with_nan(self): # Regression test for gh-11558: initialization used to fail. psr = PhysicsSphericalRepresentation( @@ -1380,6 +1399,39 @@ def test_transform(self): assert_allclose_quantity(s3.z, expected.z) assert_allclose_quantity(s3.rho, expected.rho) + def test_representation_shortcuts(self): + """Test that shortcuts in ``represent_as`` don't fail.""" + difs = CylindricalDifferential( + d_rho=4 * u.km / u.s, d_phi=5 * u.mas / u.yr, d_z=6 * u.km / u.s + ) + cyl = CylindricalRepresentation( + rho=1 * u.kpc, phi=2 * u.deg, z=3 * u.kpc, differentials={"s": difs} + ) + + # PhysicsSpherical Representation + got = cyl.represent_as( + PhysicsSphericalRepresentation, PhysicsSphericalDifferential + ) + expected = BaseRepresentation.represent_as( + cyl, PhysicsSphericalRepresentation, PhysicsSphericalDifferential + ) + assert_allclose_quantity(got.r, expected.r) + assert_allclose_quantity(got.phi, expected.phi) + assert_allclose_quantity(got.theta, expected.theta) + assert representation_equal_up_to_angular_type(got, expected) + + def test_to_physicsspherical_at_the_origin(self): + """Test that the transformation to physicsspherical at the origin preserves phi.""" + cyl = CylindricalRepresentation( + rho=0 * u.kpc, + phi=23.5 * u.deg, + z=3 * u.kpc, + ) + sph = cyl.represent_as(PhysicsSphericalRepresentation) + assert_allclose(sph.r, 3 * u.kpc) + assert_allclose(sph.theta, 0 * u.deg) + assert cyl.phi == 23.5 * u.deg # phi is preserved exactly + class TestUnitSphericalCosLatDifferential: @pytest.mark.parametrize("matrix", list(matrices.values()))
[ { "components": [ { "doc": "", "lines": [ 138, 152 ], "name": "CylindricalRepresentation.represent_as", "signature": "def represent_as(self, other_class, differential_class=None):", "type": "function" } ], "file": "astropy/coordinates/representation/cylindrical.py" } ]
[ "astropy/coordinates/tests/test_representation.py::TestPhysicsSphericalRepresentation::test_representation_shortcuts", "astropy/coordinates/tests/test_representation.py::TestPhysicsSphericalRepresentation::test_to_cylindrical_at_the_origin" ]
[ "astropy/coordinates/tests/test_representation.py::TestRadialRepresentation::test_transform", "astropy/coordinates/tests/test_representation.py::TestSphericalRepresentation::test_name", "astropy/coordinates/tests/test_representation.py::TestSphericalRepresentation::test_empty_init", "astropy/coordinates/tests/test_representation.py::TestSphericalRepresentation::test_init_quantity", "astropy/coordinates/tests/test_representation.py::TestSphericalRepresentation::test_init_no_mutate_input", "astropy/coordinates/tests/test_representation.py::TestSphericalRepresentation::test_init_lonlat", "astropy/coordinates/tests/test_representation.py::TestSphericalRepresentation::test_init_subclass", "astropy/coordinates/tests/test_representation.py::TestSphericalRepresentation::test_init_array", "astropy/coordinates/tests/test_representation.py::TestSphericalRepresentation::test_init_array_nocopy", "astropy/coordinates/tests/test_representation.py::TestSphericalRepresentation::test_init_float32_array", "astropy/coordinates/tests/test_representation.py::TestSphericalRepresentation::test_reprobj", "astropy/coordinates/tests/test_representation.py::TestSphericalRepresentation::test_broadcasting", "astropy/coordinates/tests/test_representation.py::TestSphericalRepresentation::test_broadcasting_mismatch", "astropy/coordinates/tests/test_representation.py::TestSphericalRepresentation::test_broadcasting_and_nocopy", "astropy/coordinates/tests/test_representation.py::TestSphericalRepresentation::test_readonly", "astropy/coordinates/tests/test_representation.py::TestSphericalRepresentation::test_getitem_len_iterable", "astropy/coordinates/tests/test_representation.py::TestSphericalRepresentation::test_getitem_len_iterable_scalar", "astropy/coordinates/tests/test_representation.py::TestSphericalRepresentation::test_setitem", "astropy/coordinates/tests/test_representation.py::TestSphericalRepresentation::test_negative_distance", "astropy/coordinates/tests/test_representation.py::TestSphericalRepresentation::test_nan_distance", "astropy/coordinates/tests/test_representation.py::TestSphericalRepresentation::test_raise_on_extra_arguments", "astropy/coordinates/tests/test_representation.py::TestSphericalRepresentation::test_representation_shortcuts", "astropy/coordinates/tests/test_representation.py::TestSphericalRepresentation::test_transform", "astropy/coordinates/tests/test_representation.py::TestSphericalRepresentation::test_transform_with_NaN", "astropy/coordinates/tests/test_representation.py::TestUnitSphericalRepresentation::test_name", "astropy/coordinates/tests/test_representation.py::TestUnitSphericalRepresentation::test_empty_init", "astropy/coordinates/tests/test_representation.py::TestUnitSphericalRepresentation::test_init_quantity", "astropy/coordinates/tests/test_representation.py::TestUnitSphericalRepresentation::test_init_lonlat", "astropy/coordinates/tests/test_representation.py::TestUnitSphericalRepresentation::test_init_array", "astropy/coordinates/tests/test_representation.py::TestUnitSphericalRepresentation::test_init_array_nocopy", "astropy/coordinates/tests/test_representation.py::TestUnitSphericalRepresentation::test_reprobj", "astropy/coordinates/tests/test_representation.py::TestUnitSphericalRepresentation::test_broadcasting", "astropy/coordinates/tests/test_representation.py::TestUnitSphericalRepresentation::test_broadcasting_mismatch", "astropy/coordinates/tests/test_representation.py::TestUnitSphericalRepresentation::test_readonly", "astropy/coordinates/tests/test_representation.py::TestUnitSphericalRepresentation::test_getitem", "astropy/coordinates/tests/test_representation.py::TestUnitSphericalRepresentation::test_getitem_scalar", "astropy/coordinates/tests/test_representation.py::TestUnitSphericalRepresentation::test_representation_shortcuts", "astropy/coordinates/tests/test_representation.py::TestUnitSphericalRepresentation::test_transform", "astropy/coordinates/tests/test_representation.py::TestPhysicsSphericalRepresentation::test_name", "astropy/coordinates/tests/test_representation.py::TestPhysicsSphericalRepresentation::test_empty_init", "astropy/coordinates/tests/test_representation.py::TestPhysicsSphericalRepresentation::test_init_quantity", "astropy/coordinates/tests/test_representation.py::TestPhysicsSphericalRepresentation::test_init_phitheta", "astropy/coordinates/tests/test_representation.py::TestPhysicsSphericalRepresentation::test_init_array", "astropy/coordinates/tests/test_representation.py::TestPhysicsSphericalRepresentation::test_init_array_nocopy", "astropy/coordinates/tests/test_representation.py::TestPhysicsSphericalRepresentation::test_reprobj", "astropy/coordinates/tests/test_representation.py::TestPhysicsSphericalRepresentation::test_broadcasting", "astropy/coordinates/tests/test_representation.py::TestPhysicsSphericalRepresentation::test_broadcasting_mismatch", "astropy/coordinates/tests/test_representation.py::TestPhysicsSphericalRepresentation::test_readonly", "astropy/coordinates/tests/test_representation.py::TestPhysicsSphericalRepresentation::test_getitem", "astropy/coordinates/tests/test_representation.py::TestPhysicsSphericalRepresentation::test_getitem_scalar", "astropy/coordinates/tests/test_representation.py::TestPhysicsSphericalRepresentation::test_initialize_with_nan", "astropy/coordinates/tests/test_representation.py::TestPhysicsSphericalRepresentation::test_transform", "astropy/coordinates/tests/test_representation.py::TestPhysicsSphericalRepresentation::test_transform_with_NaN", "astropy/coordinates/tests/test_representation.py::TestCartesianRepresentation::test_name", "astropy/coordinates/tests/test_representation.py::TestCartesianRepresentation::test_empty_init", "astropy/coordinates/tests/test_representation.py::TestCartesianRepresentation::test_init_quantity", "astropy/coordinates/tests/test_representation.py::TestCartesianRepresentation::test_init_singleunit", "astropy/coordinates/tests/test_representation.py::TestCartesianRepresentation::test_init_array", "astropy/coordinates/tests/test_representation.py::TestCartesianRepresentation::test_init_one_array", "astropy/coordinates/tests/test_representation.py::TestCartesianRepresentation::test_init_one_array_size_fail", "astropy/coordinates/tests/test_representation.py::TestCartesianRepresentation::test_init_xyz_but_more_than_one_array_fail", "astropy/coordinates/tests/test_representation.py::TestCartesianRepresentation::test_init_one_array_yz_fail", "astropy/coordinates/tests/test_representation.py::TestCartesianRepresentation::test_init_array_nocopy", "astropy/coordinates/tests/test_representation.py::TestCartesianRepresentation::test_xyz_is_view_if_possible", "astropy/coordinates/tests/test_representation.py::TestCartesianRepresentation::test_reprobj", "astropy/coordinates/tests/test_representation.py::TestCartesianRepresentation::test_broadcasting", "astropy/coordinates/tests/test_representation.py::TestCartesianRepresentation::test_broadcasting_mismatch", "astropy/coordinates/tests/test_representation.py::TestCartesianRepresentation::test_readonly", "astropy/coordinates/tests/test_representation.py::TestCartesianRepresentation::test_xyz", "astropy/coordinates/tests/test_representation.py::TestCartesianRepresentation::test_unit_mismatch", "astropy/coordinates/tests/test_representation.py::TestCartesianRepresentation::test_unit_non_length", "astropy/coordinates/tests/test_representation.py::TestCartesianRepresentation::test_getitem", "astropy/coordinates/tests/test_representation.py::TestCartesianRepresentation::test_getitem_scalar", "astropy/coordinates/tests/test_representation.py::TestCartesianRepresentation::test_transform", "astropy/coordinates/tests/test_representation.py::TestCartesianRepresentation::test_transform_non_contiguous_matrix", "astropy/coordinates/tests/test_representation.py::TestCylindricalRepresentation::test_name", "astropy/coordinates/tests/test_representation.py::TestCylindricalRepresentation::test_empty_init", "astropy/coordinates/tests/test_representation.py::TestCylindricalRepresentation::test_init_quantity", "astropy/coordinates/tests/test_representation.py::TestCylindricalRepresentation::test_init_array", "astropy/coordinates/tests/test_representation.py::TestCylindricalRepresentation::test_init_array_nocopy", "astropy/coordinates/tests/test_representation.py::TestCylindricalRepresentation::test_reprobj", "astropy/coordinates/tests/test_representation.py::TestCylindricalRepresentation::test_broadcasting", "astropy/coordinates/tests/test_representation.py::TestCylindricalRepresentation::test_broadcasting_mismatch", "astropy/coordinates/tests/test_representation.py::TestCylindricalRepresentation::test_readonly", "astropy/coordinates/tests/test_representation.py::TestCylindricalRepresentation::test_getitem", "astropy/coordinates/tests/test_representation.py::TestCylindricalRepresentation::test_getitem_scalar", "astropy/coordinates/tests/test_representation.py::TestCylindricalRepresentation::test_transform", "astropy/coordinates/tests/test_representation.py::TestCylindricalRepresentation::test_representation_shortcuts", "astropy/coordinates/tests/test_representation.py::TestCylindricalRepresentation::test_to_physicsspherical_at_the_origin", "astropy/coordinates/tests/test_representation.py::TestUnitSphericalCosLatDifferential::test_transform[matrix0]", "astropy/coordinates/tests/test_representation.py::TestUnitSphericalCosLatDifferential::test_transform[matrix1]", "astropy/coordinates/tests/test_representation.py::test_cartesian_spherical_roundtrip", "astropy/coordinates/tests/test_representation.py::test_cartesian_setting_with_other", "astropy/coordinates/tests/test_representation.py::test_cartesian_physics_spherical_roundtrip", "astropy/coordinates/tests/test_representation.py::test_spherical_physics_spherical_roundtrip", "astropy/coordinates/tests/test_representation.py::test_cartesian_cylindrical_roundtrip", "astropy/coordinates/tests/test_representation.py::test_unit_spherical_roundtrip", "astropy/coordinates/tests/test_representation.py::test_no_unnecessary_copies", "astropy/coordinates/tests/test_representation.py::test_representation_repr", "astropy/coordinates/tests/test_representation.py::test_representation_repr_multi_d", "astropy/coordinates/tests/test_representation.py::test_representation_str", "astropy/coordinates/tests/test_representation.py::test_representation_str_multi_d", "astropy/coordinates/tests/test_representation.py::test_subclass_representation", "astropy/coordinates/tests/test_representation.py::test_minimal_subclass", "astropy/coordinates/tests/test_representation.py::test_duplicate_warning", "astropy/coordinates/tests/test_representation.py::TestCartesianRepresentationWithDifferential::test_init_differential", "astropy/coordinates/tests/test_representation.py::TestCartesianRepresentationWithDifferential::test_init_differential_compatible", "astropy/coordinates/tests/test_representation.py::TestCartesianRepresentationWithDifferential::test_init_differential_multiple_equivalent_keys", "astropy/coordinates/tests/test_representation.py::TestCartesianRepresentationWithDifferential::test_init_array_broadcasting", "astropy/coordinates/tests/test_representation.py::TestCartesianRepresentationWithDifferential::test_reprobj", "astropy/coordinates/tests/test_representation.py::TestCartesianRepresentationWithDifferential::test_readonly", "astropy/coordinates/tests/test_representation.py::TestCartesianRepresentationWithDifferential::test_represent_as", "astropy/coordinates/tests/test_representation.py::TestCartesianRepresentationWithDifferential::test_represent_as_unit_spherical_with_diff[SphericalDifferential-UnitSphericalDifferential]", "astropy/coordinates/tests/test_representation.py::TestCartesianRepresentationWithDifferential::test_represent_as_unit_spherical_with_diff[SphericalCosLatDifferential-UnitSphericalCosLatDifferential]", "astropy/coordinates/tests/test_representation.py::TestCartesianRepresentationWithDifferential::test_getitem", "astropy/coordinates/tests/test_representation.py::TestCartesianRepresentationWithDifferential::test_setitem", "astropy/coordinates/tests/test_representation.py::TestCartesianRepresentationWithDifferential::test_transform", "astropy/coordinates/tests/test_representation.py::TestCartesianRepresentationWithDifferential::test_with_differentials", "astropy/coordinates/tests/test_representation.py::test_repr_with_differentials", "astropy/coordinates/tests/test_representation.py::test_to_cartesian", "astropy/coordinates/tests/test_representation.py::test_unitphysics", "astropy/coordinates/tests/test_representation.py::test_distance_warning", "astropy/coordinates/tests/test_representation.py::test_dtype_preservation_in_indexing", "astropy/coordinates/tests/test_representation.py::TestInfo::test_info_unit", "astropy/coordinates/tests/test_representation.py::TestInfo::test_roundtrip[rep]", "astropy/coordinates/tests/test_representation.py::TestInfo::test_roundtrip[diff]", "astropy/coordinates/tests/test_representation.py::TestInfo::test_roundtrip[rep_w_diff]", "astropy/coordinates/tests/test_representation.py::test_differential_norm_noncartesian[SphericalDifferential]", "astropy/coordinates/tests/test_representation.py::test_differential_norm_noncartesian[SphericalCosLatDifferential]", "astropy/coordinates/tests/test_representation.py::test_differential_norm_noncartesian[CylindricalDifferential]", "astropy/coordinates/tests/test_representation.py::test_differential_norm_noncartesian[PhysicsSphericalDifferential]", "astropy/coordinates/tests/test_representation.py::test_differential_norm_noncartesian[UnitSphericalDifferential]", "astropy/coordinates/tests/test_representation.py::test_differential_norm_noncartesian[UnitSphericalCosLatDifferential]", "astropy/coordinates/tests/test_representation.py::test_differential_norm_radial" ]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> feat: fast-path physicsspherical to cylindrical - [ ] By checking this box, the PR author has requested that maintainers do **NOT** use the "Squash and Merge" button. Maintainers should respect this when possible; however, the final decision is at the discretion of the maintainer that merges the PR. ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in astropy/coordinates/representation/cylindrical.py] (definition of CylindricalRepresentation.represent_as:) def represent_as(self, other_class, differential_class=None): [end of new definitions in astropy/coordinates/representation/cylindrical.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
2d281019494aaebf522f6626c0dae37510c16688
pygments__pygments-2654
2,654
pygments/pygments
null
41a8a63c993affb665d193222d8da5fdb9ae173a
2024-02-25T22:46:46Z
diff --git a/AUTHORS b/AUTHORS index a7928ea88b..4ec64ba1ef 100644 --- a/AUTHORS +++ b/AUTHORS @@ -116,6 +116,8 @@ Other contributors, listed alphabetically, are: MSDOS session, BC, WDiff * Brian R. Jackson -- Tea lexer * Christian Jann -- ShellSession lexer +* Jonas Camillus Jeppesen -- Line numbers and line highlighting for + RTF-formatter * Dennis Kaarsemaker -- sources.list lexer * Dmitri Kabak -- Inferno Limbo lexer * Igor Kalnitsky -- vhdl lexer diff --git a/pygments/formatters/rtf.py b/pygments/formatters/rtf.py index 9905ca0045..ee0e581553 100644 --- a/pygments/formatters/rtf.py +++ b/pygments/formatters/rtf.py @@ -8,8 +8,10 @@ :license: BSD, see LICENSE for details. """ +from collections import OrderedDict from pygments.formatter import Formatter -from pygments.util import get_int_opt, surrogatepair +from pygments.style import _ansimap +from pygments.util import get_bool_opt, get_int_opt, get_list_opt, surrogatepair __all__ = ['RtfFormatter'] @@ -42,6 +44,59 @@ class RtfFormatter(Formatter): default is 24 half-points, giving a size 12 font. .. versionadded:: 2.0 + + `linenos` + Turn on line numbering (default: ``False``). + + .. versionadded:: 2.18 + + `lineno_fontsize` + Font size for line numbers. Size is specified in half points + (default: `fontsize`). + + .. versionadded:: 2.18 + + `lineno_padding` + Number of spaces between the (inline) line numbers and the + source code (default: ``2``). + + .. versionadded:: 2.18 + + `linenostart` + The line number for the first line (default: ``1``). + + .. versionadded:: 2.18 + + `linenostep` + If set to a number n > 1, only every nth line number is printed. + + .. versionadded:: 2.18 + + `lineno_color` + Color for line numbers specified as a hex triplet, e.g. ``'5e5e5e'``. + Defaults to the style's line number color if it is a hex triplet, + otherwise ansi bright black. + + .. versionadded:: 2.18 + + `hl_lines` + Specify a list of lines to be highlighted, as line numbers separated by + spaces, e.g. ``'3 7 8'``. The line numbers are relative to the input + (i.e. the first line is line 1) unless `hl_linenostart` is set. + + .. versionadded:: 2.18 + + `hl_color` + Color for highlighting the lines specified in `hl_lines`, specified as + a hex triplet (default: style's `highlight_color`). + + .. versionadded:: 2.18 + + `hl_linenostart` + If set to ``True`` line numbers in `hl_lines` are specified + relative to `linenostart` (default ``False``). + + .. versionadded:: 2.18 """ name = 'RTF' aliases = ['rtf'] @@ -62,6 +117,40 @@ def __init__(self, **options): Formatter.__init__(self, **options) self.fontface = options.get('fontface') or '' self.fontsize = get_int_opt(options, 'fontsize', 0) + self.linenos = get_bool_opt(options, 'linenos', False) + self.lineno_fontsize = get_int_opt(options, 'lineno_fontsize', + self.fontsize) + self.lineno_padding = get_int_opt(options, 'lineno_padding', 2) + self.linenostart = abs(get_int_opt(options, 'linenostart', 1)) + self.linenostep = abs(get_int_opt(options, 'linenostep', 1)) + self.hl_linenostart = get_bool_opt(options, 'hl_linenostart', False) + + self.hl_color = options.get('hl_color', '') + if not self.hl_color: + self.hl_color = self.style.highlight_color + + self.hl_lines = [] + for lineno in get_list_opt(options, 'hl_lines', []): + try: + lineno = int(lineno) + if self.hl_linenostart: + lineno = lineno - self.linenostart + 1 + self.hl_lines.append(lineno) + except ValueError: + pass + + self.lineno_color = options.get('lineno_color', '') + if not self.lineno_color: + if self.style.line_number_color == 'inherit': + # style color is the css value 'inherit' + # default to ansi bright-black + self.lineno_color = _ansimap['ansibrightblack'] + else: + # style color is assumed to be a hex triplet as other + # colors in pygments/style.py + self.lineno_color = self.style.line_number_color + + self.color_mapping = self._create_color_mapping() def _escape(self, text): return text.replace('\\', '\\\\') \ @@ -90,43 +179,147 @@ def _escape_text(self, text): # Force surrogate pairs buf.append('{\\u%d}{\\u%d}' % surrogatepair(cn)) - return ''.join(buf).replace('\n', '\\par\n') + return ''.join(buf).replace('\n', '\\par') - def format_unencoded(self, tokensource, outfile): - # rtf 1.8 header - outfile.write('{\\rtf1\\ansi\\uc0\\deff0' - '{\\fonttbl{\\f0\\fmodern\\fprq1\\fcharset0%s;}}' - '{\\colortbl;' % (self.fontface and - ' ' + self._escape(self.fontface) or - '')) - - # convert colors and save them in a mapping to access them later. - color_mapping = {} + @staticmethod + def hex_to_rtf_color(hex_color): + if hex_color[0] == "#": + hex_color = hex_color[1:] + + return '\\red%d\\green%d\\blue%d;' % ( + int(hex_color[0:2], 16), + int(hex_color[2:4], 16), + int(hex_color[4:6], 16) + ) + + def _split_tokens_on_newlines(self, tokensource): + """ + Split tokens containing newline characters into multiple token + each representing a line of the input file. Needed for numbering + lines of e.g. multiline comments. + """ + for ttype, value in tokensource: + if value == '\n': + yield (ttype, value) + elif "\n" in value: + lines = value.split("\n") + for line in lines[:-1]: + yield (ttype, line+"\n") + if lines[-1]: + yield (ttype, lines[-1]) + else: + yield (ttype, value) + + def _create_color_mapping(self): + """ + Create a mapping of style hex colors to index/offset in + the RTF color table. + """ + color_mapping = OrderedDict() offset = 1 + + if self.linenos: + color_mapping[self.lineno_color] = offset + offset += 1 + + if self.hl_lines: + color_mapping[self.hl_color] = offset + offset += 1 + for _, style in self.style: for color in style['color'], style['bgcolor'], style['border']: if color and color not in color_mapping: color_mapping[color] = offset - outfile.write('\\red%d\\green%d\\blue%d;' % ( - int(color[0:2], 16), - int(color[2:4], 16), - int(color[4:6], 16) - )) offset += 1 - outfile.write('}\\f0 ') + + return color_mapping + + @property + def _lineno_template(self): + if self.lineno_fontsize != self.fontsize: + return '{\\fs%s \\cf%s %%s%s}' \ + % (self.lineno_fontsize, + self.color_mapping[self.lineno_color], + " " * self.lineno_padding) + + return '{\\cf%s %%s%s}' \ + % (self.color_mapping[self.lineno_color], + " " * self.lineno_padding) + + @property + def _hl_open_str(self): + return r'{\highlight%s ' % self.color_mapping[self.hl_color] + + @property + def _rtf_header(self): + lines = [] + # rtf 1.8 header + lines.append('{\\rtf1\\ansi\\uc0\\deff0' + '{\\fonttbl{\\f0\\fmodern\\fprq1\\fcharset0%s;}}' + % (self.fontface and ' ' + + self._escape(self.fontface) or '')) + + # color table + lines.append('{\\colortbl;') + for color, _ in self.color_mapping.items(): + lines.append(self.hex_to_rtf_color(color)) + lines.append('}') + + # font and fontsize + lines.append('\\f0') if self.fontsize: - outfile.write('\\fs%d' % self.fontsize) + lines.append('\\fs%d' % self.fontsize) + + # ensure Libre Office Writer imports and renders consecutive + # space characters the same width, needed for line numbering. + # https://bugs.documentfoundation.org/show_bug.cgi?id=144050 + lines.append('\\dntblnsbdb') + + return lines + + def format_unencoded(self, tokensource, outfile): + for line in self._rtf_header: + outfile.write(line + "\n") + + tokensource = self._split_tokens_on_newlines(tokensource) + + # first pass of tokens to count lines, needed for line numbering + if self.linenos: + line_count = 0 + tokens = [] # for copying the token source generator + for ttype, value in tokensource: + tokens.append((ttype, value)) + if value.endswith("\n"): + line_count += 1 + + # width of line number strings (for padding with spaces) + linenos_width = len(str(line_count+self.linenostart-1)) + + tokensource = tokens # highlight stream + lineno = 1 + start_new_line = True for ttype, value in tokensource: + if start_new_line and lineno in self.hl_lines: + outfile.write(self._hl_open_str) + + if start_new_line and self.linenos: + if (lineno-self.linenostart+1)%self.linenostep == 0: + current_lineno = lineno + self.linenostart - 1 + lineno_str = str(current_lineno).rjust(linenos_width) + else: + lineno_str = "".rjust(linenos_width) + outfile.write(self._lineno_template % lineno_str) + while not self.style.styles_token(ttype) and ttype.parent: ttype = ttype.parent style = self.style.style_for_token(ttype) buf = [] if style['bgcolor']: - buf.append('\\cb%d' % color_mapping[style['bgcolor']]) + buf.append('\\cb%d' % self.color_mapping[style['bgcolor']]) if style['color']: - buf.append('\\cf%d' % color_mapping[style['color']]) + buf.append('\\cf%d' % self.color_mapping[style['color']]) if style['bold']: buf.append('\\b') if style['italic']: @@ -135,12 +328,24 @@ def format_unencoded(self, tokensource, outfile): buf.append('\\ul') if style['border']: buf.append('\\chbrdr\\chcfpat%d' % - color_mapping[style['border']]) + self.color_mapping[style['border']]) start = ''.join(buf) if start: outfile.write('{%s ' % start) outfile.write(self._escape_text(value)) if start: outfile.write('}') + start_new_line = False + + # complete line of input + if value.endswith("\n"): + # close line highlighting + if lineno in self.hl_lines: + outfile.write('}') + # newline in RTF file after closing } + outfile.write("\n") + + start_new_line = True + lineno += 1 - outfile.write('}') + outfile.write('}\n')
diff --git a/tests/test_rtf_formatter.py b/tests/test_rtf_formatter.py index a21939f043..6379e37d16 100644 --- a/tests/test_rtf_formatter.py +++ b/tests/test_rtf_formatter.py @@ -7,12 +7,17 @@ """ from io import StringIO +import itertools +import re +import pytest from pygments.formatters import RtfFormatter +from pygments.lexers import CppLexer, PythonLexer from pygments.lexers.special import TextLexer +from pygments.style import _ansimap, Style +from pygments.token import Name, String, Token - -foot = (r'\par' '\n' r'}') +foot = r'\par' '\n' r'}' + '\n' def _escape(string): @@ -26,9 +31,9 @@ def _build_message(*args, **kwargs): result = _escape(kwargs.get('result', '')) if string is None: - string = ("The expected output of '{t}'\n" - "\t\tShould be '{expected}'\n" - "\t\tActually outputs '{result}'\n" + string = ("The expected output of '{t}'\n\n" + "\t\tShould be '{expected}'\n\n" + "\t\tActually outputs '{result}'\n\n" "\t(WARNING: Partial Output of Result!)") end = -len(_escape(foot)) @@ -39,9 +44,11 @@ def _build_message(*args, **kwargs): expected = expected) -def format_rtf(t): - tokensource = list(TextLexer().get_tokens(t)) - fmt = RtfFormatter() +def format_rtf(t, options=None, lexer=TextLexer): + if options is None: + options = {} + tokensource = lexer().get_tokens(t) + fmt = RtfFormatter(**options) buf = StringIO() fmt.format(tokensource, buf) result = buf.getvalue() @@ -49,6 +56,17 @@ def format_rtf(t): return result +def extract_color_table(rtf): + r""" + Return af list of \redR\greenG\blueB; color definitions + extracted from the input (the color table). + """ + return re.findall((r"\\red[0-9]{1,3}" + r"\\green[0-9]{1,3}" + r"\\blue[0-9]{1,3};"), + rtf) + + def test_rtf_header(): t = '' result = format_rtf(t) @@ -72,7 +90,7 @@ def test_rtf_footer(): def test_ascii_characters(): t = 'a b c d ~' result = format_rtf(t) - expected = (r'a b c d ~') + expected = r'a b c d ~' msg = _build_message(t=t, result=result, expected=expected) assert result.endswith(expected+foot), msg @@ -101,3 +119,434 @@ def test_double_characters(): r'{\u8597}{\u65038} {\u55422}{\u56859}') msg = _build_message(t=t, result=result, expected=expected) assert result.endswith(expected+foot), msg + + +def test_linenos_all_defaults(): + t = 'line1\nline2\n' + options = {} + result = format_rtf(t, options) + expected = (r'line1\par' + '\n' + r'line2\par' + '\n' + r'}' + '\n') + msg = _build_message(t=t, result=result, expected=expected) + assert result.endswith(expected), msg + + +def test_linenos_text(): + t = 'line1\nline2\n' + options = dict(linenos=True, lineno_padding=2) + result = format_rtf(t, options) + expected = (r'{\cf1 1 }line1\par' + '\n' + r'{\cf1 2 }line2\par' + '\n' + r'}' + '\n') + msg = _build_message(t=t, result=result, expected=expected) + assert result.endswith(expected), msg + + +def test_linenos_newline_characters(): + t = r'line1\nline2' + '\n' + options = dict(linenos=True, lineno_padding=2) + result = format_rtf(t, options) + expected = (r'{\cf1 1 }line1\\nline2\par' + '\n' + r'}' + '\n') + msg = _build_message(t=t, result=result, expected=expected) + assert result.endswith(expected), msg + + +def test_linenos_python(): + class TestStyle(Style): + name = 'rtf_formatter_test' + line_number_color = "#ff0000" + styles = {Token: '', String: '#00ff00', Name: '#0000ff'} + + t = r's = "line1\nline2"' + '\n' + options = dict(linenos=True, lineno_padding=2, style=TestStyle) + result = format_rtf(t, options, PythonLexer) + expected = (r'{\rtf1\ansi\uc0\deff0{\fonttbl{\f0\fmodern\fprq1\fcharset0;}}' + '\n' + r'{\colortbl;' + '\n' + r'\red255\green0\blue0;' + '\n' + r'\red0\green255\blue0;' + '\n' + r'\red0\green0\blue255;' + '\n' + r'}' + '\n' + r'\f0' + '\n' + r'\dntblnsbdb' + '\n' + r'{\cf1 1 }{\cf3 s} = {\cf2 "}{\cf2 line1}{\cf2 \\n}{\cf2 line2}{\cf2 "}\par' + '\n' + r'}' + '\n') + msg = _build_message(t=t, result=result, expected=expected) + assert result.endswith(expected), msg + + +def test_linenos_left_padding(): + t = '0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n' + options = dict(linenos=True, lineno_padding=2) + result = format_rtf(t, options) + expected = (r'{\cf1 9 }8\par' + '\n' + r'{\cf1 10 }9\par' + '\n' + r'}' + '\n') + msg = _build_message(t=t, result=result, expected=expected) + assert result.endswith(expected), msg + + +def test_lineno_padding(): + t = 'line1\nline2\n' + options = dict(linenos=True, lineno_padding=3) + result = format_rtf(t, options) + expected = (r'{\cf1 1 }line1\par' + '\n' + r'{\cf1 2 }line2\par' + '\n' + r'}' + '\n') + msg = _build_message(t=t, result=result, expected=expected) + assert result.endswith(expected), msg + + +def test_linenostep(): + t = 'line1\nline2\nline3\nline4\n' + options = dict(linenos=True, + linenostep=2, + lineno_padding=2) + result = format_rtf(t, options) + expected = (r'{\cf1 }line1\par' + '\n' + r'{\cf1 2 }line2\par' + '\n' + r'{\cf1 }line3\par' + '\n' + r'{\cf1 4 }line4\par' + '\n' + r'}' + '\n') + msg = _build_message(t=t, result=result, expected=expected) + assert result.endswith(expected), msg + + +def test_linenostart(): + t = 'line1\nline2\nline3\nline4\n' + options = dict(linenos=True, + linenostart=3, + lineno_padding=2) + result = format_rtf(t, options) + expected = (r'{\cf1 3 }line1\par' + '\n' + r'{\cf1 4 }line2\par' + '\n' + r'{\cf1 5 }line3\par' + '\n' + r'{\cf1 6 }line4\par' + '\n' + r'}' + '\n') + msg = _build_message(t=t, result=result, expected=expected) + assert result.endswith(expected), msg + + +def test_linenostart_left_padding(): + t = 'line1\nline2\nline3\n' + options = dict(linenos=True, + linenostart=98, + lineno_padding=2) + result = format_rtf(t, options) + expected = (r'{\cf1 98 }line1\par' + '\n' + r'{\cf1 99 }line2\par' + '\n' + r'{\cf1 100 }line3\par' + '\n' + r'}' + '\n') + msg = _build_message(t=t, result=result, expected=expected) + assert result.endswith(expected), msg + + +def test_linenos_hl_lines(): + t = 'line1\nline2\nline3\n' + options = dict(linenos=True, + hl_lines="2 3", + lineno_padding=2) + result = format_rtf(t, options) + expected = (r'{\cf1 1 }line1\par' + '\n' + r'{\highlight2 {\cf1 2 }line2\par}' + '\n' + r'{\highlight2 {\cf1 3 }line3\par}' + '\n' + r'}' + '\n') + msg = _build_message(t=t, result=result, expected=expected) + assert result.endswith(expected), msg + + +def test_linenos_off_hl_lines(): + t = 'line1\nline2\nline3\n' + options = dict(linenos=False, + hl_lines="2 3") + result = format_rtf(t, options) + expected = (r'line1\par' + '\n' + r'{\highlight1 line2\par}' + '\n' + r'{\highlight1 line3\par}' + '\n' + r'}' + '\n') + msg = _build_message(t=t, result=result, expected=expected) + assert result.endswith(expected), msg + + +def test_hl_linenostart_no_lines_highlighted(): + t = 'line11\nline12\nline13\n' + options = dict(linenos=False, + hl_lines="2 3", + hl_linenostart=True, + linenostart=11) + result = format_rtf(t, options) + expected = (r'line11\par' + '\n' + r'line12\par' + '\n' + r'line13\par' + '\n' + r'}' + '\n') + msg = _build_message(t=t, result=result, expected=expected) + assert result.endswith(expected), msg + + +def test_hl_linenostart_lines_highlighted(): + t = 'line11\nline12\nline13\n' + options = dict(linenos=False, + hl_lines="12 13", + hl_linenostart=True, + linenostart=11) + result = format_rtf(t, options) + expected = (r'line11\par' + '\n' + r'{\highlight1 line12\par}' + '\n' + r'{\highlight1 line13\par}' + '\n' + r'}' + '\n') + msg = _build_message(t=t, result=result, expected=expected) + assert result.endswith(expected), msg + + +def test_lineno_color_style_specify_hex(): + class TestStyle(Style): + name = 'rtf_formatter_test' + line_number_color = "#123456" + + t = 'line1\nline2\n' + options = dict(linenos=True, + style=TestStyle) + result = format_rtf(t, options) + rtf_color_str = RtfFormatter.hex_to_rtf_color(TestStyle.line_number_color) + color_tbl = extract_color_table(result) + msg = (f"Color table {color_tbl} " + f"should have '{rtf_color_str}' " + "as first entry") + + # With linenos=True the color table should contain: + # 1st entry: line number color (hence \cf1) + assert color_tbl[0] == rtf_color_str, msg + + +def test_lineno_color_style_specify_inherit(): + class TestStyle(Style): + name = 'rtf_formatter_test' + line_number_color = "inherit" # Default from pygments/style.py + + t = 'line1\nline2\n' + options = dict(linenos=True, + style=TestStyle) + result = format_rtf(t, options) + rtf_color_str = RtfFormatter.hex_to_rtf_color(_ansimap['ansibrightblack']) + color_tbl = extract_color_table(result) + msg = (f"Color table {color_tbl} " + f"should have '{rtf_color_str}' " + "as first entry") + + # With linenos=True the color table should contain: + # 1st entry: line number color (hence \cf1) + assert color_tbl[0] == rtf_color_str, msg + + +def test_lineno_color_from_cli_option(): + class TestStyle(Style): + name = 'rtf_formatter_test' + line_number_color = "#123456" # Default from pygments/style.py + + option_color = "112233" + t = 'line1\nline2\n' + options = dict(linenos=True, + style=TestStyle, + lineno_color=option_color) + result = format_rtf(t, options) + rtf_color_str = RtfFormatter.hex_to_rtf_color(option_color) + color_tbl = extract_color_table(result) + msg = (f"Color table {color_tbl} " + f"should have '{rtf_color_str}' " + "as first entry") + + # With linenos=True the color table should contain: + # 1st entry: line number color (hence \cf1) + assert color_tbl[0] == rtf_color_str, msg + + +def test_hl_color_style(): + class TestStyle(Style): + name = 'rtf_formatter_test' + line_number_color = "#123456" + highlight_color = "#abcdef" + + t = 'line1\nline2\n' + options = dict(linenos=True, + lineno_padding=2, + style=TestStyle, + hl_lines="1 2") + result = format_rtf(t, options) + + rtf_color = RtfFormatter.hex_to_rtf_color(TestStyle.highlight_color) + + color_tbl = extract_color_table(result) + msg = (f"Color table {color_tbl} " + f"should have '{rtf_color}' " + "as second entry") + + # With linenos=True and hl_lines="1 2" the color table should contain: + # 1st entry: line number color (hence \cf1) + # 2nd entry: highlight color (hence \highlight2) + assert color_tbl[1] == rtf_color, msg + + expected = (r'{\highlight2 {\cf1 1 }line1\par}' + '\n' + r'{\highlight2 {\cf1 2 }line2\par}' + '\n' + r'}' + '\n') + msg = _build_message(t=t, result=result, expected=expected) + + assert result.endswith(expected), msg + + +def test_hl_color_style_no_linenos(): + class TestStyle(Style): + name = 'rtf_formatter_test' + line_number_color = "#123456" + highlight_color = "#abcdef" + + t = 'line1\nline2\n' + options = dict(linenos=False, + style=TestStyle, + hl_lines="1 2") + result = format_rtf(t, options) + + rtf_color = RtfFormatter.hex_to_rtf_color(TestStyle.highlight_color) + + color_tbl = extract_color_table(result) + msg = (f"Color table {color_tbl} " + f"should have '{rtf_color}' " + "as second entry") + + # With linenos=False and hl_lines="1 2" the color table should contain: + # 1st entry: highlight color (hence \highlight1) + assert rtf_color in color_tbl and color_tbl[0] == rtf_color, msg + + expected = (r'{\highlight1 line1\par}' + '\n' + r'{\highlight1 line2\par}' + '\n' + r'}' + '\n') + msg = _build_message(t=t, result=result, expected=expected) + + assert result.endswith(expected), msg + + +def test_hl_color_option(): + class TestStyle(Style): + name = 'rtf_formatter_test' + line_number_color = "#123456" + highlight_color = "#abcdef" + + t = 'line1\nline2\n' + hl_color = "aabbcc" + options = dict(linenos=False, + style=TestStyle, + hl_lines="1 2", + hl_color=hl_color) + result = format_rtf(t, options) + + rtf_color = RtfFormatter.hex_to_rtf_color(hl_color) + + color_tbl = extract_color_table(result) + msg = (f"Color table {color_tbl} " + f"should have '{rtf_color}' " + "as second entry") + + # With linenos=False and hl_lines="1 2" the color table should contain: + # 1st entry: highlight color (hence \highlight1) + assert rtf_color in color_tbl and color_tbl[0] == rtf_color, msg + + expected = (r'{\highlight1 line1\par}' + '\n' + r'{\highlight1 line2\par}' + '\n' + r'}' + '\n') + msg = _build_message(t=t, result=result, expected=expected) + + assert result.endswith(expected), msg + + +def test_all_options(): + # Test if all combinations of options (given values and defaults) + # produce output: + # + # - No uncaught exceptions + # - Output contains one \par control word per input line + + def get_option_combinations(options): + for _, values in options.items(): + values.append('default') + # https://stackoverflow.com/a/40623158 + combinations = (dict(zip(options.keys(), x)) + for x in itertools.product(*options.values())) + for c in combinations: + yield {opt:val for opt,val in c.items() if val!='default'} + + options = {'linenos': [True], + 'lineno_fontsize': [36], + 'fontsize': [36], + 'lineno_padding': [4], + 'linenostart': [10], + 'linenostep': [3], + 'lineno_color': ['ff0000'], + 'hl_lines': ['2'], + 'hl_linenostart': [True], + 'hl_color': ['00ff00'] + } + + t_cpp = [r'#include <iostream>', + r'int main(int argc, char** argv) {', + r' /* Multi-line comment', + r' with \n escape sequence */' + r' for (int i = 0; i < argc; i++){', + r' std::cout << i << ": " << argv[i] << "\n";', + r' }', + r' return 0;', + r'}' + ] + + t_python = [r'# Description of program', + r'def add(a, b):', + r' """ Add numbers a and b.', + r' Newline \n in docstring."""', + r' return a+b', + r'if __name__ == "__main__":', + r'result = add(2,2)', + r'print(f"Result:\n{result}")' + ] + + t_text = [r'Header1;"Long', + r'Header2";Header3', + r'1,2;Single Line;20/02/2024', + r'1,3;"Multiple', + r'Lines";21/02/2024'] + + + for opts in get_option_combinations(options): + + opt_strs = '\n'.join([f"{k}: {v}" for k,v in opts.items()]) + opt_str_for_copying = "-O " + ",".join([f"{k}={v}" for k,v in opts.items()]) + + for t, lexer in [(t_cpp, CppLexer), + (t_python, PythonLexer), + (t_text, TextLexer)]: + + input_text = '\n'.join(t) + '\n' # Last line should end in \n + + try: + result = format_rtf(input_text, opts,lexer) + except Exception as e: + msg = (f"RTF-formatting caused an exception with options\n\n" + f"{opt_strs}\n\n" + f"{opt_str_for_copying}\n\n" + f"Lexer: {lexer.__name__}\n\n" + f"Input:\n" + f"{input_text}\n" + f"{type(e)}: {e}\n") + + pytest.fail(msg) + + num_input_lines = len(t) + num_of_pars = result.count(r'\par') + + msg = (f"Different of number of input lines and formatted lines:\n" + f"{opt_strs}\n\n" + f"{opt_str_for_copying}\n\n" + f"\\par control words: {num_of_pars}\n" + f"Input lines: {num_input_lines}\n\n" + f"Input:\n" + f"{input_text}\n") + + assert num_of_pars == num_input_lines, msg
diff --git a/AUTHORS b/AUTHORS index a7928ea88b..4ec64ba1ef 100644 --- a/AUTHORS +++ b/AUTHORS @@ -116,6 +116,8 @@ Other contributors, listed alphabetically, are: MSDOS session, BC, WDiff * Brian R. Jackson -- Tea lexer * Christian Jann -- ShellSession lexer +* Jonas Camillus Jeppesen -- Line numbers and line highlighting for + RTF-formatter * Dennis Kaarsemaker -- sources.list lexer * Dmitri Kabak -- Inferno Limbo lexer * Igor Kalnitsky -- vhdl lexer
[ { "components": [ { "doc": "", "lines": [ 185, 192 ], "name": "RtfFormatter.hex_to_rtf_color", "signature": "def hex_to_rtf_color(hex_color):", "type": "function" }, { "doc": "Split tokens containing newline characters into multiple token\neach representing a line of the input file. Needed for numbering\nlines of e.g. multiline comments.", "lines": [ 195, 211 ], "name": "RtfFormatter._split_tokens_on_newlines", "signature": "def _split_tokens_on_newlines(self, tokensource):", "type": "function" }, { "doc": "Create a mapping of style hex colors to index/offset in\nthe RTF color table.", "lines": [ 213, 235 ], "name": "RtfFormatter._create_color_mapping", "signature": "def _create_color_mapping(self):", "type": "function" }, { "doc": "", "lines": [ 238, 247 ], "name": "RtfFormatter._lineno_template", "signature": "def _lineno_template(self):", "type": "function" }, { "doc": "", "lines": [ 250, 251 ], "name": "RtfFormatter._hl_open_str", "signature": "def _hl_open_str(self):", "type": "function" }, { "doc": "", "lines": [ 254, 278 ], "name": "RtfFormatter._rtf_header", "signature": "def _rtf_header(self):", "type": "function" } ], "file": "pygments/formatters/rtf.py" } ]
[ "tests/test_rtf_formatter.py::test_rtf_footer", "tests/test_rtf_formatter.py::test_ascii_characters", "tests/test_rtf_formatter.py::test_escape_characters", "tests/test_rtf_formatter.py::test_single_characters", "tests/test_rtf_formatter.py::test_double_characters", "tests/test_rtf_formatter.py::test_linenos_all_defaults", "tests/test_rtf_formatter.py::test_linenos_text", "tests/test_rtf_formatter.py::test_linenos_newline_characters", "tests/test_rtf_formatter.py::test_linenos_python", "tests/test_rtf_formatter.py::test_linenos_left_padding", "tests/test_rtf_formatter.py::test_lineno_padding", "tests/test_rtf_formatter.py::test_linenostep", "tests/test_rtf_formatter.py::test_linenostart", "tests/test_rtf_formatter.py::test_linenostart_left_padding", "tests/test_rtf_formatter.py::test_linenos_hl_lines", "tests/test_rtf_formatter.py::test_linenos_off_hl_lines", "tests/test_rtf_formatter.py::test_hl_linenostart_no_lines_highlighted", "tests/test_rtf_formatter.py::test_hl_linenostart_lines_highlighted", "tests/test_rtf_formatter.py::test_lineno_color_style_specify_hex", "tests/test_rtf_formatter.py::test_lineno_color_style_specify_inherit", "tests/test_rtf_formatter.py::test_lineno_color_from_cli_option", "tests/test_rtf_formatter.py::test_hl_color_style", "tests/test_rtf_formatter.py::test_hl_color_style_no_linenos", "tests/test_rtf_formatter.py::test_hl_color_option" ]
[ "tests/test_rtf_formatter.py::test_rtf_header", "tests/test_rtf_formatter.py::test_all_options" ]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> Add line numbers and line highlighting to the RTF-formatter Finally implemented line numbers and line highlighting as discussed in issue #1217. ![Screenshot from 2024-02-25 23-01-27](https://github.com/pygments/pygments/assets/3301843/efbb744a-99ff-4561-a4ac-387bb2f488c2) If desirable, I could use f-strings instead of `%`-based string formatting while we're at it (maybe capitalize comments). I chose not to because it is not directly related to the issue. Merging this would cause https://github.com/pygments/pygments/pull/2607 to need a minor rewrite. `\\sa0` would need to be added to [rtf.py#L269](https://github.com/jonascj/pygments/blob/83019842402a743b3b6828b73b61840c25bf0ae3/pygments/formatters/rtf.py#L269) ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in pygments/formatters/rtf.py] (definition of RtfFormatter.hex_to_rtf_color:) def hex_to_rtf_color(hex_color): (definition of RtfFormatter._split_tokens_on_newlines:) def _split_tokens_on_newlines(self, tokensource): """Split tokens containing newline characters into multiple token each representing a line of the input file. Needed for numbering lines of e.g. multiline comments.""" (definition of RtfFormatter._create_color_mapping:) def _create_color_mapping(self): """Create a mapping of style hex colors to index/offset in the RTF color table.""" (definition of RtfFormatter._lineno_template:) def _lineno_template(self): (definition of RtfFormatter._hl_open_str:) def _hl_open_str(self): (definition of RtfFormatter._rtf_header:) def _rtf_header(self): [end of new definitions in pygments/formatters/rtf.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
e08bdbba2fa78270dba5ca700d053569f85d0351
conan-io__conan-15731
15,731
conan-io/conan
null
1763159dc74a54cb4920a55a7620557687e1dc25
2024-02-22T07:51:29Z
diff --git a/conan/tools/build/__init__.py b/conan/tools/build/__init__.py index 829886a8de3..da2223ff12e 100644 --- a/conan/tools/build/__init__.py +++ b/conan/tools/build/__init__.py @@ -3,3 +3,4 @@ from conan.tools.build.cppstd import check_min_cppstd, valid_min_cppstd, default_cppstd, \ supported_cppstd from conan.tools.build.stdcpp_library import stdcpp_library +from conan.tools.build.flags import cppstd_flag diff --git a/conan/tools/build/flags.py b/conan/tools/build/flags.py new file mode 100644 index 00000000000..9cd9f06385a --- /dev/null +++ b/conan/tools/build/flags.py @@ -0,0 +1,16 @@ +from conan.tools._compilers import cppstd_flag as cppstd_flag_settings + + +def cppstd_flag(conanfile): + """ + Returns flags specific to the C++ standard based on the ``conanfile.settings.compiler``, + ``conanfile.settings.compiler.version`` and ``conanfile.settings.compiler.cppstd``. + It also considers when using GNU extension in ``settings.compiler.cppstd``, reflecting it in the + compiler flag. Currently, it supports GCC, Clang, AppleClang, MSVC, Intel, MCST-LCC. + In case there is no ``settings.compiler`` or ``settings.cppstd`` in the profile, the result will + be an **empty string**. + :param conanfile: The current recipe object. Always use ``self``. + :return: ``str`` with the standard C++ flag used by the compiler. e.g. "-std=c++11", "/std:c++latest" + """ + settings = conanfile.settings + return cppstd_flag_settings(settings)
diff --git a/conans/test/unittests/client/build/cpp_std_flags_test.py b/conans/test/unittests/client/build/cpp_std_flags_test.py index 1badf2c90ab..3c30e83717a 100644 --- a/conans/test/unittests/client/build/cpp_std_flags_test.py +++ b/conans/test/unittests/client/build/cpp_std_flags_test.py @@ -1,9 +1,11 @@ import unittest from conans.client.build.cppstd_flags import cppstd_default -from conans.test.utils.mocks import MockSettings +from conans.test.utils.mocks import MockSettings, ConanFileMock from conans.tools import cppstd_flag +from conan.tools.build import cppstd_flag as cppstd_flag_conanfile + def _make_cppstd_flag(compiler, compiler_version, cppstd=None, compiler_base=None): settings = MockSettings({"compiler": compiler, @@ -399,3 +401,12 @@ def test_mcst_lcc_cppstd_flag(self): self.assertEqual(_make_cppstd_flag("mcst-lcc", "1.25", "14", "gcc"), "-std=c++14") self.assertEqual(_make_cppstd_flag("mcst-lcc", "1.25", "17", "gcc"), "-std=c++17") self.assertEqual(_make_cppstd_flag("mcst-lcc", "1.25", "20", "gcc"), "-std=c++2a") + + def test_cppstd_flag_conanfile(self): + """The conan.tools.build.cppstd_flag should work when passing a ConanFile instance + """ + conanfile = ConanFileMock() + conanfile.settings = MockSettings({"compiler": "gcc", + "compiler.version": "9", + "compiler.cppstd": "17"}) + self.assertEqual(cppstd_flag_conanfile(conanfile), "-std=c++17")
[ { "components": [ { "doc": "Returns flags specific to the C++ standard based on the ``conanfile.settings.compiler``,\n``conanfile.settings.compiler.version`` and ``conanfile.settings.compiler.cppstd``.\nIt also considers when using GNU extension in ``settings.compiler.cppstd``, reflecting it in the\ncompiler flag. Currently, it supports GCC, Clang, AppleClang, MSVC, Intel, MCST-LCC.\nIn case there is no ``settings.compiler`` or ``settings.cppstd`` in the profile, the result will\nbe an **empty string**.\n:param conanfile: The current recipe object. Always use ``self``.\n:return: ``str`` with the standard C++ flag used by the compiler. e.g. \"-std=c++11\", \"/std:c++latest\"", "lines": [ 4, 16 ], "name": "cppstd_flag", "signature": "def cppstd_flag(conanfile):", "type": "function" } ], "file": "conan/tools/build/flags.py" } ]
[ "conans/test/unittests/client/build/cpp_std_flags_test.py::CompilerFlagsTest::test_apple_clang_cppstd_defaults", "conans/test/unittests/client/build/cpp_std_flags_test.py::CompilerFlagsTest::test_apple_clang_cppstd_flags", "conans/test/unittests/client/build/cpp_std_flags_test.py::CompilerFlagsTest::test_clang_cppstd_defaults", "conans/test/unittests/client/build/cpp_std_flags_test.py::CompilerFlagsTest::test_clang_cppstd_flags", "conans/test/unittests/client/build/cpp_std_flags_test.py::CompilerFlagsTest::test_cppstd_flag_conanfile", "conans/test/unittests/client/build/cpp_std_flags_test.py::CompilerFlagsTest::test_gcc_cppstd_defaults", "conans/test/unittests/client/build/cpp_std_flags_test.py::CompilerFlagsTest::test_gcc_cppstd_flags", "conans/test/unittests/client/build/cpp_std_flags_test.py::CompilerFlagsTest::test_intel_gcc_cppstd_defaults", "conans/test/unittests/client/build/cpp_std_flags_test.py::CompilerFlagsTest::test_intel_gcc_cppstd_flag", "conans/test/unittests/client/build/cpp_std_flags_test.py::CompilerFlagsTest::test_intel_visual_cppstd_defaults", "conans/test/unittests/client/build/cpp_std_flags_test.py::CompilerFlagsTest::test_intel_visual_cppstd_flag", "conans/test/unittests/client/build/cpp_std_flags_test.py::CompilerFlagsTest::test_mcst_lcc_cppstd_defaults", "conans/test/unittests/client/build/cpp_std_flags_test.py::CompilerFlagsTest::test_mcst_lcc_cppstd_flag", "conans/test/unittests/client/build/cpp_std_flags_test.py::CompilerFlagsTest::test_visual_cppstd_defaults", "conans/test/unittests/client/build/cpp_std_flags_test.py::CompilerFlagsTest::test_visual_cppstd_flags" ]
[]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> Backport cppstd_flag from Conan 2.x Related to the PR #15710, this PR backports the method available in Conan 2.x In Conan 1.x we have [cppstd_flag](https://docs.conan.io/1/reference/tools.html#tools-cppstd-flag) available already, but it receives `settings` only is under `conans.tools`. This change creates a wrapper to make it available under `conan.tools.build` and should pass `conanfile` instead. Changelog: Feature: Promote cppstd_flag in the new conan.tools.build module. Docs: https://github.com/conan-io/docs/pull/3602 - [x] Refer to the issue that supports this Pull Request. - [x] If the issue has missing info, explain the purpose/use case/pain/need that covers this Pull Request. - [x] I've read the [Contributing guide](https://github.com/conan-io/conan/blob/develop/.github/CONTRIBUTING.md). - [x] I've followed the PEP8 style guides for Python code. - [x] I've opened another PR in the Conan docs repo to the ``develop`` branch, documenting this one. ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in conan/tools/build/flags.py] (definition of cppstd_flag:) def cppstd_flag(conanfile): """Returns flags specific to the C++ standard based on the ``conanfile.settings.compiler``, ``conanfile.settings.compiler.version`` and ``conanfile.settings.compiler.cppstd``. It also considers when using GNU extension in ``settings.compiler.cppstd``, reflecting it in the compiler flag. Currently, it supports GCC, Clang, AppleClang, MSVC, Intel, MCST-LCC. In case there is no ``settings.compiler`` or ``settings.cppstd`` in the profile, the result will be an **empty string**. :param conanfile: The current recipe object. Always use ``self``. :return: ``str`` with the standard C++ flag used by the compiler. e.g. "-std=c++11", "/std:c++latest"""" [end of new definitions in conan/tools/build/flags.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
4a5b19a75db9225316c8cb022a2dfb9705a2af34
deepset-ai__haystack-7009
7,009
deepset-ai/haystack
null
a7209f64136d7cc8bd446f6801d8695fc367608f
2024-02-16T09:06:38Z
diff --git a/haystack/dataclasses/byte_stream.py b/haystack/dataclasses/byte_stream.py index 80b1c50c3b..ee736c001d 100644 --- a/haystack/dataclasses/byte_stream.py +++ b/haystack/dataclasses/byte_stream.py @@ -49,3 +49,13 @@ def from_string( :param meta: Additional metadata to be stored with the ByteStream. """ return cls(data=text.encode(encoding), mime_type=mime_type, meta=meta or {}) + + def to_string(self, encoding: str = "utf-8") -> str: + """ + Convert the ByteStream to a string, metadata will not be included. + + :param encoding: The encoding used to convert the bytes to a string. Defaults to "utf-8". + :return: The string representation of the ByteStream. + :raises UnicodeDecodeError: If the ByteStream data cannot be decoded with the specified encoding. + """ + return self.data.decode(encoding)
diff --git a/test/dataclasses/test_byte_stream.py b/test/dataclasses/test_byte_stream.py index 57d444b038..4e4199ba19 100644 --- a/test/dataclasses/test_byte_stream.py +++ b/test/dataclasses/test_byte_stream.py @@ -1,3 +1,5 @@ +import pytest + from haystack.dataclasses import ByteStream @@ -35,6 +37,30 @@ def test_from_string(): assert b.meta == {"foo": "bar"} +def test_to_string(): + test_string = "Hello, world!" + b = ByteStream.from_string(test_string) + assert b.to_string() == test_string + + +def test_to_from_string_encoding(): + test_string = "Hello Baščaršija!" + with pytest.raises(UnicodeEncodeError): + ByteStream.from_string(test_string, encoding="ISO-8859-1") + + bs = ByteStream.from_string(test_string) # default encoding is utf-8 + + assert bs.to_string(encoding="ISO-8859-1") != test_string + assert bs.to_string(encoding="utf-8") == test_string + + +def test_to_string_encoding_error(): + # test that it raises ValueError if the encoding is not valid + b = ByteStream.from_string("Hello, world!") + with pytest.raises(UnicodeDecodeError): + b.to_string("utf-16") + + def test_to_file(tmp_path, request): test_str = "Hello, world!\n" test_path = tmp_path / request.node.name
[ { "components": [ { "doc": "Convert the ByteStream to a string, metadata will not be included.\n\n:param encoding: The encoding used to convert the bytes to a string. Defaults to \"utf-8\".\n:return: The string representation of the ByteStream.\n:raises UnicodeDecodeError: If the ByteStream data cannot be decoded with the specified encoding.", "lines": [ 53, 61 ], "name": "ByteStream.to_string", "signature": "def to_string(self, encoding: str = \"utf-8\") -> str:", "type": "function" } ], "file": "haystack/dataclasses/byte_stream.py" } ]
[ "test/dataclasses/test_byte_stream.py::test_to_string", "test/dataclasses/test_byte_stream.py::test_to_from_string_encoding", "test/dataclasses/test_byte_stream.py::test_to_string_encoding_error" ]
[ "test/dataclasses/test_byte_stream.py::test_from_file_path", "test/dataclasses/test_byte_stream.py::test_from_string", "test/dataclasses/test_byte_stream.py::test_to_file" ]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> feat: Add ByteStream to_string method ### Why: Adds `to_string` method in the `ByteStream` class which arises from the requirement to convert byte data back into its original string format for certain use cases. This enhancement provides a convenient and intuitive way to achieve this, enriching the class's functionalities. In addition, we already have a method from_string that creates a ByteStream instance from a string by encoding it to bytes. A to_string method provides the symmetric operation, converting the byte stream to a string. This symmetry in API design improves intuitiveness and usability. ### What: * A new method named `to_string` has been added to the `ByteStream` class in `haystack/dataclasses/byte_stream.py`, enabling conversion of byte data to its original string representation. * The method accepts an optional encoding parameter for controlling the decoding process and defaults to `utf-8`. * Custom error handling, specifically a `UnicodeDecodeError`, is implemented to ensure graceful failure in case of encoding issues. ### How can it be used: * The `to_string` method can be applied to `ByteStream` instances when users wish to extract the original text content. Example usage: ```python bs = ByteStream.from_string('hello, world!') text = bs.to_string() assert text == 'hello, world!' ``` ### How did you test it: * Unit tests have been added to `test/dataclasses/test_byte_stream.py` verifying correct functionality of the `to_string` method in different scenarios, including valid and invalid encoding cases. ### Notes for the reviewer: * The changes mainly concern the `ByteStream` class and its test class, keeping the impact localized. ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in haystack/dataclasses/byte_stream.py] (definition of ByteStream.to_string:) def to_string(self, encoding: str = "utf-8") -> str: """Convert the ByteStream to a string, metadata will not be included. :param encoding: The encoding used to convert the bytes to a string. Defaults to "utf-8". :return: The string representation of the ByteStream. :raises UnicodeDecodeError: If the ByteStream data cannot be decoded with the specified encoding.""" [end of new definitions in haystack/dataclasses/byte_stream.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
f4d9c2bb917be0ffe132dffcc2ad4f1b0fcc5967
roboflow__supervision-910
910
roboflow/supervision
null
0c0685987a57ffbcff8eea89bb16aff70846403e
2024-02-15T21:29:25Z
diff --git a/supervision/detection/tools/polygon_zone.py b/supervision/detection/tools/polygon_zone.py index c6f5b80e6..1357b03c2 100644 --- a/supervision/detection/tools/polygon_zone.py +++ b/supervision/detection/tools/polygon_zone.py @@ -1,5 +1,5 @@ from dataclasses import replace -from typing import Optional, Tuple +from typing import Iterable, Optional, Tuple import cv2 import numpy as np @@ -10,6 +10,7 @@ from supervision.draw.utils import draw_polygon, draw_text from supervision.geometry.core import Position from supervision.geometry.utils import get_polygon_center +from supervision.utils.internal import deprecated_parameter class PolygonZone: @@ -20,21 +21,33 @@ class PolygonZone: polygon (np.ndarray): A polygon represented by a numpy array of shape `(N, 2)`, containing the `x`, `y` coordinates of the points. frame_resolution_wh (Tuple[int, int]): The frame resolution (width, height) - triggering_position (Position): The position within the bounding - box that triggers the zone (default: Position.BOTTOM_CENTER) + triggering_anchors (Iterable[sv.Position]): A list of positions specifying + which anchors of the detections bounding box to consider when deciding on + whether the detection fits within the PolygonZone + (default: (sv.Position.BOTTOM_CENTER,)). current_count (int): The current count of detected objects within the zone mask (np.ndarray): The 2D bool mask for the polygon zone """ + @deprecated_parameter( + old_parameter="triggering_position", + new_parameter="triggering_anchors", + map_function=lambda x: [x], + warning_message="Warning: '{old_parameter}' in '{function_name}' " + "is deprecated and will be remove in " + "'{removal_sv_version}: use '{new_parameter}' instead.", + removal_sv_version="supervision-0.23.0", + ) def __init__( self, polygon: np.ndarray, frame_resolution_wh: Tuple[int, int], - triggering_position: Position = Position.BOTTOM_CENTER, + triggering_anchors: Iterable[Position] = (Position.BOTTOM_CENTER,), ): self.polygon = polygon.astype(int) self.frame_resolution_wh = frame_resolution_wh - self.triggering_position = triggering_position + self.triggering_anchors = triggering_anchors + self.current_count = 0 width, height = frame_resolution_wh @@ -59,10 +72,20 @@ def trigger(self, detections: Detections) -> np.ndarray: xyxy=detections.xyxy, resolution_wh=self.frame_resolution_wh ) clipped_detections = replace(detections, xyxy=clipped_xyxy) - clipped_anchors = np.ceil( - clipped_detections.get_anchors_coordinates(anchor=self.triggering_position) - ).astype(int) - is_in_zone = self.mask[clipped_anchors[:, 1], clipped_anchors[:, 0]] + all_clipped_anchors = np.array( + [ + np.ceil(clipped_detections.get_anchors_coordinates(anchor)).astype(int) + for anchor in self.triggering_anchors + ] + ) + + is_in_zone = ( + self.mask[all_clipped_anchors[:, :, 1], all_clipped_anchors[:, :, 0]] + .transpose() + .astype(bool) + ) + is_in_zone = np.all(is_in_zone, axis=1) + self.current_count = int(np.sum(is_in_zone)) return is_in_zone.astype(bool) diff --git a/supervision/utils/internal.py b/supervision/utils/internal.py index 031f5be15..2749e360d 100644 --- a/supervision/utils/internal.py +++ b/supervision/utils/internal.py @@ -1,5 +1,78 @@ import functools import warnings +from typing import Callable + + +def deprecated_parameter( + old_parameter: str, + new_parameter: str, + map_function: Callable = lambda x: x, + warning_message: str = "Warning: '{old_parameter}' in '{function_name}' " + "is deprecated: use '{new_parameter}' instead.", + **message_kwargs, +): + """ + A decorator to mark a function's parameter as deprecated + and issue a warning when used. + + Parameters: + - old_parameter (str): The name of the deprecated parameter. + - new_parameter (str): The name of the parameter that should be used instead. + - map_function (Callable, optional): A function used to map the value of the old + parameter to the new parameter. Defaults to the identity function. + - warn_message (str, optional): The warning message to be displayed when the + deprecated parameter is used. Defaults to a generic warning message with + placeholders for the old parameter, new parameter, and function name. + - **message_kwargs: Additional keyword arguments that can be used to customize + the warning message. + + Returns: + Callable: A decorator function that can be applied to mark a function's + parameter as deprecated. + + Usage Example: + ```python + @deprecated_parameter(old_parameter="old_param", new_parameter="new_param") + def example_function(new_param): + print(f"Function called with new_param: {new_param}") + + # When calling the function with the deprecated parameter: + example_function(old_param="deprecated_value") + ``` + This will trigger a deprecation warning and execute the function with the mapped + value of the deprecated parameter. + """ + + def decorator(func): + @functools.wraps(func) + def wrapper(*args, **kwargs): + if old_parameter in kwargs: + # In case of a method, display also the class name. + if args and hasattr(args[0], "__class__"): + class_name = args[0].__class__.__name__ + function_name = f"{class_name}.{func.__name__}" + else: + function_name = func.__name__ + + # Display deprecation warning + warnings.warn( + message=warning_message.format( + function_name=function_name, + old_parameter=old_parameter, + new_parameter=new_parameter, + **message_kwargs, + ), + category=DeprecationWarning, + stacklevel=2, + ) + # Map old_param to new_param + kwargs[new_parameter] = map_function(kwargs.pop(old_parameter)) + + return func(*args, **kwargs) + + return wrapper + + return decorator def deprecated(reason: str):
diff --git a/test/detection/test_polygonzone.py b/test/detection/test_polygonzone.py new file mode 100644 index 000000000..2aae955f7 --- /dev/null +++ b/test/detection/test_polygonzone.py @@ -0,0 +1,92 @@ +from contextlib import ExitStack as DoesNotRaise +from test.test_utils import mock_detections + +import numpy as np +import pytest + +import supervision as sv + +DETECTION_BOXES = np.array( + [ + [35.0, 35.0, 65.0, 65.0], + [60.0, 60.0, 90.0, 90.0], + [85.0, 85.0, 115.0, 115.0], + [110.0, 110.0, 140.0, 140.0], + [135.0, 135.0, 165.0, 165.0], + [160.0, 160.0, 190.0, 190.0], + [185.0, 185.0, 215.0, 215.0], + [210.0, 210.0, 240.0, 240.0], + [235.0, 235.0, 265.0, 265.0], + ], + dtype=np.float32, +) + +DETECTIONS = mock_detections( + xyxy=DETECTION_BOXES, class_id=np.array([0, 0, 0, 0, 0, 0, 0, 0, 0]) +) + +POLYGON = np.array([[100, 100], [200, 100], [200, 200], [100, 200]]) +FRAME_RESOLUTION = (300, 300) + + +@pytest.mark.parametrize( + "detections, polygon_zone, expected_results, exception", + [ + ( + DETECTIONS, + sv.PolygonZone( + POLYGON, + FRAME_RESOLUTION, + triggering_anchors=( + sv.Position.TOP_LEFT, + sv.Position.TOP_RIGHT, + sv.Position.BOTTOM_LEFT, + sv.Position.BOTTOM_RIGHT, + ), + ), + np.array( + [False, False, False, True, True, True, False, False, False], dtype=bool + ), + DoesNotRaise(), + ), # Test all four corners + ( + DETECTIONS, + sv.PolygonZone( + POLYGON, + FRAME_RESOLUTION, + ), + np.array( + [False, False, True, True, True, True, False, False, False], dtype=bool + ), + DoesNotRaise(), + ), # Test default behaviour when no anchors are provided + ( + DETECTIONS, + sv.PolygonZone( + POLYGON, FRAME_RESOLUTION, triggering_position=sv.Position.BOTTOM_CENTER + ), + np.array( + [False, False, True, True, True, True, False, False, False], dtype=bool + ), + DoesNotRaise(), + ), # Test default behaviour with deprecated api. + ( + sv.Detections.empty(), + sv.PolygonZone( + POLYGON, + FRAME_RESOLUTION, + ), + np.array([], dtype=bool), + DoesNotRaise(), + ), # Test empty detections + ], +) +def test_polygon_zone_trigger( + detections: sv.Detections, + polygon_zone: sv.PolygonZone, + expected_results: np.ndarray, + exception: Exception, +) -> None: + with exception: + in_zone = polygon_zone.trigger(detections) + assert np.all(in_zone == expected_results)
[ { "components": [ { "doc": "A decorator to mark a function's parameter as deprecated\nand issue a warning when used.\n\nParameters:\n- old_parameter (str): The name of the deprecated parameter.\n- new_parameter (str): The name of the parameter that should be used instead.\n- map_function (Callable, optional): A function used to map the value of the old\n parameter to the new parameter. Defaults to the identity function.\n- warn_message (str, optional): The warning message to be displayed when the\n deprecated parameter is used. Defaults to a generic warning message with\n placeholders for the old parameter, new parameter, and function name.\n- **message_kwargs: Additional keyword arguments that can be used to customize\n the warning message.\n\nReturns:\nCallable: A decorator function that can be applied to mark a function's\nparameter as deprecated.\n\nUsage Example:\n```python\n@deprecated_parameter(old_parameter=\"old_param\", new_parameter=\"new_param\")\ndef example_function(new_param):\n print(f\"Function called with new_param: {new_param}\")\n\n# When calling the function with the deprecated parameter:\nexample_function(old_param=\"deprecated_value\")\n```\nThis will trigger a deprecation warning and execute the function with the mapped\nvalue of the deprecated parameter.", "lines": [ 6, 75 ], "name": "deprecated_parameter", "signature": "def deprecated_parameter( old_parameter: str, new_parameter: str, map_function: Callable = lambda x: x, warning_message: str = \"Warning: '{old_parameter}' in '{function_name}' \" \"is deprecated: use '{new_parameter}' instead.\", **message_kwargs, ):", "type": "function" }, { "doc": "", "lines": [ 46, 73 ], "name": "deprecated_parameter.decorator", "signature": "def decorator(func): @functools.wraps(func)", "type": "function" }, { "doc": "", "lines": [ 48, 71 ], "name": "deprecated_parameter.decorator.wrapper", "signature": "def wrapper(*args, **kwargs):", "type": "function" } ], "file": "supervision/utils/internal.py" } ]
[ "test/detection/test_polygonzone.py::test_polygon_zone_trigger[detections0-polygon_zone0-expected_results0-exception0]", "test/detection/test_polygonzone.py::test_polygon_zone_trigger[detections1-polygon_zone1-expected_results1-exception1]", "test/detection/test_polygonzone.py::test_polygon_zone_trigger[detections2-polygon_zone2-expected_results2-exception2]", "test/detection/test_polygonzone.py::test_polygon_zone_trigger[detections3-polygon_zone3-expected_results3-exception3]" ]
[]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> Polygonzone add multiple anchors support # Description This PR addresses [Issue #844](https://github.com/roboflow/supervision/issues/844). - Rename `triggering_position` to `triggering_anchors` to be consistent with the `LineZone` naming convention. - Update type of argument from `Position` to `Iterable[Position]`. - Maintain the default behavior. The zone should, by default, be triggered by `Position.BOTTOM_CENTER`. - Adds unit tests for `PolygonZone`. - Updates documentation. ## Type of change - [ x ] New feature (non-breaking change which adds functionality) - [ x ] This change requires a documentation update ## How has this change been tested, please provide a testcase or example of how you tested the change? For a minimalist setup, I'm doing the following: 1- Create mock detections simulating an object moving in a straight line. 2- Instantiate a `PolygonZone` object with polygon partially intersecting the line. 3- Compute the `PolygonZone.trigger(mock_detections)` and annotate the detections triggering the `PolygonZone` object as green, and red otherwise. The setup used here was also used as base for the unit tests. Google colab: [https://colab.research.google.com/drive/1fcsVrprMuf7hm_bxitSqmeL5L7KBVGHh?usp=sharing](https://colab.research.google.com/drive/1fcsVrprMuf7hm_bxitSqmeL5L7KBVGHh?usp=sharing) ## Deployment Concerns ### API Backward Compatibility #### Option 1: Maintaining Deprecation Logic Within the Function To ensure backward compatibility after renaming a parameter in this PR, one approach is to maintain deprecation logic within the function itself. The implementation could look something like this: ```python class PolygonZone: def __init__(self, polygon, frame_resolution_wh, triggering_anchors, **kwargs): if 'triggering_position' in kwargs: warning.warn('deprecated argument...') ''' logic to handle deprecated parameter''' ``` While effective for specific cases, this approach has some drawbacks: 1. **Documentation Readability**: Inserting `**kwargs` might make the documentation less clear. 2. **Code Visibility**: Deprecated code may become challenging to locate, especially with scale. 3. **Lack of Precedence**: I couldn't find any examples of this pattern in the codebase. #### Option 2: Adding a `@deprecated_parameter` Annotator (Adopted Solution) The chosen solution involves creating a `@deprecated_parameter` annotator using pseudocode like this: ```python def deprecated_parameter(old_param: str, new_param: str, map_func: Callable = lambda x: x): def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): if old_param in kwargs: print('warning message...') kwargs[new_param] = map_func(kwargs.pop(old_param)) return func(*args, **kwargs) return wrapper return decorator ``` While this solution may not be suitable for highly complex parameter changes, it aligns with existing practices, such as the use of the `@deprecated` annotator, making it easier to track deprecated code references. Please share your thoughts on this proposed solution. ### Deprecated Examples Some examples, like `examples/traffic_analysis`, explicitly set `triggering_position` for the `PolygonZone` class. This PR renders it deprecated. Should we address these changes within this PR, or would it be more appropriate to handle them in a separate one? I am open to incorporating the necessary modifications here if that is the preferred approach. Let me know your preferences regarding these considerations. ## Docs - [ x ] Docs updated? What were the changes: [Changed the documentation for class `PolygonZone`](https://github.com/roboflow/supervision/pull/910/files#diff-738bb6b6510e46b8633ab062a4c980fa338f7f3ccf7c9792b91a1bd589e8bf01L23-R27). Fix : #844 ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in supervision/utils/internal.py] (definition of deprecated_parameter:) def deprecated_parameter( old_parameter: str, new_parameter: str, map_function: Callable = lambda x: x, warning_message: str = "Warning: '{old_parameter}' in '{function_name}' " "is deprecated: use '{new_parameter}' instead.", **message_kwargs, ): """A decorator to mark a function's parameter as deprecated and issue a warning when used. Parameters: - old_parameter (str): The name of the deprecated parameter. - new_parameter (str): The name of the parameter that should be used instead. - map_function (Callable, optional): A function used to map the value of the old parameter to the new parameter. Defaults to the identity function. - warn_message (str, optional): The warning message to be displayed when the deprecated parameter is used. Defaults to a generic warning message with placeholders for the old parameter, new parameter, and function name. - **message_kwargs: Additional keyword arguments that can be used to customize the warning message. Returns: Callable: A decorator function that can be applied to mark a function's parameter as deprecated. Usage Example: ```python @deprecated_parameter(old_parameter="old_param", new_parameter="new_param") def example_function(new_param): print(f"Function called with new_param: {new_param}") # When calling the function with the deprecated parameter: example_function(old_param="deprecated_value") ``` This will trigger a deprecation warning and execute the function with the mapped value of the deprecated parameter.""" (definition of deprecated_parameter.decorator:) def decorator(func): @functools.wraps(func) (definition of deprecated_parameter.decorator.wrapper:) def wrapper(*args, **kwargs): [end of new definitions in supervision/utils/internal.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
3eb5c0b024e3e46877b7fe4fd66e6177d1308ba0
huggingface__huggingface_hub-2027
2,027
huggingface/huggingface_hub
null
0c272d506e390f2d7b9dac68159595845c7f8e3b
2024-02-14T18:00:11Z
diff --git a/src/huggingface_hub/hf_file_system.py b/src/huggingface_hub/hf_file_system.py index a78ab0fd80..630ff64ba8 100644 --- a/src/huggingface_hub/hf_file_system.py +++ b/src/huggingface_hub/hf_file_system.py @@ -577,6 +577,20 @@ def isfile(self, path): except: # noqa: E722 return False + def url(self, path: str) -> str: + """Get the HTTP URL of the given path""" + resolved_path = self.resolve_path(path) + url = hf_hub_url( + resolved_path.repo_id, + resolved_path.path_in_repo, + repo_type=resolved_path.repo_type, + revision=resolved_path.revision, + endpoint=self.endpoint, + ) + if self.isdir(path): + url = url.replace("/resolve/", "/tree/", 1) + return url + @property def transaction(self): """A context within which files are committed together upon exit @@ -653,6 +667,9 @@ def _upload_chunk(self, final: bool = False) -> None: path=self.resolved_path.unresolve(), ) + def url(self) -> str: + return self.fs.url(self.path) + class HfFileSystemStreamFile(fsspec.spec.AbstractBufferedFile): def __init__( @@ -740,6 +757,9 @@ def read(self, length: int = -1): self.loc += len(out) return out + def url(self) -> str: + return self.fs.url(self.path) + def __del__(self): if not hasattr(self, "resolved_path"): # Means that the constructor failed. Nothing to do.
diff --git a/tests/test_hf_file_system.py b/tests/test_hf_file_system.py index 02cf913515..af9bf3b94f 100644 --- a/tests/test_hf_file_system.py +++ b/tests/test_hf_file_system.py @@ -131,6 +131,16 @@ def test_glob(self): ) self.assertIsNotNone(files[keys[0]]["last_commit"]) + def test_url(self): + self.assertEqual( + self.hffs.url(self.hf_path + "/data/text_data.txt"), + f"{ENDPOINT_STAGING}/datasets/{self.repo_id}/resolve/main/data/text_data.txt", + ) + self.assertEqual( + self.hffs.url(self.hf_path + "/data"), + f"{ENDPOINT_STAGING}/datasets/{self.repo_id}/tree/main/data", + ) + def test_file_type(self): self.assertTrue( self.hffs.isdir(self.hf_path + "/data") and not self.hffs.isdir(self.hf_path + "/.gitattributes")
[ { "components": [ { "doc": "Get the HTTP URL of the given path", "lines": [ 580, 592 ], "name": "HfFileSystem.url", "signature": "def url(self, path: str) -> str:", "type": "function" }, { "doc": "", "lines": [ 670, 671 ], "name": "HfFileSystemFile.url", "signature": "def url(self) -> str:", "type": "function" }, { "doc": "", "lines": [ 760, 761 ], "name": "HfFileSystemStreamFile.url", "signature": "def url(self) -> str:", "type": "function" } ], "file": "src/huggingface_hub/hf_file_system.py" } ]
[ "tests/test_hf_file_system.py::HfFileSystemTests::test_url" ]
[ "tests/test_hf_file_system.py::HfFileSystemTests::test_copy_file", "tests/test_hf_file_system.py::HfFileSystemTests::test_file_type", "tests/test_hf_file_system.py::HfFileSystemTests::test_find_data_file_no_revision", "tests/test_hf_file_system.py::HfFileSystemTests::test_find_root_directory_no_revision", "tests/test_hf_file_system.py::HfFileSystemTests::test_find_root_directory_no_revision_with_incomplete_cache", "tests/test_hf_file_system.py::HfFileSystemTests::test_glob", "tests/test_hf_file_system.py::HfFileSystemTests::test_info", "tests/test_hf_file_system.py::HfFileSystemTests::test_initialize_from_fsspec", "tests/test_hf_file_system.py::HfFileSystemTests::test_list_data_directory_no_revision", "tests/test_hf_file_system.py::HfFileSystemTests::test_list_data_directory_with_revision", "tests/test_hf_file_system.py::HfFileSystemTests::test_list_data_file_no_revision", "tests/test_hf_file_system.py::HfFileSystemTests::test_list_root_directory_no_revision", "tests/test_hf_file_system.py::HfFileSystemTests::test_list_root_directory_no_revision_no_detail_then_with_detail", "tests/test_hf_file_system.py::HfFileSystemTests::test_modified_time", "tests/test_hf_file_system.py::HfFileSystemTests::test_read_file", "tests/test_hf_file_system.py::HfFileSystemTests::test_read_file_with_revision", "tests/test_hf_file_system.py::HfFileSystemTests::test_remove_directory", "tests/test_hf_file_system.py::HfFileSystemTests::test_remove_file", "tests/test_hf_file_system.py::HfFileSystemTests::test_stream_file", "tests/test_hf_file_system.py::HfFileSystemTests::test_stream_file_retry", "tests/test_hf_file_system.py::HfFileSystemTests::test_write_file", "tests/test_hf_file_system.py::HfFileSystemTests::test_write_file_multiple_chunks", "tests/test_hf_file_system.py::test_resolve_path[gpt2-None-model-gpt2-main-]", "tests/test_hf_file_system.py::test_resolve_path[gpt2-None-model-gpt2-main-file.txt]", "tests/test_hf_file_system.py::test_resolve_path[gpt2-None-model-gpt2-main-path/to/file]", "tests/test_hf_file_system.py::test_resolve_path[gpt2-dev-model-gpt2-dev-]", "tests/test_hf_file_system.py::test_resolve_path[gpt2-dev-model-gpt2-dev-file.txt]", "tests/test_hf_file_system.py::test_resolve_path[gpt2-dev-model-gpt2-dev-path/to/file]", "tests/test_hf_file_system.py::test_resolve_path[gpt2@dev-None-model-gpt2-dev-]", "tests/test_hf_file_system.py::test_resolve_path[gpt2@dev-None-model-gpt2-dev-file.txt]", "tests/test_hf_file_system.py::test_resolve_path[gpt2@dev-None-model-gpt2-dev-path/to/file]", "tests/test_hf_file_system.py::test_resolve_path[datasets/squad-None-dataset-squad-main-]", "tests/test_hf_file_system.py::test_resolve_path[datasets/squad-None-dataset-squad-main-file.txt]", "tests/test_hf_file_system.py::test_resolve_path[datasets/squad-None-dataset-squad-main-path/to/file]", "tests/test_hf_file_system.py::test_resolve_path[datasets/squad-dev-dataset-squad-dev-]", "tests/test_hf_file_system.py::test_resolve_path[datasets/squad-dev-dataset-squad-dev-file.txt]", "tests/test_hf_file_system.py::test_resolve_path[datasets/squad-dev-dataset-squad-dev-path/to/file]", "tests/test_hf_file_system.py::test_resolve_path[datasets/squad@dev-None-dataset-squad-dev-]", "tests/test_hf_file_system.py::test_resolve_path[datasets/squad@dev-None-dataset-squad-dev-file.txt]", "tests/test_hf_file_system.py::test_resolve_path[datasets/squad@dev-None-dataset-squad-dev-path/to/file]", "tests/test_hf_file_system.py::test_resolve_path[username/my_model-None-model-username/my_model-main-]", "tests/test_hf_file_system.py::test_resolve_path[username/my_model-None-model-username/my_model-main-file.txt]", "tests/test_hf_file_system.py::test_resolve_path[username/my_model-None-model-username/my_model-main-path/to/file]", "tests/test_hf_file_system.py::test_resolve_path[username/my_model-dev-model-username/my_model-dev-]", "tests/test_hf_file_system.py::test_resolve_path[username/my_model-dev-model-username/my_model-dev-file.txt]", "tests/test_hf_file_system.py::test_resolve_path[username/my_model-dev-model-username/my_model-dev-path/to/file]", "tests/test_hf_file_system.py::test_resolve_path[username/my_model@dev-None-model-username/my_model-dev-]", "tests/test_hf_file_system.py::test_resolve_path[username/my_model@dev-None-model-username/my_model-dev-file.txt]", "tests/test_hf_file_system.py::test_resolve_path[username/my_model@dev-None-model-username/my_model-dev-path/to/file]", "tests/test_hf_file_system.py::test_resolve_path[datasets/username/my_dataset-None-dataset-username/my_dataset-main-]", "tests/test_hf_file_system.py::test_resolve_path[datasets/username/my_dataset-None-dataset-username/my_dataset-main-file.txt]", "tests/test_hf_file_system.py::test_resolve_path[datasets/username/my_dataset-None-dataset-username/my_dataset-main-path/to/file]", "tests/test_hf_file_system.py::test_resolve_path[datasets/username/my_dataset-dev-dataset-username/my_dataset-dev-]", "tests/test_hf_file_system.py::test_resolve_path[datasets/username/my_dataset-dev-dataset-username/my_dataset-dev-file.txt]", "tests/test_hf_file_system.py::test_resolve_path[datasets/username/my_dataset-dev-dataset-username/my_dataset-dev-path/to/file]", "tests/test_hf_file_system.py::test_resolve_path[datasets/username/my_dataset@dev-None-dataset-username/my_dataset-dev-]", "tests/test_hf_file_system.py::test_resolve_path[datasets/username/my_dataset@dev-None-dataset-username/my_dataset-dev-file.txt]", "tests/test_hf_file_system.py::test_resolve_path[datasets/username/my_dataset@dev-None-dataset-username/my_dataset-dev-path/to/file]", "tests/test_hf_file_system.py::test_resolve_path[hf://gpt2-None-model-gpt2-main-]", "tests/test_hf_file_system.py::test_resolve_path[hf://gpt2-None-model-gpt2-main-file.txt]", "tests/test_hf_file_system.py::test_resolve_path[hf://gpt2-None-model-gpt2-main-path/to/file]", "tests/test_hf_file_system.py::test_resolve_path[hf://gpt2-dev-model-gpt2-dev-]", "tests/test_hf_file_system.py::test_resolve_path[hf://gpt2-dev-model-gpt2-dev-file.txt]", "tests/test_hf_file_system.py::test_resolve_path[hf://gpt2-dev-model-gpt2-dev-path/to/file]", "tests/test_hf_file_system.py::test_resolve_path[hf://gpt2@dev-None-model-gpt2-dev-]", "tests/test_hf_file_system.py::test_resolve_path[hf://gpt2@dev-None-model-gpt2-dev-file.txt]", "tests/test_hf_file_system.py::test_resolve_path[hf://gpt2@dev-None-model-gpt2-dev-path/to/file]", "tests/test_hf_file_system.py::test_resolve_path[hf://datasets/squad-None-dataset-squad-main-]", "tests/test_hf_file_system.py::test_resolve_path[hf://datasets/squad-None-dataset-squad-main-file.txt]", "tests/test_hf_file_system.py::test_resolve_path[hf://datasets/squad-None-dataset-squad-main-path/to/file]", "tests/test_hf_file_system.py::test_resolve_path[hf://datasets/squad-dev-dataset-squad-dev-]", "tests/test_hf_file_system.py::test_resolve_path[hf://datasets/squad-dev-dataset-squad-dev-file.txt]", "tests/test_hf_file_system.py::test_resolve_path[hf://datasets/squad-dev-dataset-squad-dev-path/to/file]", "tests/test_hf_file_system.py::test_resolve_path[hf://datasets/squad@dev-None-dataset-squad-dev-]", "tests/test_hf_file_system.py::test_resolve_path[hf://datasets/squad@dev-None-dataset-squad-dev-file.txt]", "tests/test_hf_file_system.py::test_resolve_path[hf://datasets/squad@dev-None-dataset-squad-dev-path/to/file]", "tests/test_hf_file_system.py::test_resolve_path[datasets/squad@refs/convert/parquet-None-dataset-squad-refs/convert/parquet-]", "tests/test_hf_file_system.py::test_resolve_path[datasets/squad@refs/convert/parquet-None-dataset-squad-refs/convert/parquet-file.txt]", "tests/test_hf_file_system.py::test_resolve_path[datasets/squad@refs/convert/parquet-None-dataset-squad-refs/convert/parquet-path/to/file]", "tests/test_hf_file_system.py::test_resolve_path[hf://datasets/username/my_dataset@refs/convert/parquet-None-dataset-username/my_dataset-refs/convert/parquet-]", "tests/test_hf_file_system.py::test_resolve_path[hf://datasets/username/my_dataset@refs/convert/parquet-None-dataset-username/my_dataset-refs/convert/parquet-file.txt]", "tests/test_hf_file_system.py::test_resolve_path[hf://datasets/username/my_dataset@refs/convert/parquet-None-dataset-username/my_dataset-refs/convert/parquet-path/to/file]", "tests/test_hf_file_system.py::test_resolve_path[gpt2@refs/pr/2-None-model-gpt2-refs/pr/2-]", "tests/test_hf_file_system.py::test_resolve_path[gpt2@refs/pr/2-None-model-gpt2-refs/pr/2-file.txt]", "tests/test_hf_file_system.py::test_resolve_path[gpt2@refs/pr/2-None-model-gpt2-refs/pr/2-path/to/file]", "tests/test_hf_file_system.py::test_resolve_path[gpt2@refs%2Fpr%2F2-None-model-gpt2-refs/pr/2-]", "tests/test_hf_file_system.py::test_resolve_path[gpt2@refs%2Fpr%2F2-None-model-gpt2-refs/pr/2-file.txt]", "tests/test_hf_file_system.py::test_resolve_path[gpt2@refs%2Fpr%2F2-None-model-gpt2-refs/pr/2-path/to/file]", "tests/test_hf_file_system.py::test_resolve_path[hf://username/my_model@refs/pr/10-None-model-username/my_model-refs/pr/10-]", "tests/test_hf_file_system.py::test_resolve_path[hf://username/my_model@refs/pr/10-None-model-username/my_model-refs/pr/10-file.txt]", "tests/test_hf_file_system.py::test_resolve_path[hf://username/my_model@refs/pr/10-None-model-username/my_model-refs/pr/10-path/to/file]", "tests/test_hf_file_system.py::test_resolve_path[hf://username/my_model@refs/pr/10-refs/pr/10-model-username/my_model-refs/pr/10-]", "tests/test_hf_file_system.py::test_resolve_path[hf://username/my_model@refs/pr/10-refs/pr/10-model-username/my_model-refs/pr/10-file.txt]", "tests/test_hf_file_system.py::test_resolve_path[hf://username/my_model@refs/pr/10-refs/pr/10-model-username/my_model-refs/pr/10-path/to/file]", "tests/test_hf_file_system.py::test_resolve_path[hf://username/my_model@refs%2Fpr%2F10-refs/pr/10-model-username/my_model-refs/pr/10-]", "tests/test_hf_file_system.py::test_resolve_path[hf://username/my_model@refs%2Fpr%2F10-refs/pr/10-model-username/my_model-refs/pr/10-file.txt]", "tests/test_hf_file_system.py::test_resolve_path[hf://username/my_model@refs%2Fpr%2F10-refs/pr/10-model-username/my_model-refs/pr/10-path/to/file]", "tests/test_hf_file_system.py::test_unresolve_path[hf://datasets/squad@dev-None-datasets/squad@dev-]", "tests/test_hf_file_system.py::test_unresolve_path[hf://datasets/squad@dev-None-datasets/squad@dev-file.txt]", "tests/test_hf_file_system.py::test_unresolve_path[hf://datasets/squad@dev-None-datasets/squad@dev-path/to/file]", "tests/test_hf_file_system.py::test_unresolve_path[datasets/squad@refs/convert/parquet-None-datasets/squad@refs/convert/parquet-]", "tests/test_hf_file_system.py::test_unresolve_path[datasets/squad@refs/convert/parquet-None-datasets/squad@refs/convert/parquet-file.txt]", "tests/test_hf_file_system.py::test_unresolve_path[datasets/squad@refs/convert/parquet-None-datasets/squad@refs/convert/parquet-path/to/file]", "tests/test_hf_file_system.py::test_unresolve_path[hf://username/my_model@refs/pr/10-None-username/my_model@refs/pr/10-]", "tests/test_hf_file_system.py::test_unresolve_path[hf://username/my_model@refs/pr/10-None-username/my_model@refs/pr/10-file.txt]", "tests/test_hf_file_system.py::test_unresolve_path[hf://username/my_model@refs/pr/10-None-username/my_model@refs/pr/10-path/to/file]", "tests/test_hf_file_system.py::test_unresolve_path[username/my_model-refs/weirdo-username/my_model@refs%2Fweirdo-]", "tests/test_hf_file_system.py::test_unresolve_path[username/my_model-refs/weirdo-username/my_model@refs%2Fweirdo-file.txt]", "tests/test_hf_file_system.py::test_unresolve_path[username/my_model-refs/weirdo-username/my_model@refs%2Fweirdo-path/to/file]", "tests/test_hf_file_system.py::test_resolve_path_with_refs_revision", "tests/test_hf_file_system.py::test_resolve_path_with_non_matching_revisions", "tests/test_hf_file_system.py::test_access_repositories_lists[]", "tests/test_hf_file_system.py::test_access_repositories_lists[foo]", "tests/test_hf_file_system.py::test_access_repositories_lists[datasets]", "tests/test_hf_file_system.py::test_access_repositories_lists[datasets/foo]" ]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> Add `HfFileSystem.url` method Adds a `url` method to the `HfFileSystem` to simplify converting HF paths to HTTP URLs, which should be useful when working with libs that support HTTP URLs but not `fsspec` paths as input/output (e.g., `webdataset`, `polars`, etc.). PS: The `url` method is not part of the official `fsspec` specification, but popular filesystem implementations such as `gcsfs` and `s3fs` also have it ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in src/huggingface_hub/hf_file_system.py] (definition of HfFileSystem.url:) def url(self, path: str) -> str: """Get the HTTP URL of the given path""" (definition of HfFileSystemFile.url:) def url(self) -> str: (definition of HfFileSystemStreamFile.url:) def url(self) -> str: [end of new definitions in src/huggingface_hub/hf_file_system.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
4058e1f97ebe256b2f3006d4bc31be275c66df6b
roboflow__supervision-847
847
roboflow/supervision
null
d423ff3b6c74f38713255f18e363ea2e1986f5dd
2024-02-03T03:10:21Z
diff --git a/docs/detection/utils.md b/docs/detection/utils.md index 54d1f279f..74adc6e74 100644 --- a/docs/detection/utils.md +++ b/docs/detection/utils.md @@ -11,10 +11,22 @@ comments: true :::supervision.detection.utils.box_iou_batch <div class="md-typeset"> - <h2>non_max_suppression</h2> + <h2>mask_iou_batch</h2> </div> -:::supervision.detection.utils.non_max_suppression +:::supervision.detection.utils.mask_iou_batch + +<div class="md-typeset"> + <h2>box_non_max_suppression</h2> +</div> + +:::supervision.detection.utils.box_non_max_suppression + +<div class="md-typeset"> + <h2>mask_non_max_suppression</h2> +</div> + +:::supervision.detection.utils.mask_non_max_suppression <div class="md-typeset"> <h2>polygon_to_mask</h2> diff --git a/supervision/__init__.py b/supervision/__init__.py index 76abe5996..961162836 100644 --- a/supervision/__init__.py +++ b/supervision/__init__.py @@ -42,12 +42,14 @@ from supervision.detection.tools.smoother import DetectionsSmoother from supervision.detection.utils import ( box_iou_batch, + box_non_max_suppression, calculate_masks_centroids, filter_polygons_by_area, + mask_iou_batch, + mask_non_max_suppression, mask_to_polygons, mask_to_xyxy, move_boxes, - non_max_suppression, polygon_to_mask, polygon_to_xyxy, scale_boxes, diff --git a/supervision/detection/core.py b/supervision/detection/core.py index 7b9249630..e727426bf 100644 --- a/supervision/detection/core.py +++ b/supervision/detection/core.py @@ -8,12 +8,13 @@ from supervision.config import CLASS_NAME_DATA_FIELD, ORIENTED_BOX_COORDINATES from supervision.detection.utils import ( + box_non_max_suppression, calculate_masks_centroids, extract_ultralytics_masks, get_data_item, is_data_equal, + mask_non_max_suppression, merge_data, - non_max_suppression, process_roboflow_result, validate_detections_fields, xywh_to_xyxy, @@ -1001,7 +1002,8 @@ def with_nms( self, threshold: float = 0.5, class_agnostic: bool = False ) -> Detections: """ - Perform non-maximum suppression on the current set of object detections. + Performs non-max suppression on detection set. If the detections result + from a segmentation model, the IoU mask is applied. Otherwise, box IoU is used. Args: threshold (float, optional): The intersection-over-union threshold @@ -1028,18 +1030,26 @@ def with_nms( if class_agnostic: predictions = np.hstack((self.xyxy, self.confidence.reshape(-1, 1))) - indices = non_max_suppression( - predictions=predictions, iou_threshold=threshold + else: + assert self.class_id is not None, ( + "Detections class_id must be given for NMS to be executed. If you" + " intended to perform class agnostic NMS set class_agnostic=True." + ) + predictions = np.hstack( + ( + self.xyxy, + self.confidence.reshape(-1, 1), + self.class_id.reshape(-1, 1), + ) ) - return self[indices] - assert self.class_id is not None, ( - "Detections class_id must be given for NMS to be executed. If you intended" - " to perform class agnostic NMS set class_agnostic=True." - ) + if self.mask is not None: + indices = mask_non_max_suppression( + predictions=predictions, masks=self.mask, iou_threshold=threshold + ) + else: + indices = box_non_max_suppression( + predictions=predictions, iou_threshold=threshold + ) - predictions = np.hstack( - (self.xyxy, self.confidence.reshape(-1, 1), self.class_id.reshape(-1, 1)) - ) - indices = non_max_suppression(predictions=predictions, iou_threshold=threshold) return self[indices] diff --git a/supervision/detection/utils.py b/supervision/detection/utils.py index e8db4627e..f411df288 100644 --- a/supervision/detection/utils.py +++ b/supervision/detection/utils.py @@ -59,7 +59,119 @@ def box_area(box): return area_inter / (area_true[:, None] + area_detection - area_inter) -def non_max_suppression( +def mask_iou_batch(masks_true: np.ndarray, masks_detection: np.ndarray) -> np.ndarray: + """ + Compute Intersection over Union (IoU) of two sets of masks - + `masks_true` and `masks_detection`. + + Args: + masks_true (np.ndarray): 3D `np.ndarray` representing ground-truth masks. + masks_detection (np.ndarray): 3D `np.ndarray` representing detection masks. + + Returns: + np.ndarray: Pairwise IoU of masks from `masks_true` and `masks_detection`. + """ + intersection_area = np.logical_and(masks_true[:, None], masks_detection).sum( + axis=(2, 3) + ) + masks_true_area = masks_true.sum(axis=(1, 2)) + masks_detection_area = masks_detection.sum(axis=(1, 2)) + + union_area = masks_true_area[:, None] + masks_detection_area - intersection_area + + return np.divide( + intersection_area, + union_area, + out=np.zeros_like(intersection_area, dtype=float), + where=union_area != 0, + ) + + +def resize_masks(masks: np.ndarray, max_dimension: int = 640) -> np.ndarray: + """ + Resize all masks in the array to have a maximum dimension of max_dimension, + maintaining aspect ratio. + + Args: + masks (np.ndarray): 3D array of binary masks with shape (N, H, W). + max_dimension (int): The maximum dimension for the resized masks. + + Returns: + np.ndarray: Array of resized masks. + """ + max_height = np.max(masks.shape[1]) + max_width = np.max(masks.shape[2]) + scale = min(max_dimension / max_height, max_dimension / max_width) + + new_height = int(scale * max_height) + new_width = int(scale * max_width) + + x = np.linspace(0, max_width - 1, new_width).astype(int) + y = np.linspace(0, max_height - 1, new_height).astype(int) + xv, yv = np.meshgrid(x, y) + + resized_masks = masks[:, yv, xv] + + resized_masks = resized_masks.reshape(masks.shape[0], new_height, new_width) + return resized_masks + + +def mask_non_max_suppression( + predictions: np.ndarray, + masks: np.ndarray, + iou_threshold: float = 0.5, + mask_dimension: int = 640, +) -> np.ndarray: + """ + Perform Non-Maximum Suppression (NMS) on segmentation predictions. + + Args: + predictions (np.ndarray): A 2D array of object detection predictions in + the format of `(x_min, y_min, x_max, y_max, score)` + or `(x_min, y_min, x_max, y_max, score, class)`. Shape: `(N, 5)` or + `(N, 6)`, where N is the number of predictions. + masks (np.ndarray): A 3D array of binary masks corresponding to the predictions. + Shape: `(N, H, W)`, where N is the number of predictions, and H, W are the + dimensions of each mask. + iou_threshold (float, optional): The intersection-over-union threshold + to use for non-maximum suppression. + mask_dimension (int, optional): The dimension to which the masks should be + resized before computing IOU values. Defaults to 640. + + Returns: + np.ndarray: A boolean array indicating which predictions to keep after + non-maximum suppression. + + Raises: + AssertionError: If `iou_threshold` is not within the closed + range from `0` to `1`. + """ + assert 0 <= iou_threshold <= 1, ( + "Value of `iou_threshold` must be in the closed range from 0 to 1, " + f"{iou_threshold} given." + ) + rows, columns = predictions.shape + + if columns == 5: + predictions = np.c_[predictions, np.zeros(rows)] + + sort_index = predictions[:, 4].argsort()[::-1] + predictions = predictions[sort_index] + masks = masks[sort_index] + masks_resized = resize_masks(masks, mask_dimension) + ious = mask_iou_batch(masks_resized, masks_resized) + categories = predictions[:, 5] + + keep = np.ones(rows, dtype=bool) + for i in range(rows): + if keep[i]: + condition = (ious[i] > iou_threshold) & (categories[i] == categories) + keep[i + 1 :] = np.where(condition[i + 1 :], False, keep[i + 1 :]) + + return keep[sort_index.argsort()] + + +def box_non_max_suppression( predictions: np.ndarray, iou_threshold: float = 0.5 ) -> np.ndarray: """
diff --git a/test/detection/test_utils.py b/test/detection/test_utils.py index 576b25f8f..d09348ff5 100644 --- a/test/detection/test_utils.py +++ b/test/detection/test_utils.py @@ -6,13 +6,14 @@ from supervision.config import CLASS_NAME_DATA_FIELD from supervision.detection.utils import ( + box_non_max_suppression, calculate_masks_centroids, clip_boxes, filter_polygons_by_area, get_data_item, + mask_non_max_suppression, merge_data, move_boxes, - non_max_suppression, process_roboflow_result, scale_boxes, ) @@ -113,19 +114,225 @@ ), # three boxes with different category ], ) -def test_non_max_suppression( +def test_box_non_max_suppression( predictions: np.ndarray, iou_threshold: float, expected_result: Optional[np.ndarray], exception: Exception, ) -> None: with exception: - result = non_max_suppression( + result = box_non_max_suppression( predictions=predictions, iou_threshold=iou_threshold ) assert np.array_equal(result, expected_result) +@pytest.mark.parametrize( + "predictions, masks, iou_threshold, expected_result, exception", + [ + ( + np.empty((0, 6)), + np.empty((0, 5, 5)), + 0.5, + np.array([]), + DoesNotRaise(), + ), # empty predictions and masks + ( + np.array([[0, 0, 0, 0, 0.8]]), + np.array( + [ + [ + [False, False, False, False, False], + [False, True, True, True, False], + [False, True, True, True, False], + [False, True, True, True, False], + [False, False, False, False, False], + ] + ] + ), + 0.5, + np.array([True]), + DoesNotRaise(), + ), # single mask with no category + ( + np.array([[0, 0, 0, 0, 0.8, 0]]), + np.array( + [ + [ + [False, False, False, False, False], + [False, True, True, True, False], + [False, True, True, True, False], + [False, True, True, True, False], + [False, False, False, False, False], + ] + ] + ), + 0.5, + np.array([True]), + DoesNotRaise(), + ), # single mask with category + ( + np.array([[0, 0, 0, 0, 0.8], [0, 0, 0, 0, 0.9]]), + np.array( + [ + [ + [False, False, False, False, False], + [False, True, True, False, False], + [False, True, True, False, False], + [False, False, False, False, False], + [False, False, False, False, False], + ], + [ + [False, False, False, False, False], + [False, False, False, False, False], + [False, False, False, True, True], + [False, False, False, True, True], + [False, False, False, False, False], + ], + ] + ), + 0.5, + np.array([True, True]), + DoesNotRaise(), + ), # two masks non-overlapping with no category + ( + np.array([[0, 0, 0, 0, 0.8], [0, 0, 0, 0, 0.9]]), + np.array( + [ + [ + [False, False, False, False, False], + [False, True, True, True, False], + [False, True, True, True, False], + [False, True, True, True, False], + [False, False, False, False, False], + ], + [ + [False, False, False, False, False], + [False, False, True, True, True], + [False, False, True, True, True], + [False, False, True, True, True], + [False, False, False, False, False], + ], + ] + ), + 0.4, + np.array([False, True]), + DoesNotRaise(), + ), # two masks partially overlapping with no category + ( + np.array([[0, 0, 0, 0, 0.8, 0], [0, 0, 0, 0, 0.9, 1]]), + np.array( + [ + [ + [False, False, False, False, False], + [False, True, True, True, False], + [False, True, True, True, False], + [False, True, True, True, False], + [False, False, False, False, False], + ], + [ + [False, False, False, False, False], + [False, False, True, True, True], + [False, False, True, True, True], + [False, False, True, True, True], + [False, False, False, False, False], + ], + ] + ), + 0.5, + np.array([True, True]), + DoesNotRaise(), + ), # two masks partially overlapping with different category + ( + np.array( + [ + [0, 0, 0, 0, 0.8], + [0, 0, 0, 0, 0.85], + [0, 0, 0, 0, 0.9], + ] + ), + np.array( + [ + [ + [False, False, False, False, False], + [False, True, True, False, False], + [False, True, True, False, False], + [False, False, False, False, False], + [False, False, False, False, False], + ], + [ + [False, False, False, False, False], + [False, True, True, False, False], + [False, True, True, False, False], + [False, False, False, False, False], + [False, False, False, False, False], + ], + [ + [False, False, False, False, False], + [False, False, False, True, True], + [False, False, False, True, True], + [False, False, False, False, False], + [False, False, False, False, False], + ], + ] + ), + 0.5, + np.array([False, True, True]), + DoesNotRaise(), + ), # three masks with no category + ( + np.array( + [ + [0, 0, 0, 0, 0.8, 0], + [0, 0, 0, 0, 0.85, 1], + [0, 0, 0, 0, 0.9, 2], + ] + ), + np.array( + [ + [ + [False, False, False, False, False], + [False, True, True, False, False], + [False, True, True, False, False], + [False, False, False, False, False], + [False, False, False, False, False], + ], + [ + [False, False, False, False, False], + [False, True, True, False, False], + [False, True, True, False, False], + [False, True, True, False, False], + [False, False, False, False, False], + ], + [ + [False, False, False, False, False], + [False, True, True, False, False], + [False, True, True, False, False], + [False, False, False, False, False], + [False, False, False, False, False], + ], + ] + ), + 0.5, + np.array([True, True, True]), + DoesNotRaise(), + ), # three masks with different category + ], +) +def test_mask_non_max_suppression( + predictions: np.ndarray, + masks: np.ndarray, + iou_threshold: float, + expected_result: Optional[np.ndarray], + exception: Exception, +) -> None: + with exception: + result = mask_non_max_suppression( + predictions=predictions, masks=masks, iou_threshold=iou_threshold + ) + assert np.array_equal(result, expected_result) + + @pytest.mark.parametrize( "xyxy, resolution_wh, expected_result", [
diff --git a/docs/detection/utils.md b/docs/detection/utils.md index 54d1f279f..74adc6e74 100644 --- a/docs/detection/utils.md +++ b/docs/detection/utils.md @@ -11,10 +11,22 @@ comments: true :::supervision.detection.utils.box_iou_batch <div class="md-typeset"> - <h2>non_max_suppression</h2> + <h2>mask_iou_batch</h2> </div> -:::supervision.detection.utils.non_max_suppression +:::supervision.detection.utils.mask_iou_batch + +<div class="md-typeset"> + <h2>box_non_max_suppression</h2> +</div> + +:::supervision.detection.utils.box_non_max_suppression + +<div class="md-typeset"> + <h2>mask_non_max_suppression</h2> +</div> + +:::supervision.detection.utils.mask_non_max_suppression <div class="md-typeset"> <h2>polygon_to_mask</h2>
[ { "components": [ { "doc": "Compute Intersection over Union (IoU) of two sets of masks -\n `masks_true` and `masks_detection`.\n\nArgs:\n masks_true (np.ndarray): 3D `np.ndarray` representing ground-truth masks.\n masks_detection (np.ndarray): 3D `np.ndarray` representing detection masks.\n\nReturns:\n np.ndarray: Pairwise IoU of masks from `masks_true` and `masks_detection`.", "lines": [ 62, 86 ], "name": "mask_iou_batch", "signature": "def mask_iou_batch(masks_true: np.ndarray, masks_detection: np.ndarray) -> np.ndarray:", "type": "function" }, { "doc": "Resize all masks in the array to have a maximum dimension of max_dimension,\nmaintaining aspect ratio.\n\nArgs:\n masks (np.ndarray): 3D array of binary masks with shape (N, H, W).\n max_dimension (int): The maximum dimension for the resized masks.\n\nReturns:\n np.ndarray: Array of resized masks.", "lines": [ 90, 116 ], "name": "resize_masks", "signature": "def resize_masks(masks: np.ndarray, max_dimension: int = 640) -> np.ndarray:", "type": "function" }, { "doc": "Perform Non-Maximum Suppression (NMS) on segmentation predictions.\n\nArgs:\n predictions (np.ndarray): A 2D array of object detection predictions in\n the format of `(x_min, y_min, x_max, y_max, score)`\n or `(x_min, y_min, x_max, y_max, score, class)`. Shape: `(N, 5)` or\n `(N, 6)`, where N is the number of predictions.\n masks (np.ndarray): A 3D array of binary masks corresponding to the predictions.\n Shape: `(N, H, W)`, where N is the number of predictions, and H, W are the\n dimensions of each mask.\n iou_threshold (float, optional): The intersection-over-union threshold\n to use for non-maximum suppression.\n mask_dimension (int, optional): The dimension to which the masks should be\n resized before computing IOU values. Defaults to 640.\n\nReturns:\n np.ndarray: A boolean array indicating which predictions to keep after\n non-maximum suppression.\n\nRaises:\n AssertionError: If `iou_threshold` is not within the closed\n range from `0` to `1`.", "lines": [ 119, 171 ], "name": "mask_non_max_suppression", "signature": "def mask_non_max_suppression( predictions: np.ndarray, masks: np.ndarray, iou_threshold: float = 0.5, mask_dimension: int = 640, ) -> np.ndarray:", "type": "function" }, { "doc": "Perform Non-Maximum Suppression (NMS) on object detection predictions.\n\nArgs:\n predictions (np.ndarray): An array of object detection predictions in\n the format of `(x_min, y_min, x_max, y_max, score)`\n or `(x_min, y_min, x_max, y_max, score, class)`.\n iou_threshold (float, optional): The intersection-over-union threshold\n to use for non-maximum suppression.\n\nReturns:\n np.ndarray: A boolean array indicating which predictions to keep after n\n on-maximum suppression.\n\nRaises:\n AssertionError: If `iou_threshold` is not within the\n closed range from `0` to `1`.", "lines": [ 174, 225 ], "name": "box_non_max_suppression", "signature": "def box_non_max_suppression( predictions: np.ndarray, iou_threshold: float = 0.5 ) -> np.ndarray:", "type": "function" } ], "file": "supervision/detection/utils.py" } ]
[ "test/detection/test_utils.py::test_box_non_max_suppression[predictions0-0.5-expected_result0-exception0]", "test/detection/test_utils.py::test_box_non_max_suppression[predictions1-0.5-expected_result1-exception1]", "test/detection/test_utils.py::test_box_non_max_suppression[predictions2-0.5-expected_result2-exception2]", "test/detection/test_utils.py::test_box_non_max_suppression[predictions3-0.5-expected_result3-exception3]", "test/detection/test_utils.py::test_box_non_max_suppression[predictions4-0.5-expected_result4-exception4]", "test/detection/test_utils.py::test_box_non_max_suppression[predictions5-0.5-expected_result5-exception5]", "test/detection/test_utils.py::test_box_non_max_suppression[predictions6-0.5-expected_result6-exception6]", "test/detection/test_utils.py::test_box_non_max_suppression[predictions7-0.5-expected_result7-exception7]", "test/detection/test_utils.py::test_box_non_max_suppression[predictions8-0.5-expected_result8-exception8]", "test/detection/test_utils.py::test_mask_non_max_suppression[predictions0-masks0-0.5-expected_result0-exception0]", "test/detection/test_utils.py::test_mask_non_max_suppression[predictions1-masks1-0.5-expected_result1-exception1]", "test/detection/test_utils.py::test_mask_non_max_suppression[predictions2-masks2-0.5-expected_result2-exception2]", "test/detection/test_utils.py::test_mask_non_max_suppression[predictions3-masks3-0.5-expected_result3-exception3]", "test/detection/test_utils.py::test_mask_non_max_suppression[predictions4-masks4-0.4-expected_result4-exception4]", "test/detection/test_utils.py::test_mask_non_max_suppression[predictions5-masks5-0.5-expected_result5-exception5]", "test/detection/test_utils.py::test_mask_non_max_suppression[predictions6-masks6-0.5-expected_result6-exception6]", "test/detection/test_utils.py::test_mask_non_max_suppression[predictions7-masks7-0.5-expected_result7-exception7]", "test/detection/test_utils.py::test_clip_boxes[xyxy0-resolution_wh0-expected_result0]", "test/detection/test_utils.py::test_clip_boxes[xyxy1-resolution_wh1-expected_result1]", "test/detection/test_utils.py::test_clip_boxes[xyxy2-resolution_wh2-expected_result2]", "test/detection/test_utils.py::test_clip_boxes[xyxy3-resolution_wh3-expected_result3]", "test/detection/test_utils.py::test_clip_boxes[xyxy4-resolution_wh4-expected_result4]", "test/detection/test_utils.py::test_clip_boxes[xyxy5-resolution_wh5-expected_result5]", "test/detection/test_utils.py::test_filter_polygons_by_area[polygons0-None-None-expected_result0-exception0]", "test/detection/test_utils.py::test_filter_polygons_by_area[polygons1-50-None-expected_result1-exception1]", "test/detection/test_utils.py::test_filter_polygons_by_area[polygons2-None-50-expected_result2-exception2]", "test/detection/test_utils.py::test_filter_polygons_by_area[polygons3-200-None-expected_result3-exception3]", "test/detection/test_utils.py::test_filter_polygons_by_area[polygons4-None-200-expected_result4-exception4]", "test/detection/test_utils.py::test_filter_polygons_by_area[polygons5-200-200-expected_result5-exception5]", "test/detection/test_utils.py::test_filter_polygons_by_area[polygons6-100-100-expected_result6-exception6]", "test/detection/test_utils.py::test_filter_polygons_by_area[polygons7-400-400-expected_result7-exception7]", "test/detection/test_utils.py::test_process_roboflow_result[roboflow_result0-expected_result0-exception0]", "test/detection/test_utils.py::test_process_roboflow_result[roboflow_result1-expected_result1-exception1]", "test/detection/test_utils.py::test_process_roboflow_result[roboflow_result2-expected_result2-exception2]", "test/detection/test_utils.py::test_process_roboflow_result[roboflow_result3-expected_result3-exception3]", "test/detection/test_utils.py::test_process_roboflow_result[roboflow_result4-expected_result4-exception4]", "test/detection/test_utils.py::test_process_roboflow_result[roboflow_result5-expected_result5-exception5]", "test/detection/test_utils.py::test_process_roboflow_result[roboflow_result6-expected_result6-exception6]", "test/detection/test_utils.py::test_move_boxes[xyxy0-offset0-expected_result0-exception0]", "test/detection/test_utils.py::test_move_boxes[xyxy1-offset1-expected_result1-exception1]", "test/detection/test_utils.py::test_move_boxes[xyxy2-offset2-expected_result2-exception2]", "test/detection/test_utils.py::test_move_boxes[xyxy3-offset3-expected_result3-exception3]", "test/detection/test_utils.py::test_move_boxes[xyxy4-offset4-expected_result4-exception4]", "test/detection/test_utils.py::test_scale_boxes[xyxy0-2.0-expected_result0-exception0]", "test/detection/test_utils.py::test_scale_boxes[xyxy1-1.0-expected_result1-exception1]", "test/detection/test_utils.py::test_scale_boxes[xyxy2-2.0-expected_result2-exception2]", "test/detection/test_utils.py::test_scale_boxes[xyxy3-0.5-expected_result3-exception3]", "test/detection/test_utils.py::test_scale_boxes[xyxy4-2.0-expected_result4-exception4]", "test/detection/test_utils.py::test_calculate_masks_centroids[masks0-expected_result0-exception0]", "test/detection/test_utils.py::test_calculate_masks_centroids[masks1-expected_result1-exception1]", "test/detection/test_utils.py::test_calculate_masks_centroids[masks2-expected_result2-exception2]", "test/detection/test_utils.py::test_calculate_masks_centroids[masks3-expected_result3-exception3]", "test/detection/test_utils.py::test_calculate_masks_centroids[masks4-expected_result4-exception4]", "test/detection/test_utils.py::test_merge_data[data_list0-expected_result0-exception0]", "test/detection/test_utils.py::test_merge_data[data_list1-expected_result1-exception1]", "test/detection/test_utils.py::test_merge_data[data_list2-expected_result2-exception2]", "test/detection/test_utils.py::test_merge_data[data_list3-expected_result3-exception3]", "test/detection/test_utils.py::test_merge_data[data_list4-expected_result4-exception4]", "test/detection/test_utils.py::test_merge_data[data_list5-expected_result5-exception5]", "test/detection/test_utils.py::test_merge_data[data_list6-expected_result6-exception6]", "test/detection/test_utils.py::test_merge_data[data_list7-expected_result7-exception7]", "test/detection/test_utils.py::test_merge_data[data_list8-expected_result8-exception8]", "test/detection/test_utils.py::test_merge_data[data_list9-None-exception9]", "test/detection/test_utils.py::test_merge_data[data_list10-expected_result10-exception10]", "test/detection/test_utils.py::test_merge_data[data_list11-expected_result11-exception11]", "test/detection/test_utils.py::test_merge_data[data_list12-expected_result12-exception12]", "test/detection/test_utils.py::test_merge_data[data_list13-expected_result13-exception13]", "test/detection/test_utils.py::test_merge_data[data_list14-None-exception14]", "test/detection/test_utils.py::test_merge_data[data_list15-None-exception15]", "test/detection/test_utils.py::test_get_data_item[data0-0-expected_result0-exception0]", "test/detection/test_utils.py::test_get_data_item[data1-0-expected_result1-exception1]", "test/detection/test_utils.py::test_get_data_item[data2-0-expected_result2-exception2]", "test/detection/test_utils.py::test_get_data_item[data3-index3-expected_result3-exception3]", "test/detection/test_utils.py::test_get_data_item[data4-index4-expected_result4-exception4]", "test/detection/test_utils.py::test_get_data_item[data5--1-expected_result5-exception5]", "test/detection/test_utils.py::test_get_data_item[data6--1-expected_result6-exception6]", "test/detection/test_utils.py::test_get_data_item[data7-index7-expected_result7-exception7]", "test/detection/test_utils.py::test_get_data_item[data8-index8-expected_result8-exception8]", "test/detection/test_utils.py::test_get_data_item[data9-index9-expected_result9-exception9]", "test/detection/test_utils.py::test_get_data_item[data10-index10-expected_result10-exception10]" ]
[]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> [NMS] - add segmentation models support # Description This PR introduces Non-Maximum Suppression (NMS) algorithm focused on segmentation, enhancing our object detection capabilities, particularly in segmentation tasks. We have renamed the traditional `non_max_suppression` function to `box_non_max_suppression` for better clarity regarding its application to bounding boxes. Furthermore, we've integrated a conditional mechanism within the `with_nms` function that utilizes segmentation masks for NMS when such masks are present in the predictions. This optimization leverages the spatial context provided by segmentation masks to improve the suppression process. This enhancement is part of a task segmented into two parts for more focused development and review. This PR addresses the first part, as discussed in the related issue [here](https://github.com/roboflow/supervision/issues/678). Splitting the task ensures thorough implementation and testing of each component. In addition, this PR encompasses comprehensive unit tests for the new NMS functionality and a demo that demonstrates the algorithm's application and effectiveness in real-world scenarios. ## Type of change - [x] New feature (non-breaking change which adds functionality) ## How has this change been tested I created a demo to showcase this functionality [here](https://colab.research.google.com/drive/1lpJKXryY59FTrgZU85a3r0KK7gm1OTNh?usp=sharing) ## Docs - [x] Docs updated? What were the changes: ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in supervision/detection/utils.py] (definition of mask_iou_batch:) def mask_iou_batch(masks_true: np.ndarray, masks_detection: np.ndarray) -> np.ndarray: """Compute Intersection over Union (IoU) of two sets of masks - `masks_true` and `masks_detection`. Args: masks_true (np.ndarray): 3D `np.ndarray` representing ground-truth masks. masks_detection (np.ndarray): 3D `np.ndarray` representing detection masks. Returns: np.ndarray: Pairwise IoU of masks from `masks_true` and `masks_detection`.""" (definition of resize_masks:) def resize_masks(masks: np.ndarray, max_dimension: int = 640) -> np.ndarray: """Resize all masks in the array to have a maximum dimension of max_dimension, maintaining aspect ratio. Args: masks (np.ndarray): 3D array of binary masks with shape (N, H, W). max_dimension (int): The maximum dimension for the resized masks. Returns: np.ndarray: Array of resized masks.""" (definition of mask_non_max_suppression:) def mask_non_max_suppression( predictions: np.ndarray, masks: np.ndarray, iou_threshold: float = 0.5, mask_dimension: int = 640, ) -> np.ndarray: """Perform Non-Maximum Suppression (NMS) on segmentation predictions. Args: predictions (np.ndarray): A 2D array of object detection predictions in the format of `(x_min, y_min, x_max, y_max, score)` or `(x_min, y_min, x_max, y_max, score, class)`. Shape: `(N, 5)` or `(N, 6)`, where N is the number of predictions. masks (np.ndarray): A 3D array of binary masks corresponding to the predictions. Shape: `(N, H, W)`, where N is the number of predictions, and H, W are the dimensions of each mask. iou_threshold (float, optional): The intersection-over-union threshold to use for non-maximum suppression. mask_dimension (int, optional): The dimension to which the masks should be resized before computing IOU values. Defaults to 640. Returns: np.ndarray: A boolean array indicating which predictions to keep after non-maximum suppression. Raises: AssertionError: If `iou_threshold` is not within the closed range from `0` to `1`.""" (definition of box_non_max_suppression:) def box_non_max_suppression( predictions: np.ndarray, iou_threshold: float = 0.5 ) -> np.ndarray: """Perform Non-Maximum Suppression (NMS) on object detection predictions. Args: predictions (np.ndarray): An array of object detection predictions in the format of `(x_min, y_min, x_max, y_max, score)` or `(x_min, y_min, x_max, y_max, score, class)`. iou_threshold (float, optional): The intersection-over-union threshold to use for non-maximum suppression. Returns: np.ndarray: A boolean array indicating which predictions to keep after n on-maximum suppression. Raises: AssertionError: If `iou_threshold` is not within the closed range from `0` to `1`.""" [end of new definitions in supervision/detection/utils.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
3eb5c0b024e3e46877b7fe4fd66e6177d1308ba0
deepset-ai__haystack-6758
6,758
deepset-ai/haystack
null
88191e74bf72345924ed703c65edb9fdf6bd8edd
2024-01-17T14:05:22Z
diff --git a/haystack/components/converters/html.py b/haystack/components/converters/html.py index 0586065c78..dea38dbd1a 100644 --- a/haystack/components/converters/html.py +++ b/haystack/components/converters/html.py @@ -3,7 +3,7 @@ from typing import Any, Dict, List, Optional, Union, Literal from boilerpy3 import extractors -from haystack import Document, component +from haystack import Document, component, default_from_dict, default_to_dict from haystack.dataclasses import ByteStream from haystack.components.converters.utils import get_bytestream_from_source, normalize_metadata @@ -49,6 +49,13 @@ def __init__( """ self.extractor_type = extractor_type + def to_dict(self) -> Dict[str, Any]: + return default_to_dict(self, extractor_type=self.extractor_type) + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "HTMLToDocument": + return default_from_dict(cls, data) + @component.output_types(documents=List[Document]) def run( self,
diff --git a/test/components/converters/test_html_to_document.py b/test/components/converters/test_html_to_document.py index aa8df51197..519a1c053e 100644 --- a/test/components/converters/test_html_to_document.py +++ b/test/components/converters/test_html_to_document.py @@ -160,3 +160,12 @@ def test_mixed_sources_run(self, test_files_path): assert len(docs) == 3 for doc in docs: assert "Haystack" in doc.content + + def test_serde(self): + """ + Test if the component runs correctly gets serialized and deserialized. + """ + converter = HTMLToDocument("ArticleExtractor") + serde_data = converter.to_dict() + new_converter = HTMLToDocument.from_dict(serde_data) + assert new_converter.extractor_type == converter.extractor_type
[ { "components": [ { "doc": "", "lines": [ 52, 53 ], "name": "HTMLToDocument.to_dict", "signature": "def to_dict(self) -> Dict[str, Any]:", "type": "function" }, { "doc": "", "lines": [ 56, 57 ], "name": "HTMLToDocument.from_dict", "signature": "def from_dict(cls, data: Dict[str, Any]) -> \"HTMLToDocument\":", "type": "function" } ], "file": "haystack/components/converters/html.py" } ]
[ "test/components/converters/test_html_to_document.py::TestHTMLToDocument::test_serde" ]
[ "[", "test/components/converters/test_html_to_document.py::TestHTMLToDocument::test_run", "test/components/converters/test_html_to_document.py::TestHTMLToDocument::test_run_different_extractors", "test/components/converters/test_html_to_document.py::TestHTMLToDocument::test_run_doc_metadata", "test/components/converters/test_html_to_document.py::TestHTMLToDocument::test_incorrect_meta", "test/components/converters/test_html_to_document.py::TestHTMLToDocument::test_run_bytestream_metadata", "test/components/converters/test_html_to_document.py::TestHTMLToDocument::test_run_bytestream_and_doc_metadata", "test/components/converters/test_html_to_document.py::TestHTMLToDocument::test_run_bytestream_doc_overlapping_metadata", "test/components/converters/test_html_to_document.py::TestHTMLToDocument::test_run_wrong_file_type", "test/components/converters/test_html_to_document.py::TestHTMLToDocument::test_run_error_handling", "test/components/converters/test_html_to_document.py::TestHTMLToDocument::test_mixed_sources_run" ]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> feat: Add serde methods to `HTMLToDocument` ### Related Issues - fixes #6588 ### How did you test it? <!-- unit tests, integration tests, manual verification, instructions for manual tests --> Unit. ### Checklist - I have read the [contributors guidelines](https://github.com/deepset-ai/haystack/blob/main/CONTRIBUTING.md) and the [code of conduct](https://github.com/deepset-ai/haystack/blob/main/code_of_conduct.txt) - I have updated the related issue with new insights and changes - I added unit tests and updated the docstrings - I've used one of the [conventional commit types](https://www.conventionalcommits.org/en/v1.0.0/) for my PR title: `fix:`, `feat:`, `build:`, `chore:`, `ci:`, `docs:`, `style:`, `refactor:`, `perf:`, `test:`. - I documented my code - I ran [pre-commit hooks](https://github.com/deepset-ai/haystack/blob/main/CONTRIBUTING.md#installation) and fixed any issue ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in haystack/components/converters/html.py] (definition of HTMLToDocument.to_dict:) def to_dict(self) -> Dict[str, Any]: (definition of HTMLToDocument.from_dict:) def from_dict(cls, data: Dict[str, Any]) -> "HTMLToDocument": [end of new definitions in haystack/components/converters/html.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
Here is the discussion in the issues of the pull request. <issues> Add `to_dict` and `from_dict` methods in `HTMLToDocument` `HTMLToDocument` Component is missing serialization methods. We need to add them so it can be properly serialized. ---------- -------------------- </issues>
f4d9c2bb917be0ffe132dffcc2ad4f1b0fcc5967
conan-io__conan-15284
15,284
conan-io/conan
null
98d8f6aaa074b2bf6b827a359daf415f447a86a3
2023-12-16T10:42:15Z
diff --git a/conan/api/subapi/lockfile.py b/conan/api/subapi/lockfile.py index e9fc4daf337..7e4bf7de760 100644 --- a/conan/api/subapi/lockfile.py +++ b/conan/api/subapi/lockfile.py @@ -88,6 +88,12 @@ def add_lockfile(lockfile=None, requires=None, build_requires=None, python_requi python_requires=python_requires) return lockfile + @staticmethod + def remove_lockfile(lockfile, requires=None, build_requires=None, python_requires=None): + lockfile.remove(requires=requires, build_requires=build_requires, + python_requires=python_requires) + return lockfile + @staticmethod def save_lockfile(lockfile, lockfile_out, path=None): if lockfile_out is not None: diff --git a/conan/cli/commands/lock.py b/conan/cli/commands/lock.py index 9831337c29c..31630863a43 100644 --- a/conan/cli/commands/lock.py +++ b/conan/cli/commands/lock.py @@ -6,7 +6,6 @@ from conan.cli import make_abs_path from conan.cli.args import common_graph_args, validate_common_graph_args from conan.cli.printers.graph import print_graph_packages, print_graph_basic -from conans.client.cache.cache import ClientCache from conans.model.graph_lock import Lockfile, LOCKFILE from conans.model.recipe_ref import RecipeReference @@ -124,3 +123,27 @@ def _parse_requires(reqs): python_requires=python_requires, build_requires=build_requires) conan_api.lockfile.save_lockfile(lockfile, args.lockfile_out) + + +@conan_subcommand() +def lock_remove(conan_api, parser, subparser, *args): + """ + Remove requires, build-requires or python-requires from an existing or new lockfile. + References can be supplied with and without revisions like "--requires=pkg/version", + """ + subparser.add_argument('--requires', action="append", help='Remove references to lockfile.') + subparser.add_argument('--build-requires', action="append", + help='Remove build-requires from lockfile') + subparser.add_argument('--python-requires', action="append", + help='Remove python-requires from lockfile') + subparser.add_argument("--lockfile-out", action=OnceArgument, default=LOCKFILE, + help="Filename of the created lockfile") + subparser.add_argument("--lockfile", action=OnceArgument, help="Filename of the input lockfile") + args = parser.parse_args(*args) + + lockfile = conan_api.lockfile.get_lockfile(lockfile=args.lockfile, partial=True) + lockfile = conan_api.lockfile.remove_lockfile(lockfile, + requires=args.requires, + python_requires=args.python_requires, + build_requires=args.build_requires) + conan_api.lockfile.save_lockfile(lockfile, args.lockfile_out) diff --git a/conans/model/graph_lock.py b/conans/model/graph_lock.py index 789bb081824..3786beb07d5 100644 --- a/conans/model/graph_lock.py +++ b/conans/model/graph_lock.py @@ -1,3 +1,4 @@ +import fnmatch import json import os from collections import OrderedDict @@ -6,6 +7,7 @@ from conans.client.graph.graph import RECIPE_VIRTUAL, RECIPE_CONSUMER, CONTEXT_BUILD, Overrides from conans.errors import ConanException from conans.model.recipe_ref import RecipeReference +from conans.model.version_range import VersionRange from conans.util.files import load, save LOCKFILE = "conan.lock" @@ -64,6 +66,23 @@ def add(self, ref, package_ids=None): raise ConanException(f"Cannot add {ref} to lockfile, already exists") self._requires[ref] = package_ids + def remove(self, pattern): + ref = RecipeReference.loads(pattern) + version = str(ref.version) + remove = [] + if version.startswith("[") and version.endswith("]"): + version_range = VersionRange(version[1:-1]) + for k, v in self._requires.items(): + if fnmatch.fnmatch(k.name, ref.name) and version_range.contains(k.version, None): + new_pattern = f"{k.name}/*@{ref.user or ''}" + new_pattern += f"/{ref.channel}" if ref.channel else "" + if k.matches(new_pattern, False): + remove.append(k) + else: + remove = [k for k in self._requires if k.matches(pattern, False)] + self._requires = OrderedDict((k, v) for k, v in self._requires.items() if k not in remove) + return remove + def sort(self): self._requires = OrderedDict(reversed(sorted(self._requires.items()))) @@ -171,6 +190,19 @@ def add(self, requires=None, build_requires=None, python_requires=None): self._python_requires.add(r) self._python_requires.sort() + def remove(self, requires=None, build_requires=None, python_requires=None): + def _remove(reqs, self_reqs, name): + if reqs: + removed = [] + for r in reqs: + removed.extend(self_reqs.remove(r)) + for d in removed: + ConanOutput().info(f"Removed locked {name}: {d.repr_notime()}") + + _remove(requires, self._requires, "require") + _remove(build_requires, self._build_requires, "build_require") + _remove(python_requires, self._python_requires, "python_require") + @staticmethod def deserialize(data): """ constructs a GraphLock from a json like dict
diff --git a/conans/test/integration/lockfile/test_user_overrides.py b/conans/test/integration/lockfile/test_user_overrides.py index f37a91c4259..53648a5c6c2 100644 --- a/conans/test/integration/lockfile/test_user_overrides.py +++ b/conans/test/integration/lockfile/test_user_overrides.py @@ -1,4 +1,7 @@ import json +import textwrap + +import pytest from conans.test.assets.genconanfile import GenConanfile from conans.test.utils.tools import TestClient @@ -211,3 +214,106 @@ def test_lock_add_error(): c = TestClient() c.run(f"lock add --requires=math/1.0:pid1", assert_error=True) assert "ERROR: Invalid recipe reference 'math/1.0:pid1' is a package reference" in c.out + + +class TestLockRemove: + @pytest.mark.parametrize("args, removed", [ + ("--requires=math/*", ["math"]), + ("--requires=math/2.0", []), + ("--build-requires=cmake/1.0", ["cmake"]), + # Not valid ("--build-requires=*", ["cmake", "ninja"]), + ("--build-requires=*/*", ["cmake", "ninja"]), # But this is valid + ("--python-requires=mytool/*", ["mytool"]), + ("--python-requires=*tool/*", ["mytool", "othertool"]), + # With version ranges + ('--requires="math/[>=1.0 <2]"', ["math"]), + ('--requires="math/[>1.0]"', []), + ('--requires="*/[>=1.0 <2]"', ["math", "engine"]) + ]) + def test_lock_remove(self, args, removed): + c = TestClient() + lock = textwrap.dedent("""\ + { + "version": "0.5", + "requires": [ + "math/1.0#85d927a4a067a531b1a9c7619522c015%1702683583.3411012", + "math/1.0#12345%1702683584.3411012", + "engine/1.0#fd2b006646a54397c16a1478ac4111ac%1702683583.3544693" + ], + "build_requires": [ + "cmake/1.0#85d927a4a067a531b1a9c7619522c015%1702683583.3411012", + "ninja/1.0#fd2b006646a54397c16a1478ac4111ac%1702683583.3544693" + ], + "python_requires": [ + "mytool/1.0#85d927a4a067a531b1a9c7619522c015%1702683583.3411012", + "othertool/1.0#fd2b006646a54397c16a1478ac4111ac%1702683583.3544693" + ] + } + """) + c.save({"conan.lock": lock}) + c.run(f"lock remove {args}") + lock = c.load("conan.lock") + for remove in removed: + assert remove not in lock + for pkg in {"math", "engine", "cmake", "ninja", "mytool", "othertool"}.difference(removed): + assert pkg in lock + + @pytest.mark.parametrize("args, removed", [ + ("--requires=math/1.0#12345*", ["math/1.0#123456789abcdef"]), + ("--requires=math/1.0#*", ["math/1.0#123456789abcdef", + "math/1.0#85d927a4a067a531b1a9c7619522c015"]), + ]) + def test_lock_remove_revisions(self, args, removed): + c = TestClient() + lock = textwrap.dedent("""\ + { + "version": "0.5", + "requires": [ + "math/1.0#123456789abcdef%1702683584.3411012", + "math/1.0#85d927a4a067a531b1a9c7619522c015%1702683583.3411012", + "engine/1.0#fd2b006646a54397c16a1478ac4111ac%1702683583.3544693" + ] + } + """) + c.save({"conan.lock": lock}) + c.run(f"lock remove {args}") + lock = c.load("conan.lock") + for remove in removed: + assert remove not in lock + for pkg in {"math/1.0#123456789abcdef", + "math/1.0#85d927a4a067a531b1a9c7619522c015", + "engine/1.0#fd2b006646a54397c16a1478ac4111ac"}.difference(removed): + assert pkg in lock + + @pytest.mark.parametrize("args, removed", [ + ("--requires=*/*@team", ["pkg/1.0@team"]), + ("--requires=*/*@team*", ["pkg/1.0@team", "math/2.0@team/stable"]), + ("--requires=*/*@user", ["math/1.0@user", "other/1.0@user"]), + ("--requires=*/*@", ["engine/1.0"]), # Remove those without user + # with version ranges + ("--requires=math/[*]@user", ["math/1.0@user"]), + ("--requires=math/[*]@team*", ["math/2.0@team/stable"]), + ]) + def test_lock_remove_user_channel(self, args, removed): + c = TestClient() + lock = textwrap.dedent("""\ + { + "version": "0.5", + "requires": [ + "math/1.0@user#123456789abcdef%1702683584.3411012", + "math/2.0@team/stable#123456789abcdef%1702683584.3411012", + "other/1.0@user#85d927a4a067a531b1a9c7619522c015%1702683583.3411012", + "pkg/1.0@team#85d927a4a067a531b1a9c7619522c015%1702683583.3411012", + "engine/1.0#fd2b006646a54397c16a1478ac4111ac%1702683583.3544693" + ] + } + """) + c.save({"conan.lock": lock}) + c.run(f"lock remove {args}") + lock = c.load("conan.lock") + for remove in removed: + assert remove not in lock + rest = {"math/1.0@user", "math/2.0@team/stable", + "other/1.0@user", "pkg/1.0@team", "engine/1.0"}.difference(removed) + for pkg in rest: + assert pkg in lock
[ { "components": [ { "doc": "", "lines": [ 92, 95 ], "name": "LockfileAPI.remove_lockfile", "signature": "def remove_lockfile(lockfile, requires=None, build_requires=None, python_requires=None):", "type": "function" } ], "file": "conan/api/subapi/lockfile.py" }, { "components": [ { "doc": "Remove requires, build-requires or python-requires from an existing or new lockfile.\nReferences can be supplied with and without revisions like \"--requires=pkg/version\",", "lines": [ 129, 149 ], "name": "lock_remove", "signature": "def lock_remove(conan_api, parser, subparser, *args):", "type": "function" } ], "file": "conan/cli/commands/lock.py" }, { "components": [ { "doc": "", "lines": [ 69, 84 ], "name": "_LockRequires.remove", "signature": "def remove(self, pattern):", "type": "function" }, { "doc": "", "lines": [ 193, 204 ], "name": "Lockfile.remove", "signature": "def remove(self, requires=None, build_requires=None, python_requires=None):", "type": "function" }, { "doc": "", "lines": [ 194, 200 ], "name": "Lockfile.remove._remove", "signature": "def _remove(reqs, self_reqs, name):", "type": "function" } ], "file": "conans/model/graph_lock.py" } ]
[ "conans/test/integration/lockfile/test_user_overrides.py::TestLockRemove::test_lock_remove[--requires=math/*-removed0]", "conans/test/integration/lockfile/test_user_overrides.py::TestLockRemove::test_lock_remove[--requires=math/2.0-removed1]", "conans/test/integration/lockfile/test_user_overrides.py::TestLockRemove::test_lock_remove[--build-requires=cmake/1.0-removed2]", "conans/test/integration/lockfile/test_user_overrides.py::TestLockRemove::test_lock_remove[--build-requires=*/*-removed3]", "conans/test/integration/lockfile/test_user_overrides.py::TestLockRemove::test_lock_remove[--python-requires=mytool/*-removed4]", "conans/test/integration/lockfile/test_user_overrides.py::TestLockRemove::test_lock_remove[--python-requires=*tool/*-removed5]", "conans/test/integration/lockfile/test_user_overrides.py::TestLockRemove::test_lock_remove[--requires=\"math/[>=1.0", "conans/test/integration/lockfile/test_user_overrides.py::TestLockRemove::test_lock_remove[--requires=\"math/[>1.0]\"-removed7]", "conans/test/integration/lockfile/test_user_overrides.py::TestLockRemove::test_lock_remove[--requires=\"*/[>=1.0", "conans/test/integration/lockfile/test_user_overrides.py::TestLockRemove::test_lock_remove_revisions[--requires=math/1.0#12345*-removed0]", "conans/test/integration/lockfile/test_user_overrides.py::TestLockRemove::test_lock_remove_revisions[--requires=math/1.0#*-removed1]", "conans/test/integration/lockfile/test_user_overrides.py::TestLockRemove::test_lock_remove_user_channel[--requires=*/*@team-removed0]", "conans/test/integration/lockfile/test_user_overrides.py::TestLockRemove::test_lock_remove_user_channel[--requires=*/*@team*-removed1]", "conans/test/integration/lockfile/test_user_overrides.py::TestLockRemove::test_lock_remove_user_channel[--requires=*/*@user-removed2]", "conans/test/integration/lockfile/test_user_overrides.py::TestLockRemove::test_lock_remove_user_channel[--requires=*/*@-removed3]", "conans/test/integration/lockfile/test_user_overrides.py::TestLockRemove::test_lock_remove_user_channel[--requires=math/[*]@user-removed4]", "conans/test/integration/lockfile/test_user_overrides.py::TestLockRemove::test_lock_remove_user_channel[--requires=math/[*]@team*-removed5]" ]
[ "conans/test/integration/lockfile/test_user_overrides.py::test_user_overrides", "conans/test/integration/lockfile/test_user_overrides.py::test_user_build_overrides", "conans/test/integration/lockfile/test_user_overrides.py::test_user_python_overrides", "conans/test/integration/lockfile/test_user_overrides.py::test_add_revisions", "conans/test/integration/lockfile/test_user_overrides.py::test_add_multiple_revisions", "conans/test/integration/lockfile/test_user_overrides.py::test_timestamps_are_updated", "conans/test/integration/lockfile/test_user_overrides.py::test_lock_add_error" ]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> new lock remove command Changelog: Feature: New ``conan lock remove`` command to remove requires from lockfiles. Docs: https://github.com/conan-io/docs/pull/3496 I am proposing this PR to close: Close https://github.com/conan-io/conan/issues/14523 Close https://github.com/conan-io/conan/issues/14524 The idea is that updates are equivalent to something like: ```bash $ conan remove --requires=zlib/* && conan add --requires=zlib/1.2.11 ``` But it will allow us to first iterate and learn about the logic of removal of versions from lockfiles, because ``conan remove`` makes sense in isolation, even without ``lock update`` or ``lock add``, like for example using it before resolving it to latest with ``--lockfile-partial``. When we have clear what is the UX and UI for the removal, we can do a single command ``conan update`` or ``conan add`` with extra arguments ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in conan/api/subapi/lockfile.py] (definition of LockfileAPI.remove_lockfile:) def remove_lockfile(lockfile, requires=None, build_requires=None, python_requires=None): [end of new definitions in conan/api/subapi/lockfile.py] [start of new definitions in conan/cli/commands/lock.py] (definition of lock_remove:) def lock_remove(conan_api, parser, subparser, *args): """Remove requires, build-requires or python-requires from an existing or new lockfile. References can be supplied with and without revisions like "--requires=pkg/version",""" [end of new definitions in conan/cli/commands/lock.py] [start of new definitions in conans/model/graph_lock.py] (definition of _LockRequires.remove:) def remove(self, pattern): (definition of Lockfile.remove:) def remove(self, requires=None, build_requires=None, python_requires=None): (definition of Lockfile.remove._remove:) def _remove(reqs, self_reqs, name): [end of new definitions in conans/model/graph_lock.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
4a5b19a75db9225316c8cb022a2dfb9705a2af34
astronomer__astronomer-cosmos-758
758
astronomer/astronomer-cosmos
null
9fcee8e785ea3bcb0d19e8d36f3f5b94bedafc98
2023-12-11T01:54:27Z
diff --git a/cosmos/profiles/athena/access_key.py b/cosmos/profiles/athena/access_key.py index a8f71c2b7..02de2be24 100644 --- a/cosmos/profiles/athena/access_key.py +++ b/cosmos/profiles/athena/access_key.py @@ -3,20 +3,33 @@ from typing import Any +from cosmos.exceptions import CosmosValueError + from ..base import BaseProfileMapping class AthenaAccessKeyProfileMapping(BaseProfileMapping): """ - Maps Airflow AWS connections to a dbt Athena profile using an access key id and secret access key. + Uses the Airflow AWS Connection provided to get_credentials() to generate the profile for dbt. - https://docs.getdbt.com/docs/core/connect-data-platform/athena-setup https://airflow.apache.org/docs/apache-airflow-providers-amazon/stable/connections/aws.html + + + This behaves similarly to other provider operators such as the AWS Athena Operator. + Where you pass the aws_conn_id and the operator will generate the credentials for you. + + https://registry.astronomer.io/providers/amazon/versions/latest/modules/athenaoperator + + Information about the dbt Athena profile that is generated can be found here: + + https://github.com/dbt-athena/dbt-athena?tab=readme-ov-file#configuring-your-profile + https://docs.getdbt.com/docs/core/connect-data-platform/athena-setup """ airflow_connection_type: str = "aws" dbt_profile_type: str = "athena" is_community: bool = True + temporary_credentials = None required_fields = [ "aws_access_key_id", @@ -26,11 +39,7 @@ class AthenaAccessKeyProfileMapping(BaseProfileMapping): "s3_staging_dir", "schema", ] - secret_fields = ["aws_secret_access_key", "aws_session_token"] airflow_param_mapping = { - "aws_access_key_id": "login", - "aws_secret_access_key": "password", - "aws_session_token": "extra.aws_session_token", "aws_profile_name": "extra.aws_profile_name", "database": "extra.database", "debug_query_state": "extra.debug_query_state", @@ -49,11 +58,43 @@ class AthenaAccessKeyProfileMapping(BaseProfileMapping): @property def profile(self) -> dict[str, Any | None]: "Gets profile. The password is stored in an environment variable." + + self.temporary_credentials = self._get_temporary_credentials() # type: ignore + profile = { **self.mapped_params, **self.profile_args, - # aws_secret_access_key and aws_session_token should always get set as env var + "aws_access_key_id": self.temporary_credentials.access_key, "aws_secret_access_key": self.get_env_var_format("aws_secret_access_key"), "aws_session_token": self.get_env_var_format("aws_session_token"), } + return self.filter_null(profile) + + @property + def env_vars(self) -> dict[str, str]: + "Overwrites the env_vars for athena, Returns a dictionary of environment variables that should be set based on the self.temporary_credentials." + + if self.temporary_credentials is None: + raise CosmosValueError(f"Could not find the athena credentials.") + + env_vars = {} + + env_secret_key_name = self.get_env_var_name("aws_secret_access_key") + env_session_token_name = self.get_env_var_name("aws_session_token") + + env_vars[env_secret_key_name] = str(self.temporary_credentials.secret_key) + env_vars[env_session_token_name] = str(self.temporary_credentials.token) + + return env_vars + + def _get_temporary_credentials(self): # type: ignore + """ + Helper function to retrieve temporary short lived credentials + Returns an object including access_key, secret_key and token + """ + from airflow.providers.amazon.aws.hooks.base_aws import AwsGenericHook + + hook = AwsGenericHook(self.conn_id) # type: ignore + credentials = hook.get_credentials() + return credentials diff --git a/pyproject.toml b/pyproject.toml index c08de4ade..9d367c075 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -57,6 +57,7 @@ dbt-all = [ ] dbt-athena = [ "dbt-athena-community", + "apache-airflow-providers-amazon>=8.0.0", ] dbt-bigquery = [ "dbt-bigquery", @@ -110,7 +111,6 @@ tests = [ "mypy", "sqlalchemy-stubs", # Change when sqlalchemy is upgraded https://docs.sqlalchemy.org/en/14/orm/extensions/mypy.html ] - docker = [ "apache-airflow-providers-docker>=3.5.0", ] @@ -121,7 +121,6 @@ pydantic = [ "pydantic>=1.10.0,<2.0.0", ] - [project.entry-points.cosmos] provider_info = "cosmos:get_provider_info"
diff --git a/tests/profiles/athena/test_athena_access_key.py b/tests/profiles/athena/test_athena_access_key.py index 22c8efa2c..c224a9d4b 100644 --- a/tests/profiles/athena/test_athena_access_key.py +++ b/tests/profiles/athena/test_athena_access_key.py @@ -1,20 +1,49 @@ "Tests for the Athena profile." import json -from unittest.mock import patch - +from collections import namedtuple +import sys +from unittest.mock import MagicMock, patch import pytest from airflow.models.connection import Connection from cosmos.profiles import get_automatic_profile_mapping from cosmos.profiles.athena.access_key import AthenaAccessKeyProfileMapping +Credentials = namedtuple("Credentials", ["access_key", "secret_key", "token"]) + +mock_assumed_credentials = Credentials( + secret_key="my_aws_assumed_secret_key", + access_key="my_aws_assumed_access_key", + token="my_aws_assumed_token", +) + +mock_missing_credentials = Credentials(access_key=None, secret_key=None, token=None) + + +@pytest.fixture(autouse=True) +def mock_aws_module(): + mock_aws_hook = MagicMock() + + class MockAwsGenericHook: + def __init__(self, conn_id: str) -> None: + pass + + def get_credentials(self) -> Credentials: + return mock_assumed_credentials + + mock_aws_hook.AwsGenericHook = MockAwsGenericHook + + with patch.dict(sys.modules, {"airflow.providers.amazon.aws.hooks.base_aws": mock_aws_hook}): + yield mock_aws_hook + @pytest.fixture() def mock_athena_conn(): # type: ignore """ Sets the connection as an environment variable. """ + conn = Connection( conn_id="my_athena_connection", conn_type="aws", @@ -24,7 +53,7 @@ def mock_athena_conn(): # type: ignore { "aws_session_token": "token123", "database": "my_database", - "region_name": "my_region", + "region_name": "us-east-1", "s3_staging_dir": "s3://my_bucket/dbt/", "schema": "my_schema", } @@ -48,6 +77,7 @@ def test_athena_connection_claiming() -> None: # - region_name # - s3_staging_dir # - schema + potential_values = { "conn_type": "aws", "login": "my_aws_access_key_id", @@ -55,7 +85,7 @@ def test_athena_connection_claiming() -> None: "extra": json.dumps( { "database": "my_database", - "region_name": "my_region", + "region_name": "us-east-1", "s3_staging_dir": "s3://my_bucket/dbt/", "schema": "my_schema", } @@ -68,12 +98,14 @@ def test_athena_connection_claiming() -> None: del values[key] conn = Connection(**values) # type: ignore - print("testing with", values) - - with patch("airflow.hooks.base.BaseHook.get_connection", return_value=conn): - # should raise an InvalidMappingException - profile_mapping = AthenaAccessKeyProfileMapping(conn, {}) - assert not profile_mapping.can_claim_connection() + with patch( + "cosmos.profiles.athena.access_key.AthenaAccessKeyProfileMapping._get_temporary_credentials", + return_value=mock_missing_credentials, + ): + with patch("airflow.hooks.base.BaseHook.get_connection", return_value=conn): + # should raise an InvalidMappingException + profile_mapping = AthenaAccessKeyProfileMapping(conn, {}) + assert not profile_mapping.can_claim_connection() # if we have them all, it should claim conn = Connection(**potential_values) # type: ignore @@ -88,6 +120,7 @@ def test_athena_profile_mapping_selected( """ Tests that the correct profile mapping is selected for Athena. """ + profile_mapping = get_automatic_profile_mapping( mock_athena_conn.conn_id, ) @@ -100,13 +133,14 @@ def test_athena_profile_args( """ Tests that the profile values get set correctly for Athena. """ + profile_mapping = get_automatic_profile_mapping( mock_athena_conn.conn_id, ) assert profile_mapping.profile == { "type": "athena", - "aws_access_key_id": mock_athena_conn.login, + "aws_access_key_id": mock_assumed_credentials.access_key, "aws_secret_access_key": "{{ env_var('COSMOS_CONN_AWS_AWS_SECRET_ACCESS_KEY') }}", "aws_session_token": "{{ env_var('COSMOS_CONN_AWS_AWS_SESSION_TOKEN') }}", "database": mock_athena_conn.extra_dejson.get("database"), @@ -122,9 +156,14 @@ def test_athena_profile_args_overrides( """ Tests that you can override the profile values for Athena. """ + profile_mapping = get_automatic_profile_mapping( mock_athena_conn.conn_id, - profile_args={"schema": "my_custom_schema", "database": "my_custom_db", "aws_session_token": "override_token"}, + profile_args={ + "schema": "my_custom_schema", + "database": "my_custom_db", + "aws_session_token": "override_token", + }, ) assert profile_mapping.profile_args == { @@ -135,7 +174,7 @@ def test_athena_profile_args_overrides( assert profile_mapping.profile == { "type": "athena", - "aws_access_key_id": mock_athena_conn.login, + "aws_access_key_id": mock_assumed_credentials.access_key, "aws_secret_access_key": "{{ env_var('COSMOS_CONN_AWS_AWS_SECRET_ACCESS_KEY') }}", "aws_session_token": "{{ env_var('COSMOS_CONN_AWS_AWS_SESSION_TOKEN') }}", "database": "my_custom_db", @@ -151,10 +190,12 @@ def test_athena_profile_env_vars( """ Tests that the environment variables get set correctly for Athena. """ + profile_mapping = get_automatic_profile_mapping( mock_athena_conn.conn_id, ) + assert profile_mapping.env_vars == { - "COSMOS_CONN_AWS_AWS_SECRET_ACCESS_KEY": mock_athena_conn.password, - "COSMOS_CONN_AWS_AWS_SESSION_TOKEN": mock_athena_conn.extra_dejson.get("aws_session_token"), + "COSMOS_CONN_AWS_AWS_SECRET_ACCESS_KEY": mock_assumed_credentials.secret_key, + "COSMOS_CONN_AWS_AWS_SESSION_TOKEN": mock_assumed_credentials.token, }
diff --git a/pyproject.toml b/pyproject.toml index c08de4ade..9d367c075 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -57,6 +57,7 @@ dbt-all = [ ] dbt-athena = [ "dbt-athena-community", + "apache-airflow-providers-amazon>=8.0.0", ] dbt-bigquery = [ "dbt-bigquery", @@ -110,7 +111,6 @@ tests = [ "mypy", "sqlalchemy-stubs", # Change when sqlalchemy is upgraded https://docs.sqlalchemy.org/en/14/orm/extensions/mypy.html ] - docker = [ "apache-airflow-providers-docker>=3.5.0", ] @@ -121,7 +121,6 @@ pydantic = [ "pydantic>=1.10.0,<2.0.0", ] - [project.entry-points.cosmos] provider_info = "cosmos:get_provider_info"
[ { "components": [ { "doc": "Overwrites the env_vars for athena, Returns a dictionary of environment variables that should be set based on the self.temporary_credentials.", "lines": [ 75, 89 ], "name": "AthenaAccessKeyProfileMapping.env_vars", "signature": "def env_vars(self) -> dict[str, str]:", "type": "function" }, { "doc": "Helper function to retrieve temporary short lived credentials\nReturns an object including access_key, secret_key and token", "lines": [ 91, 100 ], "name": "AthenaAccessKeyProfileMapping._get_temporary_credentials", "signature": "def _get_temporary_credentials(self):", "type": "function" } ], "file": "cosmos/profiles/athena/access_key.py" } ]
[ "tests/profiles/athena/test_athena_access_key.py::test_athena_connection_claiming", "tests/profiles/athena/test_athena_access_key.py::test_athena_profile_args", "tests/profiles/athena/test_athena_access_key.py::test_athena_profile_args_overrides", "tests/profiles/athena/test_athena_access_key.py::test_athena_profile_env_vars" ]
[ "tests/profiles/athena/test_athena_access_key.py::test_athena_profile_mapping_selected" ]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> Athena - Get temporary credentials from the conn_id ## Description <!-- Add a brief but complete description of the change. --> Passes the `conn_id` to the `AwsGenericHook` and uses `get_credentials()`, which handles the creation of a session, credentials, freezing of credentials & also masking. [See get_credentials() docs here](https://airflow.apache.org/docs/apache-airflow-providers-amazon/stable/_api/airflow/providers/amazon/aws/hooks/base_aws/index.html#airflow.providers.amazon.aws.hooks.base_aws.AwsGenericHook.get_credentials) ## Related Issue(s) #691 <!-- If this PR closes an issue, you can use a keyword to auto-close. --> <!-- i.e. "closes #0000" --> ## Breaking Change? <!-- If this introduces a breaking change, specify that here. --> ## Checklist - [ ] I have made corresponding changes to the documentation (if required) - [X] I have added tests that prove my fix is effective or that my feature works ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in cosmos/profiles/athena/access_key.py] (definition of AthenaAccessKeyProfileMapping.env_vars:) def env_vars(self) -> dict[str, str]: """Overwrites the env_vars for athena, Returns a dictionary of environment variables that should be set based on the self.temporary_credentials.""" (definition of AthenaAccessKeyProfileMapping._get_temporary_credentials:) def _get_temporary_credentials(self): """Helper function to retrieve temporary short lived credentials Returns an object including access_key, secret_key and token""" [end of new definitions in cosmos/profiles/athena/access_key.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
c5edba07d2265d5185eaba149a639e8a0740e498
roboflow__supervision-620
620
roboflow/supervision
null
10c44b0143c13b33c1951509f9f11c37c6373752
2023-11-26T10:27:34Z
diff --git a/supervision/draw/color.py b/supervision/draw/color.py index 69bcc9c5e..9d1b4ad98 100644 --- a/supervision/draw/color.py +++ b/supervision/draw/color.py @@ -71,6 +71,21 @@ def from_hex(cls, color_hex: str) -> Color: r, g, b = (int(color_hex[i : i + 2], 16) for i in range(0, 6, 2)) return cls(r, g, b) + def as_hex(self) -> str: + """ + Converts the Color instance to a hex string. + + Returns: + str: The hexadecimal color string. + + Example: + ``` + >>> Color(r=255, g=0, b=255).as_hex() + '#ff00ff' + ``` + """ + return f"#{self.r:02x}{self.g:02x}{self.b:02x}" + def as_rgb(self) -> Tuple[int, int, int]: """ Returns the color as an RGB tuple.
diff --git a/test/draw/test_color.py b/test/draw/test_color.py index 723f7043e..eb4c36574 100644 --- a/test/draw/test_color.py +++ b/test/draw/test_color.py @@ -30,3 +30,22 @@ def test_color_from_hex( with exception: result = Color.from_hex(color_hex=color_hex) assert result == expected_result + + +@pytest.mark.parametrize( + "color, expected_result, exception", + [ + (Color.white(), "#ffffff", DoesNotRaise()), + (Color.black(), "#000000", DoesNotRaise()), + (Color.red(), "#ff0000", DoesNotRaise()), + (Color.green(), "#00ff00", DoesNotRaise()), + (Color.blue(), "#0000ff", DoesNotRaise()), + (Color(r=128, g=128, b=0), "#808000", DoesNotRaise()), + ], +) +def test_color_as_hex( + color: Color, expected_result: Optional[str], exception: Exception +) -> None: + with exception: + result = color.as_hex() + assert result == expected_result
[ { "components": [ { "doc": "Converts the Color instance to a hex string.\n\nReturns:\n str: The hexadecimal color string.\n\nExample:\n ```\n >>> Color(r=255, g=0, b=255).as_hex()\n '#ff00ff'\n ```", "lines": [ 74, 87 ], "name": "Color.as_hex", "signature": "def as_hex(self) -> str:", "type": "function" } ], "file": "supervision/draw/color.py" } ]
[ "test/draw/test_color.py::test_color_as_hex[color0-#ffffff-exception0]", "test/draw/test_color.py::test_color_as_hex[color1-#000000-exception1]", "test/draw/test_color.py::test_color_as_hex[color2-#ff0000-exception2]", "test/draw/test_color.py::test_color_as_hex[color3-#00ff00-exception3]", "test/draw/test_color.py::test_color_as_hex[color4-#0000ff-exception4]", "test/draw/test_color.py::test_color_as_hex[color5-#808000-exception5]" ]
[ "test/draw/test_color.py::test_color_from_hex[fff-expected_result0-exception0]", "test/draw/test_color.py::test_color_from_hex[#fff-expected_result1-exception1]", "test/draw/test_color.py::test_color_from_hex[ffffff-expected_result2-exception2]", "test/draw/test_color.py::test_color_from_hex[#ffffff-expected_result3-exception3]", "test/draw/test_color.py::test_color_from_hex[f00-expected_result4-exception4]", "test/draw/test_color.py::test_color_from_hex[0f0-expected_result5-exception5]", "test/draw/test_color.py::test_color_from_hex[00f-expected_result6-exception6]", "test/draw/test_color.py::test_color_from_hex[#808000-expected_result7-exception7]", "test/draw/test_color.py::test_color_from_hex[-None-exception8]", "test/draw/test_color.py::test_color_from_hex[00-None-exception9]", "test/draw/test_color.py::test_color_from_hex[0000-None-exception10]", "test/draw/test_color.py::test_color_from_hex[0000000-None-exception11]", "test/draw/test_color.py::test_color_from_hex[ffg-None-exception12]" ]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> Add 'as_hex' method and corresponding test to `Color` class. ## Type of change Please delete options that are not relevant. - [ ] Bug fix (non-breaking change which fixes an issue) - [x] New feature (non-breaking change which adds functionality) - [ ] This change requires a documentation update ## Docs - [x] Docs updated? What were the changes: ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in supervision/draw/color.py] (definition of Color.as_hex:) def as_hex(self) -> str: """Converts the Color instance to a hex string. Returns: str: The hexadecimal color string. Example: ``` >>> Color(r=255, g=0, b=255).as_hex() '#ff00ff' ```""" [end of new definitions in supervision/draw/color.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
3eb5c0b024e3e46877b7fe4fd66e6177d1308ba0
google-deepmind__optax-632
632
google-deepmind/optax
null
35920a3712d71992429dc0bd605e75d31cbe2b21
2023-11-13T14:40:27Z
diff --git a/optax/__init__.py b/optax/__init__.py index 0b373684d..6f844478d 100644 --- a/optax/__init__.py +++ b/optax/__init__.py @@ -17,6 +17,7 @@ from optax import contrib from optax import losses from optax import monte_carlo +from optax import projections from optax import schedules from optax import second_order from optax import tree_utils diff --git a/optax/projections/__init__.py b/optax/projections/__init__.py new file mode 100644 index 000000000..9b38aeb6c --- /dev/null +++ b/optax/projections/__init__.py @@ -0,0 +1,18 @@ +# Copyright 2021 DeepMind Technologies Limited. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +"""The projections sub-package.""" + +from optax.projections._projections import projection_non_negative diff --git a/optax/projections/_projections.py b/optax/projections/_projections.py new file mode 100644 index 000000000..316cd21fb --- /dev/null +++ b/optax/projections/_projections.py @@ -0,0 +1,39 @@ +# Copyright 2021 DeepMind Technologies Limited. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +"""Euclidean projections.""" + +from typing import Any + +import jax +from jax import tree_util as jtu + + +def projection_non_negative(pytree: Any) -> Any: + r"""Projection onto the non-negative orthant. + + .. math:: + + \underset{p}{\text{argmin}} ~ ||x - p||_2^2 \quad + \textrm{subject to} \quad p \ge 0 + + where :math:`x` is the input pytree. + + Args: + pytree: pytree to project. + Returns: + projected pytree, with the same structure as ``pytree``. + """ + return jtu.tree_map(jax.nn.relu, pytree)
diff --git a/optax/projections/_projections_test.py b/optax/projections/_projections_test.py new file mode 100644 index 000000000..15d4f1204 --- /dev/null +++ b/optax/projections/_projections_test.py @@ -0,0 +1,47 @@ +# Copyright 2021 DeepMind Technologies Limited. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +"""Tests for optax.projections.""" + +from absl.testing import absltest +from absl.testing import parameterized + +import chex +import jax.numpy as jnp +import numpy as np + +from optax import projections as proj + + +class ProjectionsTest(parameterized.TestCase): + + def test_projection_non_negative(self): + # test with array + x = jnp.array([-1.0, 2.0, 3.0]) + expected = jnp.array([0, 2.0, 3.0]) + np.testing.assert_array_equal(proj.projection_non_negative(x), expected) + + # test with tuple + np.testing.assert_array_equal(proj.projection_non_negative((x, x)), + (expected, expected)) + + # test with nested pytree + tree_x = (-1.0, {'k1': 1.0, 'k2': (1.0, 1.0)}, 1.0) + tree_expected = (0.0, {'k1': 1.0, 'k2': (1.0, 1.0)}, 1.0) + chex.assert_trees_all_equal(proj.projection_non_negative(tree_x), + tree_expected) + +if __name__ == '__main__': + absltest.main()
[ { "components": [ { "doc": "Projection onto the non-negative orthant.\n\n.. math::\n\n \\underset{p}{\\text{argmin}} ~ ||x - p||_2^2 \\quad\n \\textrm{subject to} \\quad p \\ge 0\n\nwhere :math:`x` is the input pytree.\n\nArgs:\n pytree: pytree to project.\nReturns:\n projected pytree, with the same structure as ``pytree``.", "lines": [ 24, 39 ], "name": "projection_non_negative", "signature": "def projection_non_negative(pytree: Any) -> Any:", "type": "function" } ], "file": "optax/projections/_projections.py" } ]
[ "optax/projections/_projections_test.py::ProjectionsTest::test_projection_non_negative" ]
[]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> Start optax.projections subpackage and add projection_non_negative. Start optax.projections subpackage and add projection_non_negative. In the future, this subpackage will contain more projections (projection_simplex, projection_l1_ball, etc) as well as non-Euclidean projections. I used typing.Any as a type annotation for pytrees for the time being, as chex.ArrayTree doesn't seem to accept tuples. ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in optax/projections/_projections.py] (definition of projection_non_negative:) def projection_non_negative(pytree: Any) -> Any: """Projection onto the non-negative orthant. .. math:: \underset{p}{\text{argmin}} ~ ||x - p||_2^2 \quad \textrm{subject to} \quad p \ge 0 where :math:`x` is the input pytree. Args: pytree: pytree to project. Returns: projected pytree, with the same structure as ``pytree``.""" [end of new definitions in optax/projections/_projections.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
1e08bccf195ac54e7d9d766eb5e69345bf0e3230
huggingface__datasets-6318
6,318
huggingface/datasets
null
3aeb078ba1afd713e901df43343c160877403d07
2023-10-19T12:19:13Z
diff --git a/src/datasets/utils/py_utils.py b/src/datasets/utils/py_utils.py index 912824fa7f3..243bc0f99c9 100644 --- a/src/datasets/utils/py_utils.py +++ b/src/datasets/utils/py_utils.py @@ -736,6 +736,29 @@ def proxy(func): return proxy +if config.DILL_VERSION < version.parse("0.3.6"): + + @pklregister(set) + def _save_set(pickler, obj): + dill._dill.log.info(f"Se: {obj}") + from datasets.fingerprint import Hasher + + args = (sorted(obj, key=Hasher.hash),) + pickler.save_reduce(set, args, obj=obj) + dill._dill.log.info("# Se") + +elif config.DILL_VERSION.release[:3] in [version.parse("0.3.6").release, version.parse("0.3.7").release]: + + @pklregister(set) + def _save_set(pickler, obj): + dill._dill.logger.trace(pickler, "Se: %s", obj) + from datasets.fingerprint import Hasher + + args = (sorted(obj, key=Hasher.hash),) + pickler.save_reduce(set, args, obj=obj) + dill._dill.logger.trace(pickler, "# Se") + + if config.DILL_VERSION < version.parse("0.3.6"): @pklregister(CodeType)
diff --git a/tests/test_fingerprint.py b/tests/test_fingerprint.py index 5538f27554e..f4d5d65744e 100644 --- a/tests/test_fingerprint.py +++ b/tests/test_fingerprint.py @@ -2,6 +2,7 @@ import os import pickle import subprocess +from functools import partial from hashlib import md5 from pathlib import Path from tempfile import gettempdir @@ -10,6 +11,7 @@ from unittest import TestCase from unittest.mock import patch +import numpy as np import pytest from multiprocess import Pool @@ -254,6 +256,22 @@ def test_hash_same_strings(self): self.assertEqual(hash1, hash2) self.assertEqual(hash1, hash3) + def test_set_stable(self): + rng = np.random.default_rng(42) + set_ = {rng.random() for _ in range(10_000)} + expected_hash = Hasher.hash(set_) + assert expected_hash == Pool(1).apply_async(partial(Hasher.hash, set(set_))).get() + + def test_set_doesnt_depend_on_order(self): + set_ = set("abc") + hash1 = md5(datasets.utils.py_utils.dumps(set_)).hexdigest() + set_ = set("def") + hash2 = md5(datasets.utils.py_utils.dumps(set_)).hexdigest() + set_ = set("cba") + hash3 = md5(datasets.utils.py_utils.dumps(set_)).hexdigest() + self.assertEqual(hash1, hash3) + self.assertNotEqual(hash1, hash2) + @require_tiktoken def test_hash_tiktoken_encoding(self): import tiktoken
[ { "components": [ { "doc": "", "lines": [ 753, 759 ], "name": "_save_set", "signature": "def _save_set(pickler, obj):", "type": "function" } ], "file": "src/datasets/utils/py_utils.py" } ]
[ "tests/test_fingerprint.py::HashingTest::test_set_stable" ]
[ "tests/test_fingerprint.py::RecurseDumpTest::test_dump_ignores_line_definition_of_function", "tests/test_fingerprint.py::RecurseDumpTest::test_dump_ipython_function", "tests/test_fingerprint.py::RecurseDumpTest::test_recurse_dump_for_class", "tests/test_fingerprint.py::RecurseDumpTest::test_recurse_dump_for_function", "tests/test_fingerprint.py::RecurseDumpTest::test_recurse_dump_for_function_with_shuffled_globals", "tests/test_fingerprint.py::RecurseDumpTest::test_recurse_dump_for_method", "tests/test_fingerprint.py::HashingTest::test_hash_class_instance", "tests/test_fingerprint.py::HashingTest::test_hash_same_strings", "tests/test_fingerprint.py::HashingTest::test_hash_simple", "tests/test_fingerprint.py::HashingTest::test_hash_unpicklable", "tests/test_fingerprint.py::HashingTest::test_hash_update", "tests/test_fingerprint.py::HashingTest::test_set_doesnt_depend_on_order", "tests/test_fingerprint.py::test_move_script_doesnt_change_hash", "tests/test_fingerprint.py::test_fingerprint_in_multiprocessing", "tests/test_fingerprint.py::test_fingerprint_when_transform_version_changes", "tests/test_fingerprint.py::test_dependency_on_dill" ]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> Deterministic set hash Sort the items in a set according to their `datasets.fingerprint.Hasher.hash` hash to get a deterministic hash of sets. This is useful to get deterministic hashes of tokenizers that use a trie based on python sets. reported in https://github.com/huggingface/datasets/issues/3847 ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in src/datasets/utils/py_utils.py] (definition of _save_set:) def _save_set(pickler, obj): [end of new definitions in src/datasets/utils/py_utils.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
5142a8cf61d8a4495eda3d91dc4283a6df01ea14
pyvista__pyvista-5055
5,055
pyvista/pyvista
0.43
e574da02bb2c2d7aafb2e8e15f55024505087b56
2023-10-11T23:44:19Z
diff --git a/pyvista/plotting/text.py b/pyvista/plotting/text.py index b5e0292d364..492990d6ed0 100644 --- a/pyvista/plotting/text.py +++ b/pyvista/plotting/text.py @@ -250,6 +250,14 @@ class TextProperty(_vtk.vtkTextProperty): shadow : bool, optional If enable the shadow. + justification_horizontal : str, optional + Text's horizontal justification. + Should be either "left", "center" or "right". + + justification_vertical : str, optional + Text's vertical justification. + Should be either "bottom", "center" or "top". + Examples -------- Create a text's property. @@ -281,6 +289,8 @@ def __init__( font_size=None, font_file=None, shadow=False, + justification_horizontal=None, + justification_vertical=None, ): """Initialize text's property.""" super().__init__() @@ -300,6 +310,10 @@ def __init__( self.set_font_file(font_file) if shadow: self.enable_shadow() + if justification_horizontal is not None: + self.justification_horizontal = justification_horizontal + if justification_vertical is not None: + self.justification_vertical = justification_vertical @property def color(self) -> Color: @@ -486,3 +500,61 @@ def set_font_file(self, font_file: str): raise FileNotFoundError(f'Unable to locate {path}') self.SetFontFamily(_vtk.VTK_FONT_FILE) self.SetFontFile(str(path)) + + @property + def justification_horizontal(self) -> str: + """Text's justification horizontal. + + Returns + ------- + str + Text's horizontal justification. + Should be either "left", "center" or "right". + """ + justification = self.GetJustificationAsString().lower() + if justification == 'centered': + justification = 'center' + return justification + + @justification_horizontal.setter + def justification_horizontal(self, justification: str): # numpydoc ignore=GL08 + if justification.lower() == 'left': + self.SetJustificationToLeft() + elif justification.lower() == 'center': + self.SetJustificationToCentered() + elif justification.lower() == 'right': + self.SetJustificationToRight() + else: + raise ValueError( + f'Invalid {justification} for justification_horizontal. ' + 'Should be either "left", "center" or "right".' + ) + + @property + def justification_vertical(self) -> str: + """Text's vertical justification. + + Returns + ------- + str + Text's vertical justification. + Should be either "bottom", "center" or "top". + """ + justification = self.GetVerticalJustificationAsString().lower() + if justification == 'centered': + justification = 'center' + return justification + + @justification_vertical.setter + def justification_vertical(self, justification: str): # numpydoc ignore=GL08 + if justification.lower() == 'bottom': + self.SetVerticalJustificationToBottom() + elif justification.lower() == 'center': + self.SetVerticalJustificationToCentered() + elif justification.lower() == 'top': + self.SetVerticalJustificationToTop() + else: + raise ValueError( + f'Invalid {justification} for justification_vertical. ' + 'Should be either "bottom", "center" or "top".' + )
diff --git a/tests/plotting/test_text.py b/tests/plotting/test_text.py index 2a15cbb4d46..0046eec024c 100644 --- a/tests/plotting/test_text.py +++ b/tests/plotting/test_text.py @@ -129,3 +129,34 @@ def test_property_set_font_file(prop): prop.set_font_file(font_file) with pytest.raises(FileNotFoundError): prop.set_font_file("foo.ttf") + + +@pytest.mark.parametrize( + 'justification', [('left', 'left'), ('center', 'centered'), ('right', 'right')] +) +def test_property_justification_horizontal(prop, justification): + prop.justification_horizontal = justification[0] + assert prop.GetJustificationAsString().lower() == justification[1] + assert prop.justification_horizontal == justification[0] + prop = pv.TextProperty(justification_horizontal=justification[0]) + assert prop.GetJustificationAsString().lower() == justification[1] + assert prop.justification_horizontal == justification[0] + + +@pytest.mark.parametrize( + 'justification', [('bottom', 'bottom'), ('center', 'centered'), ('top', 'top')] +) +def test_property_justification_vertical(prop, justification): + prop.justification_vertical = justification[0] + assert prop.GetVerticalJustificationAsString().lower() == justification[1] + assert prop.justification_vertical == justification[0] + prop = pv.TextProperty(justification_vertical=justification[0]) + assert prop.GetVerticalJustificationAsString().lower() == justification[1] + assert prop.justification_vertical == justification[0] + + +def test_property_justification_invalid(prop): + with pytest.raises(ValueError): + prop.justification_horizontal = "invalid" + with pytest.raises(ValueError): + prop.justification_vertical = "invalid"
[ { "components": [ { "doc": "", "lines": [ 520, 529 ], "name": "TextProperty.justification_horizontal", "signature": "def justification_horizontal(self, justification: str):", "type": "function" }, { "doc": "", "lines": [ 549, 558 ], "name": "TextProperty.justification_vertical", "signature": "def justification_vertical(self, justification: str):", "type": "function" } ], "file": "pyvista/plotting/text.py" } ]
[ "tests/plotting/test_text.py::test_property_justification_horizontal[justification0]", "tests/plotting/test_text.py::test_property_justification_horizontal[justification1]", "tests/plotting/test_text.py::test_property_justification_horizontal[justification2]", "tests/plotting/test_text.py::test_property_justification_vertical[justification0]", "tests/plotting/test_text.py::test_property_justification_vertical[justification1]", "tests/plotting/test_text.py::test_property_justification_vertical[justification2]", "tests/plotting/test_text.py::test_property_justification_invalid" ]
[ "tests/plotting/test_text.py::test_corner_annotation_text", "tests/plotting/test_text.py::test_corner_annotation_prop", "tests/plotting/test_text.py::test_text_input", "tests/plotting/test_text.py::test_text_prop", "tests/plotting/test_text.py::test_text_position", "tests/plotting/test_text.py::test_property_init", "tests/plotting/test_text.py::test_property_color", "tests/plotting/test_text.py::test_property_opacity", "tests/plotting/test_text.py::test_property_background_color", "tests/plotting/test_text.py::test_property_background_opacity", "tests/plotting/test_text.py::test_property_show_frame", "tests/plotting/test_text.py::test_property_frame_color", "tests/plotting/test_text.py::test_property_frame_width", "tests/plotting/test_text.py::test_property_font_family", "tests/plotting/test_text.py::test_property_font_size", "tests/plotting/test_text.py::test_property_enable_shadow", "tests/plotting/test_text.py::test_property_orientation", "tests/plotting/test_text.py::test_property_set_font_file" ]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> Add `justification` property to `TextProperty` ### Overview <!-- Please insert a high-level description of this pull request here. --> Add `justify` property to `TextProperty`. ```python >>> import pyvista as pv >>> prop = pv.TextProperty() >>> prop.justification_horizontal = "right" >>> prop.justification_vertical = "center" ``` <!-- Be sure to link other PRs or issues that relate to this PR here. --> <!-- If this fully addresses an issue, please use the keyword `resolves` in front of that issue number. --> ### Details - Follow-up of #5044 . ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in pyvista/plotting/text.py] (definition of TextProperty.justification_horizontal:) def justification_horizontal(self, justification: str): (definition of TextProperty.justification_vertical:) def justification_vertical(self, justification: str): [end of new definitions in pyvista/plotting/text.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
25921025e45cafe97b2e274de39c3076b3c84681
softlayer__softlayer-python-2073
2,073
softlayer/softlayer-python
null
fe65dc3e4978e1497f242e0318ed6d43f6659b0b
2023-08-10T07:29:02Z
diff --git a/SoftLayer/CLI/routes.py b/SoftLayer/CLI/routes.py index 54c1deaad..dbaf1cfe0 100644 --- a/SoftLayer/CLI/routes.py +++ b/SoftLayer/CLI/routes.py @@ -403,6 +403,8 @@ ('user:device-access', 'SoftLayer.CLI.user.device_access:cli'), ('user:vpn-manual', 'SoftLayer.CLI.user.vpn_manual:cli'), ('user:vpn-subnet', 'SoftLayer.CLI.user.vpn_subnet:cli'), + ('user:vpn-enable', 'SoftLayer.CLI.user.vpn_enable_or_disable:vpn_enable'), + ('user:vpn-disable', 'SoftLayer.CLI.user.vpn_enable_or_disable:vpn_disable'), ('user:remove-access', 'SoftLayer.CLI.user.remove_access:cli'), ('user:grant-access', 'SoftLayer.CLI.user.grant_access:cli'), ('user:vpn-password', 'SoftLayer.CLI.user.vpn_password:cli'), diff --git a/SoftLayer/CLI/user/vpn_enable_or_disable.py b/SoftLayer/CLI/user/vpn_enable_or_disable.py new file mode 100644 index 000000000..2e8216d26 --- /dev/null +++ b/SoftLayer/CLI/user/vpn_enable_or_disable.py @@ -0,0 +1,49 @@ +"""Enable or Disable vpn for a user.""" +# :license: MIT, see LICENSE for more details. + + +import click + +import SoftLayer +from SoftLayer.CLI import environment +from SoftLayer.CLI import helpers + + +@click.command(cls=SoftLayer.CLI.command.SLCommand, ) +@click.argument('user') +@environment.pass_env +def vpn_enable(env, user): + """Enable vpn for a user. + + Example:: + slcli user vpn-enable 1234567 + """ + + mgr = SoftLayer.UserManager(env.client) + user_id = helpers.resolve_id(mgr.resolve_ids, user, 'username') + + result = mgr.vpn_enable_or_disable(user_id, True) + message = f"{user} vpn is successfully enabled" + + if result: + click.secho(message, fg='green') + + +@click.command(cls=SoftLayer.CLI.command.SLCommand, ) +@click.argument('user') +@environment.pass_env +def vpn_disable(env, user): + """Disable vpn for a user. + + Example:: + slcli user vpn-disable 1234567 + """ + + mgr = SoftLayer.UserManager(env.client) + user_id = helpers.resolve_id(mgr.resolve_ids, user, 'username') + + result = mgr.vpn_enable_or_disable(user_id, False) + message = f"{user} vpn is successfully disabled" + + if result: + click.secho(message, fg='green') diff --git a/SoftLayer/managers/user.py b/SoftLayer/managers/user.py index 6682c0cf5..cafdf1b8f 100644 --- a/SoftLayer/managers/user.py +++ b/SoftLayer/managers/user.py @@ -361,6 +361,17 @@ def vpn_manual(self, user_id, value): user_object = {'vpnManualConfig': value} return self.edit_user(user_id, user_object) + def vpn_enable_or_disable(self, user_id, value): + """Enable or Disable vpn for a user. + + :param int user_id: User to edit. + :param bool value: Value for vpn enable flag. + or + :param bool value: Value for vpn disable flag. + """ + user_object = {'sslVpnAllowedFlag': value} + return self.edit_user(user_id, user_object) + def vpn_subnet_add(self, user_id, subnet_ids): """Add subnets for a user. diff --git a/docs/cli/users.rst b/docs/cli/users.rst index e3d45bb1d..af86b4a94 100644 --- a/docs/cli/users.rst +++ b/docs/cli/users.rst @@ -64,6 +64,14 @@ Version 5.6.0 introduces the ability to interact with user accounts from the cli :prog: user vpn-password :show-nested: +.. click:: SoftLayer.CLI.user.vpn_enable_or_disable:vpn_enable + :prog: user vpn-enable + :show-nested: + +.. click:: SoftLayer.CLI.user.vpn_enable_or_disable:vpn_disable + :prog: user vpn-disable + :show-nested: + .. click:: SoftLayer.CLI.user.apikey:cli :prog: user apikey :show-nested:
diff --git a/tests/CLI/modules/user_tests.py b/tests/CLI/modules/user_tests.py index 02956e682..804c9ef1d 100644 --- a/tests/CLI/modules/user_tests.py +++ b/tests/CLI/modules/user_tests.py @@ -8,10 +8,9 @@ import sys import unittest -from unittest import mock as mock - from SoftLayer.fixtures import SoftLayer_User_Customer from SoftLayer import testing +from unittest import mock as mock class UserCLITests(testing.TestCase): @@ -416,3 +415,27 @@ def test_remove_api_authentication_key(self): def test_refresh_api_authentication_key(self): result = self.run_command(['user', 'apikey', '123456', '--refresh']) self.assert_no_fail(result) + + def test_vpn_disable(self): + result = self.run_command(['user', 'vpn-disable', '8344458']) + self.assert_no_fail(result) + self.assert_called_with('SoftLayer_User_Customer', 'editObject', identifier=8344458) + + result = self.run_command(['user', 'vpn-disable', '8344458']) + permission_m = self.set_mock('SoftLayer_User_Customer', 'editObject') + permission_m.return_value = {'sslVpnAllowedFlag': False} + self.assert_no_fail(result) + self.assert_called_with('SoftLayer_User_Customer', 'editObject', identifier=8344458) + self.assertEqual('8344458 vpn is successfully disabled\n', result.output) + + def test_vpn_enable(self): + result = self.run_command(['user', 'vpn-enable', '8344458']) + self.assert_no_fail(result) + self.assert_called_with('SoftLayer_User_Customer', 'editObject', identifier=8344458) + + result = self.run_command(['user', 'vpn-enable', '8344458']) + permission_m = self.set_mock('SoftLayer_User_Customer', 'editObject') + permission_m.return_value = {'sslVpnAllowedFlag': True} + self.assert_no_fail(result) + self.assert_called_with('SoftLayer_User_Customer', 'editObject', identifier=8344458) + self.assertEqual('8344458 vpn is successfully enabled\n', result.output)
diff --git a/docs/cli/users.rst b/docs/cli/users.rst index e3d45bb1d..af86b4a94 100644 --- a/docs/cli/users.rst +++ b/docs/cli/users.rst @@ -64,6 +64,14 @@ Version 5.6.0 introduces the ability to interact with user accounts from the cli :prog: user vpn-password :show-nested: +.. click:: SoftLayer.CLI.user.vpn_enable_or_disable:vpn_enable + :prog: user vpn-enable + :show-nested: + +.. click:: SoftLayer.CLI.user.vpn_enable_or_disable:vpn_disable + :prog: user vpn-disable + :show-nested: + .. click:: SoftLayer.CLI.user.apikey:cli :prog: user apikey :show-nested:
[ { "components": [ { "doc": "Enable vpn for a user.\n\nExample::\n slcli user vpn-enable 1234567", "lines": [ 15, 29 ], "name": "vpn_enable", "signature": "def vpn_enable(env, user):", "type": "function" }, { "doc": "Disable vpn for a user.\n\nExample::\n slcli user vpn-disable 1234567", "lines": [ 35, 49 ], "name": "vpn_disable", "signature": "def vpn_disable(env, user):", "type": "function" } ], "file": "SoftLayer/CLI/user/vpn_enable_or_disable.py" }, { "components": [ { "doc": "Enable or Disable vpn for a user.\n\n:param int user_id: User to edit.\n:param bool value: Value for vpn enable flag.\nor\n:param bool value: Value for vpn disable flag.", "lines": [ 364, 373 ], "name": "UserManager.vpn_enable_or_disable", "signature": "def vpn_enable_or_disable(self, user_id, value):", "type": "function" } ], "file": "SoftLayer/managers/user.py" } ]
[ "tests/CLI/modules/user_tests.py::UserCLITests::test_vpn_disable", "tests/CLI/modules/user_tests.py::UserCLITests::test_vpn_enable" ]
[ "tests/CLI/modules/user_tests.py::UserCLITests::test_add_api_authentication_key", "tests/CLI/modules/user_tests.py::UserCLITests::test_api_key_with_all_option", "tests/CLI/modules/user_tests.py::UserCLITests::test_api_key_without_option", "tests/CLI/modules/user_tests.py::UserCLITests::test_create_user", "tests/CLI/modules/user_tests.py::UserCLITests::test_create_user_and_apikey", "tests/CLI/modules/user_tests.py::UserCLITests::test_create_user_from_user", "tests/CLI/modules/user_tests.py::UserCLITests::test_create_user_generate_password_36", "tests/CLI/modules/user_tests.py::UserCLITests::test_create_user_no_confirm", "tests/CLI/modules/user_tests.py::UserCLITests::test_create_user_with_bad_template", "tests/CLI/modules/user_tests.py::UserCLITests::test_create_user_with_no_confirm", "tests/CLI/modules/user_tests.py::UserCLITests::test_create_user_with_template", "tests/CLI/modules/user_tests.py::UserCLITests::test_delete", "tests/CLI/modules/user_tests.py::UserCLITests::test_delete_failure", "tests/CLI/modules/user_tests.py::UserCLITests::test_detail", "tests/CLI/modules/user_tests.py::UserCLITests::test_detail_events", "tests/CLI/modules/user_tests.py::UserCLITests::test_detail_hardware", "tests/CLI/modules/user_tests.py::UserCLITests::test_detail_keys", "tests/CLI/modules/user_tests.py::UserCLITests::test_detail_logins", "tests/CLI/modules/user_tests.py::UserCLITests::test_detail_permissions", "tests/CLI/modules/user_tests.py::UserCLITests::test_detail_virtual", "tests/CLI/modules/user_tests.py::UserCLITests::test_devices_access", "tests/CLI/modules/user_tests.py::UserCLITests::test_edit_details", "tests/CLI/modules/user_tests.py::UserCLITests::test_edit_details_bad_json", "tests/CLI/modules/user_tests.py::UserCLITests::test_edit_details_failure", "tests/CLI/modules/user_tests.py::UserCLITests::test_edit_notification_off_failure", "tests/CLI/modules/user_tests.py::UserCLITests::test_edit_notification_on", "tests/CLI/modules/user_tests.py::UserCLITests::test_edit_notification_on_bad", "tests/CLI/modules/user_tests.py::UserCLITests::test_edit_notifications_off", "tests/CLI/modules/user_tests.py::UserCLITests::test_edit_perms_from_user", "tests/CLI/modules/user_tests.py::UserCLITests::test_edit_perms_off", "tests/CLI/modules/user_tests.py::UserCLITests::test_edit_perms_off_failure", "tests/CLI/modules/user_tests.py::UserCLITests::test_edit_perms_on", "tests/CLI/modules/user_tests.py::UserCLITests::test_edit_perms_on_bad", "tests/CLI/modules/user_tests.py::UserCLITests::test_grant_access_dedicated", "tests/CLI/modules/user_tests.py::UserCLITests::test_grant_access_hardware", "tests/CLI/modules/user_tests.py::UserCLITests::test_grant_access_virtual", "tests/CLI/modules/user_tests.py::UserCLITests::test_grant_without_device", "tests/CLI/modules/user_tests.py::UserCLITests::test_notificacions_list", "tests/CLI/modules/user_tests.py::UserCLITests::test_permissions_list", "tests/CLI/modules/user_tests.py::UserCLITests::test_print_hardware_access", "tests/CLI/modules/user_tests.py::UserCLITests::test_refresh_api_authentication_key", "tests/CLI/modules/user_tests.py::UserCLITests::test_remove_access_dedicated", "tests/CLI/modules/user_tests.py::UserCLITests::test_remove_access_hardware", "tests/CLI/modules/user_tests.py::UserCLITests::test_remove_access_virtual", "tests/CLI/modules/user_tests.py::UserCLITests::test_remove_api_authentication_key", "tests/CLI/modules/user_tests.py::UserCLITests::test_remove_api_authentication_key_without_api_key", "tests/CLI/modules/user_tests.py::UserCLITests::test_remove_without_device", "tests/CLI/modules/user_tests.py::UserCLITests::test_remove_without_password", "tests/CLI/modules/user_tests.py::UserCLITests::test_update_vpn_password", "tests/CLI/modules/user_tests.py::UserCLITests::test_user_list", "tests/CLI/modules/user_tests.py::UserCLITests::test_user_list_only_id", "tests/CLI/modules/user_tests.py::UserCLITests::test_vpn_manual", "tests/CLI/modules/user_tests.py::UserCLITests::test_vpn_manual_fail", "tests/CLI/modules/user_tests.py::UserCLITests::test_vpn_subnet_add", "tests/CLI/modules/user_tests.py::UserCLITests::test_vpn_subnet_add_fail", "tests/CLI/modules/user_tests.py::UserCLITests::test_vpn_subnet_remove" ]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> Added new slcli user vpn-disable and slcli user vpn-enable command Hi @allmightyspiff, Fixes: #2069 **Title:** new slcli user vpn-enable command **Description:** I have added new features `slcli user vpn-disable` and `slcli user vpn-enable` commands. I have **tested** it. Please **review** it. Please find the screen shots. **Screen Shot: 1** <img width="745" alt="Screenshot 2023-08-09 at 8 21 07 PM" src="https://github.com/softlayer/softlayer-python/assets/125332006/48023c35-3ad1-4985-8236-2b326e66916b"> **Screen Shot: 2** <img width="678" alt="Screenshot 2023-08-09 at 8 22 33 PM" src="https://github.com/softlayer/softlayer-python/assets/125332006/a45bc21d-8cef-487c-87ba-b23be82628f6"> Thanks, Ramkishor Chaladi. ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in SoftLayer/CLI/user/vpn_enable_or_disable.py] (definition of vpn_enable:) def vpn_enable(env, user): """Enable vpn for a user. Example:: slcli user vpn-enable 1234567""" (definition of vpn_disable:) def vpn_disable(env, user): """Disable vpn for a user. Example:: slcli user vpn-disable 1234567""" [end of new definitions in SoftLayer/CLI/user/vpn_enable_or_disable.py] [start of new definitions in SoftLayer/managers/user.py] (definition of UserManager.vpn_enable_or_disable:) def vpn_enable_or_disable(self, user_id, value): """Enable or Disable vpn for a user. :param int user_id: User to edit. :param bool value: Value for vpn enable flag. or :param bool value: Value for vpn disable flag.""" [end of new definitions in SoftLayer/managers/user.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
bd1ecce1ec4313b9ceefd3cfea52d1b9274fef9d
roboflow__supervision-245
245
roboflow/supervision
null
36cdcf1b128e38cb9a086290fbfb0130fa64ac5b
2023-07-26T08:25:02Z
diff --git a/supervision/dataset/core.py b/supervision/dataset/core.py index ce7e0edb5..6e47d747f 100644 --- a/supervision/dataset/core.py +++ b/supervision/dataset/core.py @@ -31,7 +31,6 @@ train_test_split, ) from supervision.detection.core import Detections -from supervision.utils.file import list_files_with_extensions @dataclass @@ -197,7 +196,10 @@ def as_pascal_voc( @classmethod def from_pascal_voc( - cls, images_directory_path: str, annotations_directory_path: str + cls, + images_directory_path: str, + annotations_directory_path: str, + force_masks: bool = False, ) -> DetectionDataset: """ Creates a Dataset instance from PASCAL VOC formatted data. @@ -205,6 +207,7 @@ def from_pascal_voc( Args: images_directory_path (str): The path to the directory containing the images. annotations_directory_path (str): The path to the directory containing the PASCAL VOC XML annotations. + force_masks (bool, optional): If True, forces masks to be loaded for all annotations, regardless of whether they are present. Returns: DetectionDataset: A DetectionDataset instance containing the loaded images and annotations. @@ -222,7 +225,7 @@ def from_pascal_voc( >>> project = rf.workspace(WORKSPACE_ID).project(PROJECT_ID) >>> dataset = project.version(PROJECT_VERSION).download("voc") - >>> ds = sv.DetectionDataset.from_yolo( + >>> ds = sv.DetectionDataset.from_pascal_voc( ... images_directory_path=f"{dataset.location}/train/images", ... annotations_directory_path=f"{dataset.location}/train/labels" ... ) @@ -231,34 +234,13 @@ def from_pascal_voc( ['dog', 'person'] ``` """ - image_paths = list_files_with_extensions( - directory=images_directory_path, extensions=["jpg", "jpeg", "png"] - ) - annotation_paths = list_files_with_extensions( - directory=annotations_directory_path, extensions=["xml"] - ) - raw_annotations: List[Tuple[str, Detections, List[str]]] = [ - load_pascal_voc_annotations(annotation_path=str(annotation_path)) - for annotation_path in annotation_paths - ] - - classes = [] - for annotation in raw_annotations: - classes.extend(annotation[2]) - classes = list(set(classes)) - - for annotation in raw_annotations: - class_id = [classes.index(class_name) for class_name in annotation[2]] - annotation[1].class_id = np.array(class_id) - - images = { - image_path.name: cv2.imread(str(image_path)) for image_path in image_paths - } + classes, images, annotations = load_pascal_voc_annotations( + images_directory_path=images_directory_path, + annotations_directory_path=annotations_directory_path, + force_masks=force_masks, + ) - annotations = { - image_name: detections for image_name, detections, _ in raw_annotations - } return DetectionDataset(classes=classes, images=images, annotations=annotations) @classmethod diff --git a/supervision/dataset/formats/pascal_voc.py b/supervision/dataset/formats/pascal_voc.py index a3005eb90..4efb29173 100644 --- a/supervision/dataset/formats/pascal_voc.py +++ b/supervision/dataset/formats/pascal_voc.py @@ -1,12 +1,16 @@ -from typing import List, Optional, Tuple +import os +from pathlib import Path +from typing import Dict, List, Optional, Tuple from xml.dom.minidom import parseString from xml.etree.ElementTree import Element, SubElement, parse, tostring +import cv2 import numpy as np from supervision.dataset.utils import approximate_mask_with_polygons from supervision.detection.core import Detections -from supervision.detection.utils import polygon_to_xyxy +from supervision.detection.utils import polygon_to_mask, polygon_to_xyxy +from supervision.utils.file import list_files_with_extensions def object_to_pascal_voc( @@ -120,24 +124,91 @@ def detections_to_pascal_voc( def load_pascal_voc_annotations( - annotation_path: str, -) -> Tuple[str, Detections, List[str]]: + images_directory_path: str, + annotations_directory_path: str, + force_masks: bool = False, +) -> Tuple[List[str], Dict[str, np.ndarray], Dict[str, Detections]]: """ - Loads PASCAL VOC XML annotations and returns the image name, a Detections instance, and a list of class names. + Loads PASCAL VOC annotations and returns class names, images, and their corresponding detections. Args: - annotation_path (str): The path to the PASCAL VOC XML annotations file. + images_directory_path (str): The path to the directory containing the images. + annotations_directory_path (str): The path to the directory containing the PASCAL VOC annotation files. + force_masks (bool, optional): If True, forces masks to be loaded for all annotations, regardless of whether they are present. Returns: - Tuple[str, Detections, List[str]]: A tuple containing the image name, a Detections instance, and a list of class names of objects in the detections. + Tuple[List[str], Dict[str, np.ndarray], Dict[str, Detections]]: A tuple containing a list of class names, a dictionary with image names as keys and images as values, and a dictionary with image names as keys and corresponding Detections instances as values. """ - tree = parse(annotation_path) - root = tree.getroot() - image_name = root.find("filename").text + image_paths = list_files_with_extensions( + directory=images_directory_path, extensions=["jpg", "jpeg", "png"] + ) + classes = [] + images = {} + annotations = {} + + for image_path in image_paths: + image_name = Path(image_path).stem + image = cv2.imread(str(image_path)) + + annotation_path = os.path.join(annotations_directory_path, f"{image_name}.xml") + if not os.path.exists(annotation_path): + images[image_path.name] = image + annotations[image_path.name] = Detections.empty() + continue + + tree = parse(annotation_path) + root = tree.getroot() + + resolution_wh = (image.shape[1], image.shape[0]) + annotation, classes = detections_from_xml_obj( + root, classes, resolution_wh, force_masks + ) + + images[image_path.name] = image + annotations[image_path.name] = annotation + + return classes, images, annotations + + +def detections_from_xml_obj( + root: Element, classes: List[str], resolution_wh, force_masks: bool = False +) -> Tuple[Detections, List[str]]: + """ + Converts an XML object in Pascal VOC format to a Detections object. + Expected XML format: + <annotation> + ... + <object> + <name>dog</name> + <bndbox> + <xmin>48</xmin> + <ymin>240</ymin> + <xmax>195</xmax> + <ymax>371</ymax> + </bndbox> + <polygon> + <x1>48</x1> + <y1>240</y1> + <x2>195</x2> + <y2>240</y2> + <x3>195</x3> + <y3>371</y3> + <x4>48</x4> + <y4>371</y4> + </polygon> + </object> + </annotation> + + Returns: + Tuple[Detections, List[str]]: A tuple containing a Detections object and an updated list of class names, extended with the class names from the XML object. + """ xyxy = [] class_names = [] + masks = [] + with_masks = False + extended_classes = classes[:] for obj in root.findall("object"): class_name = obj.find("name").text class_names.append(class_name) @@ -150,7 +221,40 @@ def load_pascal_voc_annotations( xyxy.append([x1, y1, x2, y2]) - xyxy = np.array(xyxy) - detections = Detections(xyxy=xyxy) + with_masks = obj.find("polygon") is not None + with_masks = force_masks if force_masks else with_masks + + for polygon in obj.findall("polygon"): + polygon_points = parse_polygon_points(polygon) + + mask_from_polygon = polygon_to_mask( + polygon=np.array(polygon_points), + resolution_wh=resolution_wh, + ) + masks.append(mask_from_polygon) + + xyxy = np.array(xyxy) if len(xyxy) > 0 else np.empty((0, 4)) + for k in set(class_names): + if k not in extended_classes: + extended_classes.append(k) + class_id = np.array( + [extended_classes.index(class_name) for class_name in class_names] + ) + + if with_masks: + annotation = Detections( + xyxy=xyxy, mask=np.array(masks).astype(bool), class_id=class_id + ) + else: + annotation = Detections(xyxy=xyxy, class_id=class_id) + return annotation, extended_classes + - return image_name, detections, class_names +def parse_polygon_points(polygon: Element) -> List[List[int]]: + polygon_points = [] + coords = polygon.findall(".//*") + for i in range(0, len(coords), 2): + x = int(coords[i].text) + y = int(coords[i + 1].text) + polygon_points.append([x, y]) + return polygon_points diff --git a/supervision/detection/utils.py b/supervision/detection/utils.py index 63206ddcc..e30e6a053 100644 --- a/supervision/detection/utils.py +++ b/supervision/detection/utils.py @@ -17,7 +17,7 @@ def polygon_to_mask(polygon: np.ndarray, resolution_wh: Tuple[int, int]) -> np.n np.ndarray: The generated 2D mask, where the polygon is marked with `1`'s and the rest is filled with `0`'s. """ width, height = resolution_wh - mask = np.zeros((height, width), dtype=np.uint8) + mask = np.zeros((height, width)) cv2.fillPoly(mask, [polygon], color=1) return mask
diff --git a/test/dataset/formats/test_pascal_voc.py b/test/dataset/formats/test_pascal_voc.py new file mode 100644 index 000000000..fa3f11244 --- /dev/null +++ b/test/dataset/formats/test_pascal_voc.py @@ -0,0 +1,147 @@ +import xml.etree.ElementTree as ET +from contextlib import ExitStack as DoesNotRaise +from test.utils import mock_detections +from typing import List, Optional + +import numpy as np +import pytest + +from supervision.dataset.formats.pascal_voc import ( + detections_from_xml_obj, + object_to_pascal_voc, + parse_polygon_points, +) + + +def are_xml_elements_equal(elem1, elem2): + if ( + elem1.tag != elem2.tag + or elem1.attrib != elem2.attrib + or elem1.text != elem2.text + or len(elem1) != len(elem2) + ): + return False + + for child1, child2 in zip(elem1, elem2): + if not are_xml_elements_equal(child1, child2): + return False + + return True + + +@pytest.mark.parametrize( + "xyxy, name, polygon, expected_result, exception", + [ + ( + [0, 0, 10, 10], + "test", + None, + ET.fromstring( + """<object><name>test</name><bndbox><xmin>0</xmin><ymin>0</ymin><xmax>10</xmax><ymax>10</ymax></bndbox></object>""" + ), + DoesNotRaise(), + ), + ( + [0, 0, 10, 10], + "test", + [[0, 0], [10, 0], [10, 10], [0, 10]], + ET.fromstring( + """<object><name>test</name><bndbox><xmin>0</xmin><ymin>0</ymin><xmax>10</xmax><ymax>10</ymax></bndbox><polygon><x1>0</x1><y1>0</y1><x2>10</x2><y2>0</y2><x3>10</x3><y3>10</y3><x4>0</x4><y4>10</y4></polygon></object>""" + ), + DoesNotRaise(), + ), + ], +) +def test_object_to_pascal_voc( + xyxy: np.ndarray, + name: str, + polygon: Optional[np.ndarray], + expected_result, + exception: Exception, +): + with exception: + result = object_to_pascal_voc(xyxy=xyxy, name=name, polygon=polygon) + assert are_xml_elements_equal(result, expected_result) + + +@pytest.mark.parametrize( + "polygon_element, expected_result, exception", + [ + ( + ET.fromstring( + """<polygon><x1>0</x1><y1>0</y1><x2>10</x2><y2>0</y2><x3>10</x3><y3>10</y3><x4>0</x4><y4>10</y4></polygon>""" + ), + [[0, 0], [10, 0], [10, 10], [0, 10]], + DoesNotRaise(), + ) + ], +) +def test_parse_polygon_points( + polygon_element, + expected_result: List[list], + exception, +): + with exception: + result = parse_polygon_points(polygon_element) + assert result == expected_result + + +ONE_CLASS_N_BBOX = """<annotation><object><name>test</name><bndbox><xmin>0</xmin><ymin>0</ymin><xmax>10</xmax><ymax>10</ymax></bndbox></object><object><name>test</name><bndbox><xmin>10</xmin><ymin>10</ymin><xmax>20</xmax><ymax>20</ymax></bndbox></object></annotation>""" + + +ONE_CLASS_ONE_BBOX = """<annotation><object><name>test</name><bndbox><xmin>0</xmin><ymin>0</ymin><xmax>10</xmax><ymax>10</ymax></bndbox></object></annotation>""" + + +N_CLASS_N_BBOX = """<annotation><object><name>test</name><bndbox><xmin>0</xmin><ymin>0</ymin><xmax>10</xmax><ymax>10</ymax></bndbox></object><object><name>test</name><bndbox><xmin>20</xmin><ymin>30</ymin><xmax>30</xmax><ymax>40</ymax></bndbox></object><object><name>test2</name><bndbox><xmin>10</xmin><ymin>10</ymin><xmax>20</xmax><ymax>20</ymax></bndbox></object></annotation>""" + +NO_DETECTIONS = """<annotation></annotation>""" + + +@pytest.mark.parametrize( + "xml_string, classes, resolution_wh, force_masks, expected_result, exception", + [ + ( + ONE_CLASS_ONE_BBOX, + ["test"], + (100, 100), + False, + mock_detections(np.array([[0, 0, 10, 10]]), None, [0]), + DoesNotRaise(), + ), + ( + ONE_CLASS_N_BBOX, + ["test"], + (100, 100), + False, + mock_detections(np.array([[0, 0, 10, 10], [10, 10, 20, 20]]), None, [0, 0]), + DoesNotRaise(), + ), + ( + N_CLASS_N_BBOX, + ["test", "test2"], + (100, 100), + False, + mock_detections( + np.array([[0, 0, 10, 10], [20, 30, 30, 40], [10, 10, 20, 20]]), + None, + [0, 0, 1], + ), + DoesNotRaise(), + ), + ( + NO_DETECTIONS, + [], + (100, 100), + False, + mock_detections(np.empty((0, 4)), None, []), + DoesNotRaise(), + ), + ], +) +def test_detections_from_xml_obj( + xml_string, classes, resolution_wh, force_masks, expected_result, exception +): + with exception: + root = ET.fromstring(xml_string) + result, _ = detections_from_xml_obj(root, classes, resolution_wh, force_masks) + assert result == expected_result
[ { "components": [ { "doc": "Converts an XML object in Pascal VOC format to a Detections object.\nExpected XML format:\n<annotation>\n ...\n <object>\n <name>dog</name>\n <bndbox>\n <xmin>48</xmin>\n <ymin>240</ymin>\n <xmax>195</xmax>\n <ymax>371</ymax>\n </bndbox>\n <polygon>\n <x1>48</x1>\n <y1>240</y1>\n <x2>195</x2>\n <y2>240</y2>\n <x3>195</x3>\n <y3>371</y3>\n <x4>48</x4>\n <y4>371</y4>\n </polygon>\n </object>\n</annotation>\n\nReturns:\n Tuple[Detections, List[str]]: A tuple containing a Detections object and an updated list of class names, extended with the class names from the XML object.", "lines": [ 175, 250 ], "name": "detections_from_xml_obj", "signature": "def detections_from_xml_obj( root: Element, classes: List[str], resolution_wh, force_masks: bool = False ) -> Tuple[Detections, List[str]]:", "type": "function" }, { "doc": "", "lines": [ 253, 260 ], "name": "parse_polygon_points", "signature": "def parse_polygon_points(polygon: Element) -> List[List[int]]:", "type": "function" } ], "file": "supervision/dataset/formats/pascal_voc.py" } ]
[ "test/dataset/formats/test_pascal_voc.py::test_object_to_pascal_voc[xyxy0-test-None-expected_result0-exception0]", "test/dataset/formats/test_pascal_voc.py::test_object_to_pascal_voc[xyxy1-test-polygon1-expected_result1-exception1]", "test/dataset/formats/test_pascal_voc.py::test_parse_polygon_points[polygon_element0-expected_result0-exception0]", "test/dataset/formats/test_pascal_voc.py::test_detections_from_xml_obj[<annotation><object><name>test</name><bndbox><xmin>0</xmin><ymin>0</ymin><xmax>10</xmax><ymax>10</ymax></bndbox></object></annotation>-classes0-resolution_wh0-False-expected_result0-exception0]", "test/dataset/formats/test_pascal_voc.py::test_detections_from_xml_obj[<annotation><object><name>test</name><bndbox><xmin>0</xmin><ymin>0</ymin><xmax>10</xmax><ymax>10</ymax></bndbox></object><object><name>test</name><bndbox><xmin>10</xmin><ymin>10</ymin><xmax>20</xmax><ymax>20</ymax></bndbox></object></annotation>-classes1-resolution_wh1-False-expected_result1-exception1]", "test/dataset/formats/test_pascal_voc.py::test_detections_from_xml_obj[<annotation><object><name>test</name><bndbox><xmin>0</xmin><ymin>0</ymin><xmax>10</xmax><ymax>10</ymax></bndbox></object><object><name>test</name><bndbox><xmin>20</xmin><ymin>30</ymin><xmax>30</xmax><ymax>40</ymax></bndbox></object><object><name>test2</name><bndbox><xmin>10</xmin><ymin>10</ymin><xmax>20</xmax><ymax>20</ymax></bndbox></object></annotation>-classes2-resolution_wh2-False-expected_result2-exception2]", "test/dataset/formats/test_pascal_voc.py::test_detections_from_xml_obj[<annotation></annotation>-classes3-resolution_wh3-False-expected_result3-exception3]" ]
[]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> Add support for loading segmentation datasets in Pascal VOC format # Description Add possibility to load PASCAL VOC segmentation masks in addition to object detection ([related issue](https://github.com/roboflow/supervision/issues/244)). Changes were made to core.DetectionDataset.from_pascal_voc and format.pascal_voc.load_pascal_voc_annotations. ## Type of change Please delete options that are not relevant. - [+] New feature (non-breaking change which adds functionality) ## How has this change been tested, please provide a testcase or example of how you tested the change? Via new tests. ## Any specific deployment considerations For example, documentation changes, usability, usage/costs, secrets, etc. ## Docs - [ ] Docs updated? What were the changes: ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in supervision/dataset/formats/pascal_voc.py] (definition of detections_from_xml_obj:) def detections_from_xml_obj( root: Element, classes: List[str], resolution_wh, force_masks: bool = False ) -> Tuple[Detections, List[str]]: """Converts an XML object in Pascal VOC format to a Detections object. Expected XML format: <annotation> ... <object> <name>dog</name> <bndbox> <xmin>48</xmin> <ymin>240</ymin> <xmax>195</xmax> <ymax>371</ymax> </bndbox> <polygon> <x1>48</x1> <y1>240</y1> <x2>195</x2> <y2>240</y2> <x3>195</x3> <y3>371</y3> <x4>48</x4> <y4>371</y4> </polygon> </object> </annotation> Returns: Tuple[Detections, List[str]]: A tuple containing a Detections object and an updated list of class names, extended with the class names from the XML object.""" (definition of parse_polygon_points:) def parse_polygon_points(polygon: Element) -> List[List[int]]: [end of new definitions in supervision/dataset/formats/pascal_voc.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
3eb5c0b024e3e46877b7fe4fd66e6177d1308ba0
scrapy__scrapy-5979
5,979
scrapy/scrapy
null
8055a948dc2544c4d8ebe7aa1c6227e19b1583ac
2023-07-18T10:33:03Z
diff --git a/docs/topics/extensions.rst b/docs/topics/extensions.rst index 96e0216b8f0..8d4749ab33d 100644 --- a/docs/topics/extensions.rst +++ b/docs/topics/extensions.rst @@ -258,6 +258,7 @@ The conditions for closing a spider can be configured through the following settings: * :setting:`CLOSESPIDER_TIMEOUT` +* :setting:`CLOSESPIDER_TIMEOUT_NO_ITEM` * :setting:`CLOSESPIDER_ITEMCOUNT` * :setting:`CLOSESPIDER_PAGECOUNT` * :setting:`CLOSESPIDER_ERRORCOUNT` @@ -280,6 +281,18 @@ more than that number of second, it will be automatically closed with the reason ``closespider_timeout``. If zero (or non set), spiders won't be closed by timeout. +.. setting:: CLOSESPIDER_TIMEOUT_NO_ITEM + +CLOSESPIDER_TIMEOUT_NO_ITEM +""""""""""""""""""""""""""" + +Default: ``0`` + +An integer which specifies a number of seconds. If the spider has not produced +any items in the last number of seconds, it will be closed with the reason +``closespider_timeout_no_item``. If zero (or non set), spiders won't be closed +regardless if it hasn't produced any items. + .. setting:: CLOSESPIDER_ITEMCOUNT CLOSESPIDER_ITEMCOUNT diff --git a/scrapy/extensions/closespider.py b/scrapy/extensions/closespider.py index bb6f832f296..4307b417028 100644 --- a/scrapy/extensions/closespider.py +++ b/scrapy/extensions/closespider.py @@ -4,11 +4,14 @@ See documentation in docs/topics/extensions.rst """ +import logging from collections import defaultdict from scrapy import signals from scrapy.exceptions import NotConfigured +logger = logging.getLogger(__name__) + class CloseSpider: def __init__(self, crawler): @@ -19,6 +22,7 @@ def __init__(self, crawler): "itemcount": crawler.settings.getint("CLOSESPIDER_ITEMCOUNT"), "pagecount": crawler.settings.getint("CLOSESPIDER_PAGECOUNT"), "errorcount": crawler.settings.getint("CLOSESPIDER_ERRORCOUNT"), + "timeout_no_item": crawler.settings.getint("CLOSESPIDER_TIMEOUT_NO_ITEM"), } if not any(self.close_on.values()): @@ -34,6 +38,15 @@ def __init__(self, crawler): crawler.signals.connect(self.spider_opened, signal=signals.spider_opened) if self.close_on.get("itemcount"): crawler.signals.connect(self.item_scraped, signal=signals.item_scraped) + if self.close_on.get("timeout_no_item"): + self.timeout_no_item = self.close_on["timeout_no_item"] + self.items_in_period = 0 + crawler.signals.connect( + self.spider_opened_no_item, signal=signals.spider_opened + ) + crawler.signals.connect( + self.item_scraped_no_item, signal=signals.item_scraped + ) crawler.signals.connect(self.spider_closed, signal=signals.spider_closed) @classmethod @@ -69,3 +82,31 @@ def spider_closed(self, spider): task = getattr(self, "task", False) if task and task.active(): task.cancel() + + task_no_item = getattr(self, "task_no_item", False) + if task_no_item and task_no_item.running: + task_no_item.stop() + + def spider_opened_no_item(self, spider): + from twisted.internet import task + + self.task_no_item = task.LoopingCall(self._count_items_produced, spider) + self.task_no_item.start(self.timeout_no_item, now=False) + + logger.info( + f"Spider will stop when no items are produced after " + f"{self.timeout_no_item} seconds." + ) + + def item_scraped_no_item(self, item, spider): + self.items_in_period += 1 + + def _count_items_produced(self, spider): + if self.items_in_period >= 1: + self.items_in_period = 0 + else: + logger.info( + f"Closing spider since no items were produced in the last " + f"{self.timeout_no_item} seconds." + ) + self.crawler.engine.close_spider(spider, "closespider_timeout_no_item")
diff --git a/tests/spiders.py b/tests/spiders.py index 6ff48f4710c..f29dea2a12b 100644 --- a/tests/spiders.py +++ b/tests/spiders.py @@ -77,6 +77,22 @@ def errback(self, failure): self.t2_err = time.time() +class SlowSpider(DelaySpider): + name = "slow" + + def start_requests(self): + # 1st response is fast + url = self.mockserver.url("/delay?n=0&b=0") + yield Request(url, callback=self.parse, errback=self.errback) + + # 2nd response is slow + url = self.mockserver.url(f"/delay?n={self.n}&b={self.b}") + yield Request(url, callback=self.parse, errback=self.errback) + + def parse(self, response): + yield Item() + + class SimpleSpider(MetaSpider): name = "simple" diff --git a/tests/test_closespider.py b/tests/test_closespider.py index 9b39187d583..38ede70e449 100644 --- a/tests/test_closespider.py +++ b/tests/test_closespider.py @@ -3,7 +3,7 @@ from scrapy.utils.test import get_crawler from tests.mockserver import MockServer -from tests.spiders import ErrorSpider, FollowAllSpider, ItemSpider +from tests.spiders import ErrorSpider, FollowAllSpider, ItemSpider, SlowSpider class TestCloseSpider(TestCase): @@ -54,3 +54,13 @@ def test_closespider_timeout(self): self.assertEqual(reason, "closespider_timeout") total_seconds = crawler.stats.get_value("elapsed_time_seconds") self.assertTrue(total_seconds >= close_on) + + @defer.inlineCallbacks + def test_closespider_timeout_no_item(self): + timeout = 1 + crawler = get_crawler(SlowSpider, {"CLOSESPIDER_TIMEOUT_NO_ITEM": timeout}) + yield crawler.crawl(n=3, mockserver=self.mockserver) + reason = crawler.spider.meta["close_reason"] + self.assertEqual(reason, "closespider_timeout_no_item") + total_seconds = crawler.stats.get_value("elapsed_time_seconds") + self.assertTrue(total_seconds >= timeout)
diff --git a/docs/topics/extensions.rst b/docs/topics/extensions.rst index 96e0216b8f0..8d4749ab33d 100644 --- a/docs/topics/extensions.rst +++ b/docs/topics/extensions.rst @@ -258,6 +258,7 @@ The conditions for closing a spider can be configured through the following settings: * :setting:`CLOSESPIDER_TIMEOUT` +* :setting:`CLOSESPIDER_TIMEOUT_NO_ITEM` * :setting:`CLOSESPIDER_ITEMCOUNT` * :setting:`CLOSESPIDER_PAGECOUNT` * :setting:`CLOSESPIDER_ERRORCOUNT` @@ -280,6 +281,18 @@ more than that number of second, it will be automatically closed with the reason ``closespider_timeout``. If zero (or non set), spiders won't be closed by timeout. +.. setting:: CLOSESPIDER_TIMEOUT_NO_ITEM + +CLOSESPIDER_TIMEOUT_NO_ITEM +""""""""""""""""""""""""""" + +Default: ``0`` + +An integer which specifies a number of seconds. If the spider has not produced +any items in the last number of seconds, it will be closed with the reason +``closespider_timeout_no_item``. If zero (or non set), spiders won't be closed +regardless if it hasn't produced any items. + .. setting:: CLOSESPIDER_ITEMCOUNT CLOSESPIDER_ITEMCOUNT
[ { "components": [ { "doc": "", "lines": [ 90, 98 ], "name": "CloseSpider.spider_opened_no_item", "signature": "def spider_opened_no_item(self, spider):", "type": "function" }, { "doc": "", "lines": [ 101, 102 ], "name": "CloseSpider.item_scraped_no_item", "signature": "def item_scraped_no_item(self, item, spider):", "type": "function" }, { "doc": "", "lines": [ 104, 112 ], "name": "CloseSpider._count_items_produced", "signature": "def _count_items_produced(self, spider):", "type": "function" } ], "file": "scrapy/extensions/closespider.py" } ]
[ "tests/test_closespider.py::TestCloseSpider::test_closespider_timeout_no_item" ]
[ "tests/test_closespider.py::TestCloseSpider::test_closespider_errorcount", "tests/test_closespider.py::TestCloseSpider::test_closespider_itemcount", "tests/test_closespider.py::TestCloseSpider::test_closespider_pagecount", "tests/test_closespider.py::TestCloseSpider::test_closespider_timeout" ]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> introduce CLOSESPIDER_TIMEOUT_NO_ITEM in CloseSpider **Motivation:** Sometimes spiders still keep running without producing any items. This could be due to a variety of reasons like poor dupe URL filtration, bad crawling strategy, etc. **Proposal:** Auto-close the spider if it hasn't produced any items in the past number of seconds. ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in scrapy/extensions/closespider.py] (definition of CloseSpider.spider_opened_no_item:) def spider_opened_no_item(self, spider): (definition of CloseSpider.item_scraped_no_item:) def item_scraped_no_item(self, item, spider): (definition of CloseSpider._count_items_produced:) def _count_items_produced(self, spider): [end of new definitions in scrapy/extensions/closespider.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
57a5460529ff71c42e4d0381265b1b512b1eb09b
matplotlib__matplotlib-26293
26,293
matplotlib/matplotlib
3.7
a4dca24d04f928a9e614db403c716237446140b2
2023-07-12T06:31:49Z
diff --git a/doc/api/axes_api.rst b/doc/api/axes_api.rst index 3457368fa51c..8b01a120da5b 100644 --- a/doc/api/axes_api.rst +++ b/doc/api/axes_api.rst @@ -335,6 +335,8 @@ Autoscaling and margins Axes.use_sticky_edges Axes.margins + Axes.get_xmargin + Axes.get_ymargin Axes.set_xmargin Axes.set_ymargin diff --git a/doc/api/toolkits/mplot3d/axes3d.rst b/doc/api/toolkits/mplot3d/axes3d.rst index f6d8e2529896..b581494e4883 100644 --- a/doc/api/toolkits/mplot3d/axes3d.rst +++ b/doc/api/toolkits/mplot3d/axes3d.rst @@ -137,6 +137,7 @@ Autoscaling and margins :template: autosummary.rst :nosignatures: + get_zmargin set_zmargin margins autoscale diff --git a/doc/users/next_whats_new/margin_getters.rst b/doc/users/next_whats_new/margin_getters.rst new file mode 100644 index 000000000000..c43709a17d52 --- /dev/null +++ b/doc/users/next_whats_new/margin_getters.rst @@ -0,0 +1,4 @@ +Getters for xmargin, ymargin and zmargin +---------------------------------------- +``.Axes.get_xmargin()``, ``.Axes.get_ymargin()`` and ``.Axes3D.get_zmargin()`` methods have been added to return +the margin values set by ``.Axes.set_xmargin()``, ``.Axes.set_ymargin()`` and ``.Axes3D.set_zmargin()``, respectively. diff --git a/lib/matplotlib/axes/_base.py b/lib/matplotlib/axes/_base.py index 3796d9bbe508..ad06e6d552bc 100644 --- a/lib/matplotlib/axes/_base.py +++ b/lib/matplotlib/axes/_base.py @@ -2617,6 +2617,38 @@ def use_sticky_edges(self, b): self._use_sticky_edges = bool(b) # No effect until next autoscaling, which will mark the Axes as stale. + def get_xmargin(self): + """ + Retrieve autoscaling margin of the x-axis. + + .. versionadded:: 3.9 + + Returns + ------- + xmargin : float + + See Also + -------- + matplotlib.axes.Axes.set_xmargin + """ + return self._xmargin + + def get_ymargin(self): + """ + Retrieve autoscaling margin of the y-axis. + + .. versionadded:: 3.9 + + Returns + ------- + ymargin : float + + See Also + -------- + matplotlib.axes.Axes.set_ymargin + """ + return self._ymargin + def set_xmargin(self, m): """ Set padding of X data limits prior to autoscaling. diff --git a/lib/matplotlib/axes/_base.pyi b/lib/matplotlib/axes/_base.pyi index d41ecae1803c..e3644585296d 100644 --- a/lib/matplotlib/axes/_base.pyi +++ b/lib/matplotlib/axes/_base.pyi @@ -242,6 +242,8 @@ class _AxesBase(martist.Artist): def use_sticky_edges(self) -> bool: ... @use_sticky_edges.setter def use_sticky_edges(self, b: bool) -> None: ... + def get_xmargin(self) -> float: ... + def get_ymargin(self) -> float: ... def set_xmargin(self, m: float) -> None: ... def set_ymargin(self, m: float) -> None: ... diff --git a/lib/mpl_toolkits/mplot3d/axes3d.py b/lib/mpl_toolkits/mplot3d/axes3d.py index aeb6a66d2c98..e7abdc0767b5 100644 --- a/lib/mpl_toolkits/mplot3d/axes3d.py +++ b/lib/mpl_toolkits/mplot3d/axes3d.py @@ -513,6 +513,22 @@ def update_datalim(self, xys, **kwargs): get_autoscalez_on = _axis_method_wrapper("zaxis", "_get_autoscale_on") set_autoscalez_on = _axis_method_wrapper("zaxis", "_set_autoscale_on") + def get_zmargin(self): + """ + Retrieve autoscaling margin of the z-axis. + + .. versionadded:: 3.9 + + Returns + ------- + zmargin : float + + See Also + -------- + mpl_toolkits.mplot3d.axes3d.Axes3D.set_zmargin + """ + return self._zmargin + def set_zmargin(self, m): """ Set padding of Z data limits prior to autoscaling.
diff --git a/lib/matplotlib/tests/test_axes.py b/lib/matplotlib/tests/test_axes.py index 0fcb2eb26cbb..6dea39a702fc 100644 --- a/lib/matplotlib/tests/test_axes.py +++ b/lib/matplotlib/tests/test_axes.py @@ -6153,6 +6153,14 @@ def test_margins(): ymax + (ymax - ymin) * 0.5) +def test_margin_getters(): + fig = plt.figure() + ax = fig.add_subplot() + ax.margins(0.2, 0.3) + assert ax.get_xmargin() == 0.2 + assert ax.get_ymargin() == 0.3 + + def test_set_margin_updates_limits(): mpl.style.use("default") fig, ax = plt.subplots() diff --git a/lib/mpl_toolkits/mplot3d/tests/test_axes3d.py b/lib/mpl_toolkits/mplot3d/tests/test_axes3d.py index 1f8764cbab9d..df9f2ae52fd7 100644 --- a/lib/mpl_toolkits/mplot3d/tests/test_axes3d.py +++ b/lib/mpl_toolkits/mplot3d/tests/test_axes3d.py @@ -1994,6 +1994,15 @@ def test_margins(): assert ax.margins() == (0, 0.1, 0) +def test_margin_getters(): + fig = plt.figure() + ax = fig.add_subplot(projection='3d') + ax.margins(0.1, 0.2, 0.3) + assert ax.get_xmargin() == 0.1 + assert ax.get_ymargin() == 0.2 + assert ax.get_zmargin() == 0.3 + + @pytest.mark.parametrize('err, args, kwargs, match', ( (ValueError, (-1,), {}, r'margin must be greater than -0\.5'), (ValueError, (1, -1, 1), {}, r'margin must be greater than -0\.5'),
diff --git a/doc/api/axes_api.rst b/doc/api/axes_api.rst index 3457368fa51c..8b01a120da5b 100644 --- a/doc/api/axes_api.rst +++ b/doc/api/axes_api.rst @@ -335,6 +335,8 @@ Autoscaling and margins Axes.use_sticky_edges Axes.margins + Axes.get_xmargin + Axes.get_ymargin Axes.set_xmargin Axes.set_ymargin diff --git a/doc/api/toolkits/mplot3d/axes3d.rst b/doc/api/toolkits/mplot3d/axes3d.rst index f6d8e2529896..b581494e4883 100644 --- a/doc/api/toolkits/mplot3d/axes3d.rst +++ b/doc/api/toolkits/mplot3d/axes3d.rst @@ -137,6 +137,7 @@ Autoscaling and margins :template: autosummary.rst :nosignatures: + get_zmargin set_zmargin margins autoscale diff --git a/doc/users/next_whats_new/margin_getters.rst b/doc/users/next_whats_new/margin_getters.rst new file mode 100644 index 000000000000..c43709a17d52 --- /dev/null +++ b/doc/users/next_whats_new/margin_getters.rst @@ -0,0 +1,4 @@ +Getters for xmargin, ymargin and zmargin +---------------------------------------- +``.Axes.get_xmargin()``, ``.Axes.get_ymargin()`` and ``.Axes3D.get_zmargin()`` methods have been added to return +the margin values set by ``.Axes.set_xmargin()``, ``.Axes.set_ymargin()`` and ``.Axes3D.set_zmargin()``, respectively. diff --git a/lib/matplotlib/axes/_base.pyi b/lib/matplotlib/axes/_base.pyi index d41ecae1803c..e3644585296d 100644 --- a/lib/matplotlib/axes/_base.pyi +++ b/lib/matplotlib/axes/_base.pyi @@ -242,6 +242,8 @@ class _AxesBase(martist.Artist): def use_sticky_edges(self) -> bool: ... @use_sticky_edges.setter def use_sticky_edges(self, b: bool) -> None: ... + def get_xmargin(self) -> float: ... + def get_ymargin(self) -> float: ... def set_xmargin(self, m: float) -> None: ... def set_ymargin(self, m: float) -> None: ...
[ { "components": [ { "doc": "Retrieve autoscaling margin of the x-axis.\n\n.. versionadded:: 3.9\n\nReturns\n-------\nxmargin : float\n\nSee Also\n--------\nmatplotlib.axes.Axes.set_xmargin", "lines": [ 2620, 2634 ], "name": "_AxesBase.get_xmargin", "signature": "def get_xmargin(self):", "type": "function" }, { "doc": "Retrieve autoscaling margin of the y-axis.\n\n.. versionadded:: 3.9\n\nReturns\n-------\nymargin : float\n\nSee Also\n--------\nmatplotlib.axes.Axes.set_ymargin", "lines": [ 2636, 2650 ], "name": "_AxesBase.get_ymargin", "signature": "def get_ymargin(self):", "type": "function" } ], "file": "lib/matplotlib/axes/_base.py" }, { "components": [ { "doc": "Retrieve autoscaling margin of the z-axis.\n\n.. versionadded:: 3.9\n\nReturns\n-------\nzmargin : float\n\nSee Also\n--------\nmpl_toolkits.mplot3d.axes3d.Axes3D.set_zmargin", "lines": [ 516, 530 ], "name": "Axes3D.get_zmargin", "signature": "def get_zmargin(self):", "type": "function" } ], "file": "lib/mpl_toolkits/mplot3d/axes3d.py" } ]
[ "lib/matplotlib/tests/test_axes.py::test_margin_getters", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_margin_getters" ]
[ "lib/matplotlib/tests/test_axes.py::test_invisible_axes[png]", "lib/matplotlib/tests/test_axes.py::test_get_labels", "lib/matplotlib/tests/test_axes.py::test_repr", "lib/matplotlib/tests/test_axes.py::test_label_loc_vertical[png]", "lib/matplotlib/tests/test_axes.py::test_label_loc_horizontal[png]", "lib/matplotlib/tests/test_axes.py::test_label_loc_rc[png]", "lib/matplotlib/tests/test_axes.py::test_label_shift", "lib/matplotlib/tests/test_axes.py::test_acorr[png]", "lib/matplotlib/tests/test_axes.py::test_acorr_integers[png]", "lib/matplotlib/tests/test_axes.py::test_spy[png]", "lib/matplotlib/tests/test_axes.py::test_spy_invalid_kwargs", "lib/matplotlib/tests/test_axes.py::test_matshow[png]", "lib/matplotlib/tests/test_axes.py::test_formatter_ticker[png]", "lib/matplotlib/tests/test_axes.py::test_funcformatter_auto_formatter", "lib/matplotlib/tests/test_axes.py::test_strmethodformatter_auto_formatter", "lib/matplotlib/tests/test_axes.py::test_twin_axis_locators_formatters[png]", "lib/matplotlib/tests/test_axes.py::test_twinx_cla", "lib/matplotlib/tests/test_axes.py::test_twin_units[x]", "lib/matplotlib/tests/test_axes.py::test_twin_units[y]", "lib/matplotlib/tests/test_axes.py::test_twin_logscale[png-x]", "lib/matplotlib/tests/test_axes.py::test_twin_logscale[png-y]", "lib/matplotlib/tests/test_axes.py::test_twinx_axis_scales[png]", "lib/matplotlib/tests/test_axes.py::test_twin_inherit_autoscale_setting", "lib/matplotlib/tests/test_axes.py::test_inverted_cla", "lib/matplotlib/tests/test_axes.py::test_subclass_clear_cla", "lib/matplotlib/tests/test_axes.py::test_cla_not_redefined_internally", "lib/matplotlib/tests/test_axes.py::test_minorticks_on_rcParams_both[png]", "lib/matplotlib/tests/test_axes.py::test_autoscale_tiny_range[png]", "lib/matplotlib/tests/test_axes.py::test_autoscale_tight", "lib/matplotlib/tests/test_axes.py::test_autoscale_log_shared", "lib/matplotlib/tests/test_axes.py::test_use_sticky_edges", "lib/matplotlib/tests/test_axes.py::test_sticky_shared_axes[png]", "lib/matplotlib/tests/test_axes.py::test_nargs_stem", "lib/matplotlib/tests/test_axes.py::test_nargs_legend", "lib/matplotlib/tests/test_axes.py::test_nargs_pcolorfast", "lib/matplotlib/tests/test_axes.py::test_basic_annotate[png]", "lib/matplotlib/tests/test_axes.py::test_arrow_simple[png]", "lib/matplotlib/tests/test_axes.py::test_arrow_empty", "lib/matplotlib/tests/test_axes.py::test_arrow_in_view", "lib/matplotlib/tests/test_axes.py::test_annotate_default_arrow", "lib/matplotlib/tests/test_axes.py::test_annotate_signature", "lib/matplotlib/tests/test_axes.py::test_fill_units[png]", "lib/matplotlib/tests/test_axes.py::test_plot_format_kwarg_redundant", "lib/matplotlib/tests/test_axes.py::test_errorbar_dashes[png]", "lib/matplotlib/tests/test_axes.py::test_single_point[png]", "lib/matplotlib/tests/test_axes.py::test_single_date[png]", "lib/matplotlib/tests/test_axes.py::test_shaped_data[png]", "lib/matplotlib/tests/test_axes.py::test_structured_data", "lib/matplotlib/tests/test_axes.py::test_aitoff_proj[png]", "lib/matplotlib/tests/test_axes.py::test_axvspan_epoch[png]", "lib/matplotlib/tests/test_axes.py::test_axhspan_epoch[png]", "lib/matplotlib/tests/test_axes.py::test_hexbin_extent[png]", "lib/matplotlib/tests/test_axes.py::test_hexbin_empty[png]", "lib/matplotlib/tests/test_axes.py::test_hexbin_pickable", "lib/matplotlib/tests/test_axes.py::test_hexbin_log[png]", "lib/matplotlib/tests/test_axes.py::test_hexbin_linear[png]", "lib/matplotlib/tests/test_axes.py::test_hexbin_log_clim", "lib/matplotlib/tests/test_axes.py::test_hexbin_mincnt_behavior_upon_C_parameter[png]", "lib/matplotlib/tests/test_axes.py::test_inverted_limits", "lib/matplotlib/tests/test_axes.py::test_nonfinite_limits[png]", "lib/matplotlib/tests/test_axes.py::test_limits_empty_data[png-scatter]", "lib/matplotlib/tests/test_axes.py::test_limits_empty_data[png-plot]", "lib/matplotlib/tests/test_axes.py::test_limits_empty_data[png-fill_between]", "lib/matplotlib/tests/test_axes.py::test_imshow[png]", "lib/matplotlib/tests/test_axes.py::test_imshow_clip[png]", "lib/matplotlib/tests/test_axes.py::test_imshow_norm_vminvmax", "lib/matplotlib/tests/test_axes.py::test_polycollection_joinstyle[png]", "lib/matplotlib/tests/test_axes.py::test_fill_between_input[2d_x_input]", "lib/matplotlib/tests/test_axes.py::test_fill_between_input[2d_y1_input]", "lib/matplotlib/tests/test_axes.py::test_fill_between_input[2d_y2_input]", "lib/matplotlib/tests/test_axes.py::test_fill_betweenx_input[2d_y_input]", "lib/matplotlib/tests/test_axes.py::test_fill_betweenx_input[2d_x1_input]", "lib/matplotlib/tests/test_axes.py::test_fill_betweenx_input[2d_x2_input]", "lib/matplotlib/tests/test_axes.py::test_fill_between_interpolate[png]", "lib/matplotlib/tests/test_axes.py::test_fill_between_interpolate_decreasing[png]", "lib/matplotlib/tests/test_axes.py::test_fill_between_interpolate_nan[png]", "lib/matplotlib/tests/test_axes.py::test_pcolorargs_5205", "lib/matplotlib/tests/test_axes.py::test_pcolormesh[png]", "lib/matplotlib/tests/test_axes.py::test_pcolormesh_alpha[png]", "lib/matplotlib/tests/test_axes.py::test_pcolormesh_rgba[png-3-1]", "lib/matplotlib/tests/test_axes.py::test_pcolormesh_rgba[png-4-0.5]", "lib/matplotlib/tests/test_axes.py::test_pcolormesh_datetime_axis[png]", "lib/matplotlib/tests/test_axes.py::test_pcolor_datetime_axis[png]", "lib/matplotlib/tests/test_axes.py::test_pcolorargs", "lib/matplotlib/tests/test_axes.py::test_pcolorargs_with_read_only", "lib/matplotlib/tests/test_axes.py::test_pcolornearest[png]", "lib/matplotlib/tests/test_axes.py::test_pcolornearestunits[png]", "lib/matplotlib/tests/test_axes.py::test_pcolorflaterror", "lib/matplotlib/tests/test_axes.py::test_samesizepcolorflaterror", "lib/matplotlib/tests/test_axes.py::test_pcolorauto[png-False]", "lib/matplotlib/tests/test_axes.py::test_pcolorauto[png-True]", "lib/matplotlib/tests/test_axes.py::test_canonical[png]", "lib/matplotlib/tests/test_axes.py::test_arc_angles[png]", "lib/matplotlib/tests/test_axes.py::test_arc_ellipse[png]", "lib/matplotlib/tests/test_axes.py::test_marker_as_markerstyle", "lib/matplotlib/tests/test_axes.py::test_markevery[png]", "lib/matplotlib/tests/test_axes.py::test_markevery_line[png]", "lib/matplotlib/tests/test_axes.py::test_markevery_linear_scales[png]", "lib/matplotlib/tests/test_axes.py::test_markevery_linear_scales_zoomed[png]", "lib/matplotlib/tests/test_axes.py::test_markevery_log_scales[png]", "lib/matplotlib/tests/test_axes.py::test_markevery_polar[png]", "lib/matplotlib/tests/test_axes.py::test_markevery_linear_scales_nans[png]", "lib/matplotlib/tests/test_axes.py::test_marker_edges[png]", "lib/matplotlib/tests/test_axes.py::test_bar_tick_label_single[png]", "lib/matplotlib/tests/test_axes.py::test_nan_bar_values", "lib/matplotlib/tests/test_axes.py::test_bar_ticklabel_fail", "lib/matplotlib/tests/test_axes.py::test_bar_tick_label_multiple[png]", "lib/matplotlib/tests/test_axes.py::test_bar_tick_label_multiple_old_alignment[png]", "lib/matplotlib/tests/test_axes.py::test_bar_decimal_center[png]", "lib/matplotlib/tests/test_axes.py::test_barh_decimal_center[png]", "lib/matplotlib/tests/test_axes.py::test_bar_decimal_width[png]", "lib/matplotlib/tests/test_axes.py::test_barh_decimal_height[png]", "lib/matplotlib/tests/test_axes.py::test_bar_color_none_alpha", "lib/matplotlib/tests/test_axes.py::test_bar_edgecolor_none_alpha", "lib/matplotlib/tests/test_axes.py::test_barh_tick_label[png]", "lib/matplotlib/tests/test_axes.py::test_bar_timedelta", "lib/matplotlib/tests/test_axes.py::test_bar_datetime_start", "lib/matplotlib/tests/test_axes.py::test_boxplot_dates_pandas", "lib/matplotlib/tests/test_axes.py::test_boxplot_capwidths", "lib/matplotlib/tests/test_axes.py::test_pcolor_regression", "lib/matplotlib/tests/test_axes.py::test_bar_pandas", "lib/matplotlib/tests/test_axes.py::test_bar_pandas_indexed", "lib/matplotlib/tests/test_axes.py::test_bar_hatches[png]", "lib/matplotlib/tests/test_axes.py::test_bar_labels[x-1-x-expected_labels0-x]", "lib/matplotlib/tests/test_axes.py::test_bar_labels[x1-width1-label1-expected_labels1-_nolegend_]", "lib/matplotlib/tests/test_axes.py::test_bar_labels[x2-width2-label2-expected_labels2-_nolegend_]", "lib/matplotlib/tests/test_axes.py::test_bar_labels[x3-width3-bars-expected_labels3-bars]", "lib/matplotlib/tests/test_axes.py::test_bar_labels_length", "lib/matplotlib/tests/test_axes.py::test_pandas_minimal_plot", "lib/matplotlib/tests/test_axes.py::test_hist_log[png]", "lib/matplotlib/tests/test_axes.py::test_hist_log_2[png]", "lib/matplotlib/tests/test_axes.py::test_hist_log_barstacked", "lib/matplotlib/tests/test_axes.py::test_hist_bar_empty[png]", "lib/matplotlib/tests/test_axes.py::test_hist_float16", "lib/matplotlib/tests/test_axes.py::test_hist_step_empty[png]", "lib/matplotlib/tests/test_axes.py::test_hist_step_filled[png]", "lib/matplotlib/tests/test_axes.py::test_hist_density[png]", "lib/matplotlib/tests/test_axes.py::test_hist_unequal_bins_density", "lib/matplotlib/tests/test_axes.py::test_hist_datetime_datasets", "lib/matplotlib/tests/test_axes.py::test_hist_datetime_datasets_bins[date2num]", "lib/matplotlib/tests/test_axes.py::test_hist_datetime_datasets_bins[datetime.datetime]", "lib/matplotlib/tests/test_axes.py::test_hist_datetime_datasets_bins[np.datetime64]", "lib/matplotlib/tests/test_axes.py::test_hist_with_empty_input[data0-1]", "lib/matplotlib/tests/test_axes.py::test_hist_with_empty_input[data1-1]", "lib/matplotlib/tests/test_axes.py::test_hist_with_empty_input[data2-2]", "lib/matplotlib/tests/test_axes.py::test_hist_zorder[bar-1]", "lib/matplotlib/tests/test_axes.py::test_hist_zorder[step-2]", "lib/matplotlib/tests/test_axes.py::test_hist_zorder[stepfilled-1]", "lib/matplotlib/tests/test_axes.py::test_stairs[png]", "lib/matplotlib/tests/test_axes.py::test_stairs_fill[png]", "lib/matplotlib/tests/test_axes.py::test_stairs_update[png]", "lib/matplotlib/tests/test_axes.py::test_stairs_baseline_0[png]", "lib/matplotlib/tests/test_axes.py::test_stairs_empty", "lib/matplotlib/tests/test_axes.py::test_stairs_invalid_nan", "lib/matplotlib/tests/test_axes.py::test_stairs_invalid_mismatch", "lib/matplotlib/tests/test_axes.py::test_stairs_invalid_update", "lib/matplotlib/tests/test_axes.py::test_stairs_invalid_update2", "lib/matplotlib/tests/test_axes.py::test_stairs_options[png]", "lib/matplotlib/tests/test_axes.py::test_stairs_datetime[png]", "lib/matplotlib/tests/test_axes.py::test_stairs_edge_handling[png]", "lib/matplotlib/tests/test_axes.py::test_contour_hatching[png]", "lib/matplotlib/tests/test_axes.py::test_contour_colorbar[png]", "lib/matplotlib/tests/test_axes.py::test_hist2d[png]", "lib/matplotlib/tests/test_axes.py::test_hist2d_transpose[png]", "lib/matplotlib/tests/test_axes.py::test_hist2d_density", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_plot[png]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_marker[png]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_2D[png]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_decimal[png]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_color", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_color_warning[kwargs0]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_color_warning[kwargs1]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_color_warning[kwargs2]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_color_warning[kwargs3]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_unfilled", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_unfillable", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_size_arg_size", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_edgecolor_RGB", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_invalid_color[png]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_no_invalid_color[png]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_norm_vminvmax", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_single_point[png]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_different_shapes[png]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[0.5-None]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case1-conversion]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[red-None]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[none-None]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[None-None]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case5-None]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[jaune-conversion]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case7-conversion]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case8-conversion]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case9-None]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case10-None]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case11-shape]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case12-None]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case13-None]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case14-conversion]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case15-None]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case16-shape]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case17-None]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case18-shape]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case19-None]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case20-shape]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case21-None]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case22-shape]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case23-None]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case24-shape]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case25-None]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case26-shape]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case27-conversion]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case28-conversion]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case29-conversion]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_single_color_c[png]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_linewidths", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_singular_plural_arguments", "lib/matplotlib/tests/test_axes.py::test_parse_scatter_color_args[params0-expected_result0]", "lib/matplotlib/tests/test_axes.py::test_parse_scatter_color_args[params1-expected_result1]", "lib/matplotlib/tests/test_axes.py::test_parse_scatter_color_args[params2-expected_result2]", "lib/matplotlib/tests/test_axes.py::test_parse_scatter_color_args[params3-expected_result3]", "lib/matplotlib/tests/test_axes.py::test_parse_scatter_color_args[params4-expected_result4]", "lib/matplotlib/tests/test_axes.py::test_parse_scatter_color_args_edgecolors[kwargs0-None]", "lib/matplotlib/tests/test_axes.py::test_parse_scatter_color_args_edgecolors[kwargs1-None]", "lib/matplotlib/tests/test_axes.py::test_parse_scatter_color_args_edgecolors[kwargs2-r]", "lib/matplotlib/tests/test_axes.py::test_parse_scatter_color_args_edgecolors[kwargs3-expected_edgecolors3]", "lib/matplotlib/tests/test_axes.py::test_parse_scatter_color_args_edgecolors[kwargs4-r]", "lib/matplotlib/tests/test_axes.py::test_parse_scatter_color_args_edgecolors[kwargs5-face]", "lib/matplotlib/tests/test_axes.py::test_parse_scatter_color_args_edgecolors[kwargs6-none]", "lib/matplotlib/tests/test_axes.py::test_parse_scatter_color_args_edgecolors[kwargs7-r]", "lib/matplotlib/tests/test_axes.py::test_parse_scatter_color_args_edgecolors[kwargs8-r]", "lib/matplotlib/tests/test_axes.py::test_parse_scatter_color_args_edgecolors[kwargs9-r]", "lib/matplotlib/tests/test_axes.py::test_parse_scatter_color_args_edgecolors[kwargs10-g]", "lib/matplotlib/tests/test_axes.py::test_parse_scatter_color_args_error", "lib/matplotlib/tests/test_axes.py::test_as_mpl_axes_api", "lib/matplotlib/tests/test_axes.py::test_pyplot_axes", "lib/matplotlib/tests/test_axes.py::test_log_scales", "lib/matplotlib/tests/test_axes.py::test_log_scales_no_data", "lib/matplotlib/tests/test_axes.py::test_log_scales_invalid", "lib/matplotlib/tests/test_axes.py::test_stackplot[png]", "lib/matplotlib/tests/test_axes.py::test_stackplot_baseline[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_baseline[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_rangewhis[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_percentilewhis[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_with_xlabels[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_horizontal[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_with_ylabels[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_patchartist[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_custompatchartist[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_customoutlier[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_showcustommean[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_custombox[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_custommedian[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_customcap[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_customwhisker[png]", "lib/matplotlib/tests/test_axes.py::test_boxplot_median_bound_by_box[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_shownotches[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_nocaps[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_nobox[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_no_flier_stats[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_showmean[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_showmeanasline[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_scalarwidth[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_customwidths[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_custompositions[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_bad_widths", "lib/matplotlib/tests/test_axes.py::test_bxp_bad_positions", "lib/matplotlib/tests/test_axes.py::test_bxp_custom_capwidths[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_custom_capwidth[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_bad_capwidths", "lib/matplotlib/tests/test_axes.py::test_boxplot[png]", "lib/matplotlib/tests/test_axes.py::test_boxplot_custom_capwidths[png]", "lib/matplotlib/tests/test_axes.py::test_boxplot_sym2[png]", "lib/matplotlib/tests/test_axes.py::test_boxplot_sym[png]", "lib/matplotlib/tests/test_axes.py::test_boxplot_autorange_whiskers[png]", "lib/matplotlib/tests/test_axes.py::test_boxplot_rc_parameters[png]", "lib/matplotlib/tests/test_axes.py::test_boxplot_with_CIarray[png]", "lib/matplotlib/tests/test_axes.py::test_boxplot_no_weird_whisker[png]", "lib/matplotlib/tests/test_axes.py::test_boxplot_bad_medians", "lib/matplotlib/tests/test_axes.py::test_boxplot_bad_ci", "lib/matplotlib/tests/test_axes.py::test_boxplot_zorder", "lib/matplotlib/tests/test_axes.py::test_boxplot_marker_behavior", "lib/matplotlib/tests/test_axes.py::test_boxplot_mod_artist_after_plotting[png]", "lib/matplotlib/tests/test_axes.py::test_vert_violinplot_baseline[png]", "lib/matplotlib/tests/test_axes.py::test_vert_violinplot_showmeans[png]", "lib/matplotlib/tests/test_axes.py::test_vert_violinplot_showextrema[png]", "lib/matplotlib/tests/test_axes.py::test_vert_violinplot_showmedians[png]", "lib/matplotlib/tests/test_axes.py::test_vert_violinplot_showall[png]", "lib/matplotlib/tests/test_axes.py::test_vert_violinplot_custompoints_10[png]", "lib/matplotlib/tests/test_axes.py::test_vert_violinplot_custompoints_200[png]", "lib/matplotlib/tests/test_axes.py::test_horiz_violinplot_baseline[png]", "lib/matplotlib/tests/test_axes.py::test_horiz_violinplot_showmedians[png]", "lib/matplotlib/tests/test_axes.py::test_horiz_violinplot_showmeans[png]", "lib/matplotlib/tests/test_axes.py::test_horiz_violinplot_showextrema[png]", "lib/matplotlib/tests/test_axes.py::test_horiz_violinplot_showall[png]", "lib/matplotlib/tests/test_axes.py::test_horiz_violinplot_custompoints_10[png]", "lib/matplotlib/tests/test_axes.py::test_horiz_violinplot_custompoints_200[png]", "lib/matplotlib/tests/test_axes.py::test_violinplot_bad_positions", "lib/matplotlib/tests/test_axes.py::test_violinplot_bad_widths", "lib/matplotlib/tests/test_axes.py::test_violinplot_bad_quantiles", "lib/matplotlib/tests/test_axes.py::test_violinplot_outofrange_quantiles", "lib/matplotlib/tests/test_axes.py::test_violinplot_single_list_quantiles[png]", "lib/matplotlib/tests/test_axes.py::test_violinplot_pandas_series[png]", "lib/matplotlib/tests/test_axes.py::test_manage_xticks", "lib/matplotlib/tests/test_axes.py::test_boxplot_not_single", "lib/matplotlib/tests/test_axes.py::test_tick_space_size_0", "lib/matplotlib/tests/test_axes.py::test_errorbar[png]", "lib/matplotlib/tests/test_axes.py::test_mixed_errorbar_polar_caps[png]", "lib/matplotlib/tests/test_axes.py::test_errorbar_colorcycle", "lib/matplotlib/tests/test_axes.py::test_errorbar_cycle_ecolor[png]", "lib/matplotlib/tests/test_axes.py::test_errorbar_shape", "lib/matplotlib/tests/test_axes.py::test_errorbar_limits[png]", "lib/matplotlib/tests/test_axes.py::test_errorbar_nonefmt", "lib/matplotlib/tests/test_axes.py::test_errorbar_line_specific_kwargs", "lib/matplotlib/tests/test_axes.py::test_errorbar_with_prop_cycle[png]", "lib/matplotlib/tests/test_axes.py::test_errorbar_every_invalid", "lib/matplotlib/tests/test_axes.py::test_xerr_yerr_not_negative", "lib/matplotlib/tests/test_axes.py::test_errorbar_every[png]", "lib/matplotlib/tests/test_axes.py::test_errorbar_linewidth_type[elinewidth0]", "lib/matplotlib/tests/test_axes.py::test_errorbar_linewidth_type[elinewidth1]", "lib/matplotlib/tests/test_axes.py::test_errorbar_linewidth_type[1]", "lib/matplotlib/tests/test_axes.py::test_errorbar_nan[png]", "lib/matplotlib/tests/test_axes.py::test_hist_stacked_stepfilled[png]", "lib/matplotlib/tests/test_axes.py::test_hist_offset[png]", "lib/matplotlib/tests/test_axes.py::test_hist_step[png]", "lib/matplotlib/tests/test_axes.py::test_hist_step_horiz[png]", "lib/matplotlib/tests/test_axes.py::test_hist_stacked_weighted[png]", "lib/matplotlib/tests/test_axes.py::test_stem[png]", "lib/matplotlib/tests/test_axes.py::test_stem_args", "lib/matplotlib/tests/test_axes.py::test_stem_markerfmt", "lib/matplotlib/tests/test_axes.py::test_stem_dates", "lib/matplotlib/tests/test_axes.py::test_stem_orientation[png]", "lib/matplotlib/tests/test_axes.py::test_hist_stacked_stepfilled_alpha[png]", "lib/matplotlib/tests/test_axes.py::test_hist_stacked_step[png]", "lib/matplotlib/tests/test_axes.py::test_hist_stacked_density[png]", "lib/matplotlib/tests/test_axes.py::test_hist_step_bottom[png]", "lib/matplotlib/tests/test_axes.py::test_hist_stepfilled_geometry", "lib/matplotlib/tests/test_axes.py::test_hist_step_geometry", "lib/matplotlib/tests/test_axes.py::test_hist_stepfilled_bottom_geometry", "lib/matplotlib/tests/test_axes.py::test_hist_step_bottom_geometry", "lib/matplotlib/tests/test_axes.py::test_hist_stacked_stepfilled_geometry", "lib/matplotlib/tests/test_axes.py::test_hist_stacked_step_geometry", "lib/matplotlib/tests/test_axes.py::test_hist_stacked_stepfilled_bottom_geometry", "lib/matplotlib/tests/test_axes.py::test_hist_stacked_step_bottom_geometry", "lib/matplotlib/tests/test_axes.py::test_hist_stacked_bar[png]", "lib/matplotlib/tests/test_axes.py::test_hist_barstacked_bottom_unchanged", "lib/matplotlib/tests/test_axes.py::test_hist_emptydata", "lib/matplotlib/tests/test_axes.py::test_hist_labels", "lib/matplotlib/tests/test_axes.py::test_transparent_markers[png]", "lib/matplotlib/tests/test_axes.py::test_rgba_markers[png]", "lib/matplotlib/tests/test_axes.py::test_mollweide_grid[png]", "lib/matplotlib/tests/test_axes.py::test_mollweide_forward_inverse_closure", "lib/matplotlib/tests/test_axes.py::test_mollweide_inverse_forward_closure", "lib/matplotlib/tests/test_axes.py::test_alpha[png]", "lib/matplotlib/tests/test_axes.py::test_eventplot[png]", "lib/matplotlib/tests/test_axes.py::test_eventplot_defaults[png]", "lib/matplotlib/tests/test_axes.py::test_eventplot_colors[colors0]", "lib/matplotlib/tests/test_axes.py::test_eventplot_colors[colors1]", "lib/matplotlib/tests/test_axes.py::test_eventplot_colors[colors2]", "lib/matplotlib/tests/test_axes.py::test_eventplot_alpha", "lib/matplotlib/tests/test_axes.py::test_eventplot_problem_kwargs[png]", "lib/matplotlib/tests/test_axes.py::test_empty_eventplot", "lib/matplotlib/tests/test_axes.py::test_eventplot_orientation[None-data0]", "lib/matplotlib/tests/test_axes.py::test_eventplot_orientation[None-data1]", "lib/matplotlib/tests/test_axes.py::test_eventplot_orientation[None-data2]", "lib/matplotlib/tests/test_axes.py::test_eventplot_orientation[vertical-data0]", "lib/matplotlib/tests/test_axes.py::test_eventplot_orientation[vertical-data1]", "lib/matplotlib/tests/test_axes.py::test_eventplot_orientation[vertical-data2]", "lib/matplotlib/tests/test_axes.py::test_eventplot_orientation[horizontal-data0]", "lib/matplotlib/tests/test_axes.py::test_eventplot_orientation[horizontal-data1]", "lib/matplotlib/tests/test_axes.py::test_eventplot_orientation[horizontal-data2]", "lib/matplotlib/tests/test_axes.py::test_eventplot_units_list[png]", "lib/matplotlib/tests/test_axes.py::test_marker_styles[png]", "lib/matplotlib/tests/test_axes.py::test_markers_fillstyle_rcparams[png]", "lib/matplotlib/tests/test_axes.py::test_vertex_markers[png]", "lib/matplotlib/tests/test_axes.py::test_eb_line_zorder[png]", "lib/matplotlib/tests/test_axes.py::test_axline_loglog[png]", "lib/matplotlib/tests/test_axes.py::test_axline[png]", "lib/matplotlib/tests/test_axes.py::test_axline_transaxes[png]", "lib/matplotlib/tests/test_axes.py::test_axline_transaxes_panzoom[png]", "lib/matplotlib/tests/test_axes.py::test_axline_args", "lib/matplotlib/tests/test_axes.py::test_vlines[png]", "lib/matplotlib/tests/test_axes.py::test_vlines_default", "lib/matplotlib/tests/test_axes.py::test_hlines[png]", "lib/matplotlib/tests/test_axes.py::test_hlines_default", "lib/matplotlib/tests/test_axes.py::test_lines_with_colors[png-data0]", "lib/matplotlib/tests/test_axes.py::test_lines_with_colors[png-data1]", "lib/matplotlib/tests/test_axes.py::test_vlines_hlines_blended_transform[png]", "lib/matplotlib/tests/test_axes.py::test_step_linestyle[png]", "lib/matplotlib/tests/test_axes.py::test_mixed_collection[png]", "lib/matplotlib/tests/test_axes.py::test_subplot_key_hash", "lib/matplotlib/tests/test_axes.py::test_specgram[png]", "lib/matplotlib/tests/test_axes.py::test_specgram_magnitude[png]", "lib/matplotlib/tests/test_axes.py::test_specgram_angle[png]", "lib/matplotlib/tests/test_axes.py::test_specgram_fs_none", "lib/matplotlib/tests/test_axes.py::test_specgram_origin_rcparam[png]", "lib/matplotlib/tests/test_axes.py::test_specgram_origin_kwarg", "lib/matplotlib/tests/test_axes.py::test_psd_csd[png]", "lib/matplotlib/tests/test_axes.py::test_spectrum[png]", "lib/matplotlib/tests/test_axes.py::test_psd_csd_edge_cases", "lib/matplotlib/tests/test_axes.py::test_twin_remove[png]", "lib/matplotlib/tests/test_axes.py::test_twin_spines[png]", "lib/matplotlib/tests/test_axes.py::test_twin_spines_on_top[png]", "lib/matplotlib/tests/test_axes.py::test_rcparam_grid_minor[both-True-True]", "lib/matplotlib/tests/test_axes.py::test_rcparam_grid_minor[major-True-False]", "lib/matplotlib/tests/test_axes.py::test_rcparam_grid_minor[minor-False-True]", "lib/matplotlib/tests/test_axes.py::test_grid", "lib/matplotlib/tests/test_axes.py::test_reset_grid", "lib/matplotlib/tests/test_axes.py::test_reset_ticks[png]", "lib/matplotlib/tests/test_axes.py::test_vline_limit", "lib/matplotlib/tests/test_axes.py::test_axline_minmax[axvline-axhline-args0]", "lib/matplotlib/tests/test_axes.py::test_axline_minmax[axvspan-axhspan-args1]", "lib/matplotlib/tests/test_axes.py::test_empty_shared_subplots", "lib/matplotlib/tests/test_axes.py::test_shared_with_aspect_1", "lib/matplotlib/tests/test_axes.py::test_shared_with_aspect_2", "lib/matplotlib/tests/test_axes.py::test_shared_with_aspect_3", "lib/matplotlib/tests/test_axes.py::test_shared_aspect_error", "lib/matplotlib/tests/test_axes.py::test_axis_errors[TypeError-args0-kwargs0-axis\\\\(\\\\)", "lib/matplotlib/tests/test_axes.py::test_axis_errors[ValueError-args1-kwargs1-Unrecognized", "lib/matplotlib/tests/test_axes.py::test_axis_errors[TypeError-args2-kwargs2-The", "lib/matplotlib/tests/test_axes.py::test_axis_errors[TypeError-args3-kwargs3-axis\\\\(\\\\)", "lib/matplotlib/tests/test_axes.py::test_axis_method_errors", "lib/matplotlib/tests/test_axes.py::test_twin_with_aspect[x]", "lib/matplotlib/tests/test_axes.py::test_twin_with_aspect[y]", "lib/matplotlib/tests/test_axes.py::test_relim_visible_only", "lib/matplotlib/tests/test_axes.py::test_text_labelsize", "lib/matplotlib/tests/test_axes.py::test_pie_default[png]", "lib/matplotlib/tests/test_axes.py::test_pie_linewidth_0[png]", "lib/matplotlib/tests/test_axes.py::test_pie_center_radius[png]", "lib/matplotlib/tests/test_axes.py::test_pie_linewidth_2[png]", "lib/matplotlib/tests/test_axes.py::test_pie_ccw_true[png]", "lib/matplotlib/tests/test_axes.py::test_pie_frame_grid[png]", "lib/matplotlib/tests/test_axes.py::test_pie_rotatelabels_true[png]", "lib/matplotlib/tests/test_axes.py::test_pie_nolabel_but_legend[png]", "lib/matplotlib/tests/test_axes.py::test_pie_shadow[png]", "lib/matplotlib/tests/test_axes.py::test_pie_textprops", "lib/matplotlib/tests/test_axes.py::test_pie_get_negative_values", "lib/matplotlib/tests/test_axes.py::test_normalize_kwarg_pie", "lib/matplotlib/tests/test_axes.py::test_pie_hatch_single[png]", "lib/matplotlib/tests/test_axes.py::test_pie_hatch_multi[png]", "lib/matplotlib/tests/test_axes.py::test_set_get_ticklabels[png]", "lib/matplotlib/tests/test_axes.py::test_set_ticks_kwargs_raise_error_without_labels", "lib/matplotlib/tests/test_axes.py::test_set_ticks_with_labels[png]", "lib/matplotlib/tests/test_axes.py::test_xticks_bad_args", "lib/matplotlib/tests/test_axes.py::test_subsampled_ticklabels", "lib/matplotlib/tests/test_axes.py::test_mismatched_ticklabels", "lib/matplotlib/tests/test_axes.py::test_empty_ticks_fixed_loc", "lib/matplotlib/tests/test_axes.py::test_retain_tick_visibility[png]", "lib/matplotlib/tests/test_axes.py::test_warn_too_few_labels", "lib/matplotlib/tests/test_axes.py::test_tick_label_update", "lib/matplotlib/tests/test_axes.py::test_o_marker_path_snap[png]", "lib/matplotlib/tests/test_axes.py::test_margins", "lib/matplotlib/tests/test_axes.py::test_set_margin_updates_limits", "lib/matplotlib/tests/test_axes.py::test_margins_errors[ValueError-args0-kwargs0-margin", "lib/matplotlib/tests/test_axes.py::test_margins_errors[ValueError-args1-kwargs1-margin", "lib/matplotlib/tests/test_axes.py::test_margins_errors[ValueError-args2-kwargs2-margin", "lib/matplotlib/tests/test_axes.py::test_margins_errors[ValueError-args3-kwargs3-margin", "lib/matplotlib/tests/test_axes.py::test_margins_errors[TypeError-args4-kwargs4-Cannot", "lib/matplotlib/tests/test_axes.py::test_margins_errors[TypeError-args5-kwargs5-Cannot", "lib/matplotlib/tests/test_axes.py::test_margins_errors[TypeError-args6-kwargs6-Must", "lib/matplotlib/tests/test_axes.py::test_length_one_hist", "lib/matplotlib/tests/test_axes.py::test_set_xy_bound", "lib/matplotlib/tests/test_axes.py::test_pathological_hexbin", "lib/matplotlib/tests/test_axes.py::test_color_None", "lib/matplotlib/tests/test_axes.py::test_color_alias", "lib/matplotlib/tests/test_axes.py::test_numerical_hist_label", "lib/matplotlib/tests/test_axes.py::test_unicode_hist_label", "lib/matplotlib/tests/test_axes.py::test_move_offsetlabel", "lib/matplotlib/tests/test_axes.py::test_rc_spines[png]", "lib/matplotlib/tests/test_axes.py::test_rc_grid[png]", "lib/matplotlib/tests/test_axes.py::test_rc_tick", "lib/matplotlib/tests/test_axes.py::test_rc_major_minor_tick", "lib/matplotlib/tests/test_axes.py::test_square_plot", "lib/matplotlib/tests/test_axes.py::test_bad_plot_args", "lib/matplotlib/tests/test_axes.py::test_pcolorfast[data0-xy0-AxesImage]", "lib/matplotlib/tests/test_axes.py::test_pcolorfast[data0-xy1-AxesImage]", "lib/matplotlib/tests/test_axes.py::test_pcolorfast[data0-xy2-AxesImage]", "lib/matplotlib/tests/test_axes.py::test_pcolorfast[data0-xy3-PcolorImage]", "lib/matplotlib/tests/test_axes.py::test_pcolorfast[data0-xy4-QuadMesh]", "lib/matplotlib/tests/test_axes.py::test_pcolorfast[data1-xy0-AxesImage]", "lib/matplotlib/tests/test_axes.py::test_pcolorfast[data1-xy1-AxesImage]", "lib/matplotlib/tests/test_axes.py::test_pcolorfast[data1-xy2-AxesImage]", "lib/matplotlib/tests/test_axes.py::test_pcolorfast[data1-xy3-PcolorImage]", "lib/matplotlib/tests/test_axes.py::test_pcolorfast[data1-xy4-QuadMesh]", "lib/matplotlib/tests/test_axes.py::test_shared_scale", "lib/matplotlib/tests/test_axes.py::test_shared_bool", "lib/matplotlib/tests/test_axes.py::test_violin_point_mass", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs0]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs1]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs2]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs3]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs4]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs5]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs6]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs7]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs8]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs9]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs10]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs11]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs12]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs13]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs14]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs15]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs16]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs17]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs18]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs19]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs20]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs21]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs22]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs23]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs24]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs25]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs26]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs27]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs28]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs29]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs30]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs31]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs32]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs33]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs34]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs35]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs36]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs37]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs38]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs39]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs40]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs41]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs42]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs43]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs44]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs45]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs46]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs47]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs48]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs49]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs50]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs51]", "lib/matplotlib/tests/test_axes.py::test_dash_offset[png]", "lib/matplotlib/tests/test_axes.py::test_title_pad", "lib/matplotlib/tests/test_axes.py::test_title_location_roundtrip", "lib/matplotlib/tests/test_axes.py::test_title_location_shared[True]", "lib/matplotlib/tests/test_axes.py::test_title_location_shared[False]", "lib/matplotlib/tests/test_axes.py::test_loglog[png]", "lib/matplotlib/tests/test_axes.py::test_loglog_nonpos[png]", "lib/matplotlib/tests/test_axes.py::test_axes_margins", "lib/matplotlib/tests/test_axes.py::test_remove_shared_axes[gca-x]", "lib/matplotlib/tests/test_axes.py::test_remove_shared_axes[gca-y]", "lib/matplotlib/tests/test_axes.py::test_remove_shared_axes[subplots-x]", "lib/matplotlib/tests/test_axes.py::test_remove_shared_axes[subplots-y]", "lib/matplotlib/tests/test_axes.py::test_remove_shared_axes[subplots_shared-x]", "lib/matplotlib/tests/test_axes.py::test_remove_shared_axes[subplots_shared-y]", "lib/matplotlib/tests/test_axes.py::test_remove_shared_axes[add_axes-x]", "lib/matplotlib/tests/test_axes.py::test_remove_shared_axes[add_axes-y]", "lib/matplotlib/tests/test_axes.py::test_remove_shared_axes_relim", "lib/matplotlib/tests/test_axes.py::test_shared_axes_autoscale", "lib/matplotlib/tests/test_axes.py::test_adjust_numtick_aspect", "lib/matplotlib/tests/test_axes.py::test_auto_numticks", "lib/matplotlib/tests/test_axes.py::test_auto_numticks_log", "lib/matplotlib/tests/test_axes.py::test_broken_barh_empty", "lib/matplotlib/tests/test_axes.py::test_broken_barh_timedelta", "lib/matplotlib/tests/test_axes.py::test_pandas_pcolormesh", "lib/matplotlib/tests/test_axes.py::test_pandas_indexing_dates", "lib/matplotlib/tests/test_axes.py::test_pandas_errorbar_indexing", "lib/matplotlib/tests/test_axes.py::test_pandas_index_shape", "lib/matplotlib/tests/test_axes.py::test_pandas_indexing_hist", "lib/matplotlib/tests/test_axes.py::test_pandas_bar_align_center", "lib/matplotlib/tests/test_axes.py::test_axis_get_tick_params", "lib/matplotlib/tests/test_axes.py::test_axis_set_tick_params_labelsize_labelcolor", "lib/matplotlib/tests/test_axes.py::test_axes_tick_params_gridlines", "lib/matplotlib/tests/test_axes.py::test_axes_tick_params_ylabelside", "lib/matplotlib/tests/test_axes.py::test_axes_tick_params_xlabelside", "lib/matplotlib/tests/test_axes.py::test_none_kwargs", "lib/matplotlib/tests/test_axes.py::test_bar_uint8", "lib/matplotlib/tests/test_axes.py::test_date_timezone_x[png]", "lib/matplotlib/tests/test_axes.py::test_date_timezone_y[png]", "lib/matplotlib/tests/test_axes.py::test_date_timezone_x_and_y[png]", "lib/matplotlib/tests/test_axes.py::test_axisbelow[png]", "lib/matplotlib/tests/test_axes.py::test_titletwiny", "lib/matplotlib/tests/test_axes.py::test_titlesetpos", "lib/matplotlib/tests/test_axes.py::test_title_xticks_top", "lib/matplotlib/tests/test_axes.py::test_title_xticks_top_both", "lib/matplotlib/tests/test_axes.py::test_title_above_offset[left", "lib/matplotlib/tests/test_axes.py::test_title_above_offset[center", "lib/matplotlib/tests/test_axes.py::test_title_above_offset[both", "lib/matplotlib/tests/test_axes.py::test_title_no_move_off_page", "lib/matplotlib/tests/test_axes.py::test_offset_label_color", "lib/matplotlib/tests/test_axes.py::test_offset_text_visible", "lib/matplotlib/tests/test_axes.py::test_large_offset", "lib/matplotlib/tests/test_axes.py::test_barb_units", "lib/matplotlib/tests/test_axes.py::test_quiver_units", "lib/matplotlib/tests/test_axes.py::test_bar_color_cycle", "lib/matplotlib/tests/test_axes.py::test_tick_param_label_rotation", "lib/matplotlib/tests/test_axes.py::test_fillbetween_cycle", "lib/matplotlib/tests/test_axes.py::test_log_margins", "lib/matplotlib/tests/test_axes.py::test_color_length_mismatch", "lib/matplotlib/tests/test_axes.py::test_eventplot_legend", "lib/matplotlib/tests/test_axes.py::test_eventplot_errors[ValueError-args0-kwargs0-lineoffsets", "lib/matplotlib/tests/test_axes.py::test_eventplot_errors[ValueError-args1-kwargs1-linelengths", "lib/matplotlib/tests/test_axes.py::test_eventplot_errors[ValueError-args2-kwargs2-linewidths", "lib/matplotlib/tests/test_axes.py::test_eventplot_errors[ValueError-args3-kwargs3-linestyles", "lib/matplotlib/tests/test_axes.py::test_eventplot_errors[ValueError-args4-kwargs4-alpha", "lib/matplotlib/tests/test_axes.py::test_eventplot_errors[ValueError-args5-kwargs5-positions", "lib/matplotlib/tests/test_axes.py::test_eventplot_errors[ValueError-args6-kwargs6-lineoffsets", "lib/matplotlib/tests/test_axes.py::test_eventplot_errors[ValueError-args7-kwargs7-linelengths", "lib/matplotlib/tests/test_axes.py::test_eventplot_errors[ValueError-args8-kwargs8-linewidths", "lib/matplotlib/tests/test_axes.py::test_eventplot_errors[ValueError-args9-kwargs9-linestyles", "lib/matplotlib/tests/test_axes.py::test_eventplot_errors[ValueError-args10-kwargs10-alpha", "lib/matplotlib/tests/test_axes.py::test_eventplot_errors[ValueError-args11-kwargs11-colors", "lib/matplotlib/tests/test_axes.py::test_bar_broadcast_args", "lib/matplotlib/tests/test_axes.py::test_invalid_axis_limits", "lib/matplotlib/tests/test_axes.py::test_minorticks_on[symlog-symlog]", "lib/matplotlib/tests/test_axes.py::test_minorticks_on[symlog-log]", "lib/matplotlib/tests/test_axes.py::test_minorticks_on[log-symlog]", "lib/matplotlib/tests/test_axes.py::test_minorticks_on[log-log]", "lib/matplotlib/tests/test_axes.py::test_twinx_knows_limits", "lib/matplotlib/tests/test_axes.py::test_zero_linewidth", "lib/matplotlib/tests/test_axes.py::test_empty_errorbar_legend", "lib/matplotlib/tests/test_axes.py::test_plot_decimal[png]", "lib/matplotlib/tests/test_axes.py::test_markerfacecolor_none_alpha[png]", "lib/matplotlib/tests/test_axes.py::test_tick_padding_tightbbox", "lib/matplotlib/tests/test_axes.py::test_inset", "lib/matplotlib/tests/test_axes.py::test_zoom_inset", "lib/matplotlib/tests/test_axes.py::test_inset_polar[png]", "lib/matplotlib/tests/test_axes.py::test_inset_projection", "lib/matplotlib/tests/test_axes.py::test_inset_subclass", "lib/matplotlib/tests/test_axes.py::test_indicate_inset_inverted[False-False]", "lib/matplotlib/tests/test_axes.py::test_indicate_inset_inverted[False-True]", "lib/matplotlib/tests/test_axes.py::test_indicate_inset_inverted[True-False]", "lib/matplotlib/tests/test_axes.py::test_indicate_inset_inverted[True-True]", "lib/matplotlib/tests/test_axes.py::test_set_position", "lib/matplotlib/tests/test_axes.py::test_spines_properbbox_after_zoom", "lib/matplotlib/tests/test_axes.py::test_limits_after_scroll_zoom", "lib/matplotlib/tests/test_axes.py::test_gettightbbox_ignore_nan", "lib/matplotlib/tests/test_axes.py::test_scatter_series_non_zero_index", "lib/matplotlib/tests/test_axes.py::test_scatter_empty_data", "lib/matplotlib/tests/test_axes.py::test_annotate_across_transforms[png]", "lib/matplotlib/tests/test_axes.py::test_secondary_xy[png]", "lib/matplotlib/tests/test_axes.py::test_secondary_fail", "lib/matplotlib/tests/test_axes.py::test_secondary_resize", "lib/matplotlib/tests/test_axes.py::test_secondary_minorloc", "lib/matplotlib/tests/test_axes.py::test_secondary_formatter", "lib/matplotlib/tests/test_axes.py::test_secondary_repr", "lib/matplotlib/tests/test_axes.py::test_axis_options[png]", "lib/matplotlib/tests/test_axes.py::test_normal_axes", "lib/matplotlib/tests/test_axes.py::test_nodecorator", "lib/matplotlib/tests/test_axes.py::test_displaced_spine", "lib/matplotlib/tests/test_axes.py::test_tickdirs", "lib/matplotlib/tests/test_axes.py::test_minor_accountedfor", "lib/matplotlib/tests/test_axes.py::test_axis_bool_arguments[png]", "lib/matplotlib/tests/test_axes.py::test_axis_extent_arg", "lib/matplotlib/tests/test_axes.py::test_axis_extent_arg2", "lib/matplotlib/tests/test_axes.py::test_hist_auto_bins", "lib/matplotlib/tests/test_axes.py::test_hist_nan_data", "lib/matplotlib/tests/test_axes.py::test_hist_range_and_density", "lib/matplotlib/tests/test_axes.py::test_bar_errbar_zorder", "lib/matplotlib/tests/test_axes.py::test_set_ticks_inverted", "lib/matplotlib/tests/test_axes.py::test_aspect_nonlinear_adjustable_box", "lib/matplotlib/tests/test_axes.py::test_aspect_nonlinear_adjustable_datalim", "lib/matplotlib/tests/test_axes.py::test_box_aspect", "lib/matplotlib/tests/test_axes.py::test_box_aspect_custom_position", "lib/matplotlib/tests/test_axes.py::test_bbox_aspect_axes_init", "lib/matplotlib/tests/test_axes.py::test_set_aspect_negative", "lib/matplotlib/tests/test_axes.py::test_redraw_in_frame", "lib/matplotlib/tests/test_axes.py::test_invisible_axes_events", "lib/matplotlib/tests/test_axes.py::test_xtickcolor_is_not_markercolor", "lib/matplotlib/tests/test_axes.py::test_ytickcolor_is_not_markercolor", "lib/matplotlib/tests/test_axes.py::test_unautoscale[True-x]", "lib/matplotlib/tests/test_axes.py::test_unautoscale[True-y]", "lib/matplotlib/tests/test_axes.py::test_unautoscale[False-x]", "lib/matplotlib/tests/test_axes.py::test_unautoscale[False-y]", "lib/matplotlib/tests/test_axes.py::test_unautoscale[None-x]", "lib/matplotlib/tests/test_axes.py::test_unautoscale[None-y]", "lib/matplotlib/tests/test_axes.py::test_polar_interpolation_steps_variable_r[png]", "lib/matplotlib/tests/test_axes.py::test_autoscale_tiny_sticky", "lib/matplotlib/tests/test_axes.py::test_xtickcolor_is_not_xticklabelcolor", "lib/matplotlib/tests/test_axes.py::test_ytickcolor_is_not_yticklabelcolor", "lib/matplotlib/tests/test_axes.py::test_xaxis_offsetText_color", "lib/matplotlib/tests/test_axes.py::test_yaxis_offsetText_color", "lib/matplotlib/tests/test_axes.py::test_relative_ticklabel_sizes[xx-small]", "lib/matplotlib/tests/test_axes.py::test_relative_ticklabel_sizes[x-small]", "lib/matplotlib/tests/test_axes.py::test_relative_ticklabel_sizes[small]", "lib/matplotlib/tests/test_axes.py::test_relative_ticklabel_sizes[medium]", "lib/matplotlib/tests/test_axes.py::test_relative_ticklabel_sizes[large]", "lib/matplotlib/tests/test_axes.py::test_relative_ticklabel_sizes[x-large]", "lib/matplotlib/tests/test_axes.py::test_relative_ticklabel_sizes[xx-large]", "lib/matplotlib/tests/test_axes.py::test_relative_ticklabel_sizes[larger]", "lib/matplotlib/tests/test_axes.py::test_relative_ticklabel_sizes[smaller]", "lib/matplotlib/tests/test_axes.py::test_relative_ticklabel_sizes[8]", "lib/matplotlib/tests/test_axes.py::test_relative_ticklabel_sizes[10]", "lib/matplotlib/tests/test_axes.py::test_relative_ticklabel_sizes[12]", "lib/matplotlib/tests/test_axes.py::test_multiplot_autoscale", "lib/matplotlib/tests/test_axes.py::test_sharing_does_not_link_positions", "lib/matplotlib/tests/test_axes.py::test_shared_axes_clear[png]", "lib/matplotlib/tests/test_axes.py::test_shared_axes_retick", "lib/matplotlib/tests/test_axes.py::test_ylabel_ha_with_position[left]", "lib/matplotlib/tests/test_axes.py::test_ylabel_ha_with_position[center]", "lib/matplotlib/tests/test_axes.py::test_ylabel_ha_with_position[right]", "lib/matplotlib/tests/test_axes.py::test_bar_label_location_vertical", "lib/matplotlib/tests/test_axes.py::test_bar_label_location_vertical_yinverted", "lib/matplotlib/tests/test_axes.py::test_bar_label_location_horizontal", "lib/matplotlib/tests/test_axes.py::test_bar_label_location_horizontal_yinverted", "lib/matplotlib/tests/test_axes.py::test_bar_label_location_horizontal_xinverted", "lib/matplotlib/tests/test_axes.py::test_bar_label_location_horizontal_xyinverted", "lib/matplotlib/tests/test_axes.py::test_bar_label_location_center", "lib/matplotlib/tests/test_axes.py::test_centered_bar_label_label_beyond_limits", "lib/matplotlib/tests/test_axes.py::test_bar_label_location_errorbars", "lib/matplotlib/tests/test_axes.py::test_bar_label_fmt[%.2f]", "lib/matplotlib/tests/test_axes.py::test_bar_label_fmt[{:.2f}]", "lib/matplotlib/tests/test_axes.py::test_bar_label_fmt[format]", "lib/matplotlib/tests/test_axes.py::test_bar_label_fmt_error", "lib/matplotlib/tests/test_axes.py::test_bar_label_labels", "lib/matplotlib/tests/test_axes.py::test_bar_label_nan_ydata", "lib/matplotlib/tests/test_axes.py::test_bar_label_nan_ydata_inverted", "lib/matplotlib/tests/test_axes.py::test_nan_barlabels", "lib/matplotlib/tests/test_axes.py::test_patch_bounds", "lib/matplotlib/tests/test_axes.py::test_warn_ignored_scatter_kwargs", "lib/matplotlib/tests/test_axes.py::test_artist_sublists", "lib/matplotlib/tests/test_axes.py::test_empty_line_plots", "lib/matplotlib/tests/test_axes.py::test_plot_format_errors[None-f-'f'", "lib/matplotlib/tests/test_axes.py::test_plot_format_errors[None-o+-'o\\\\+'", "lib/matplotlib/tests/test_axes.py::test_plot_format_errors[None-:--':-'", "lib/matplotlib/tests/test_axes.py::test_plot_format_errors[None-rk-'rk'", "lib/matplotlib/tests/test_axes.py::test_plot_format_errors[None-:o-r-':o-r'", "lib/matplotlib/tests/test_axes.py::test_plot_format_errors[data1-f-'f'", "lib/matplotlib/tests/test_axes.py::test_plot_format_errors[data1-o+-'o\\\\+'", "lib/matplotlib/tests/test_axes.py::test_plot_format_errors[data1-:--':-'", "lib/matplotlib/tests/test_axes.py::test_plot_format_errors[data1-rk-'rk'", "lib/matplotlib/tests/test_axes.py::test_plot_format_errors[data1-:o-r-':o-r'", "lib/matplotlib/tests/test_axes.py::test_plot_format", "lib/matplotlib/tests/test_axes.py::test_automatic_legend", "lib/matplotlib/tests/test_axes.py::test_plot_errors", "lib/matplotlib/tests/test_axes.py::test_clim", "lib/matplotlib/tests/test_axes.py::test_bezier_autoscale", "lib/matplotlib/tests/test_axes.py::test_small_autoscale", "lib/matplotlib/tests/test_axes.py::test_get_xticklabel", "lib/matplotlib/tests/test_axes.py::test_bar_leading_nan", "lib/matplotlib/tests/test_axes.py::test_bar_all_nan[png]", "lib/matplotlib/tests/test_axes.py::test_extent_units[png]", "lib/matplotlib/tests/test_axes.py::test_cla_clears_children_axes_and_fig", "lib/matplotlib/tests/test_axes.py::test_scatter_color_repr_error", "lib/matplotlib/tests/test_axes.py::test_zorder_and_explicit_rasterization", "lib/matplotlib/tests/test_axes.py::test_preset_clip_paths[png]", "lib/matplotlib/tests/test_axes.py::test_rc_axes_label_formatting", "lib/matplotlib/tests/test_axes.py::test_ecdf[png]", "lib/matplotlib/tests/test_axes.py::test_ecdf_invalid", "lib/matplotlib/tests/test_axes.py::test_fill_between_axes_limits", "lib/matplotlib/tests/test_axes.py::test_tick_param_labelfont", "lib/matplotlib/tests/test_axes.py::test_set_secondary_axis_color", "lib/matplotlib/tests/test_axes.py::test_xylim_changed_shared", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_invisible_axes[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_grid_off[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_invisible_ticks_axis[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_axis_positions[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_aspects[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_aspects_adjust_box[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_axes3d_repr", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_axes3d_primary_views[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_bar3d[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_bar3d_colors", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_bar3d_shaded[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_bar3d_notshaded[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_bar3d_lightsource", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_contour3d[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_contour3d_extend3d[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_contourf3d[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_contourf3d_fill[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_contourf3d_extend[png-both-levels0]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_contourf3d_extend[png-min-levels1]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_contourf3d_extend[png-max-levels2]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_tricontour[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_contour3d_1d_input", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_lines3d[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_plot_scalar[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_invalid_line_data", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_mixedsubplots[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_tight_layout_text[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_scatter3d[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_scatter3d_color[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_scatter3d_linewidth[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_scatter3d_linewidth_modification[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_scatter3d_modification[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_scatter3d_sorting[png-True]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_scatter3d_sorting[png-False]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_marker_draw_order_data_reversed[png--50]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_marker_draw_order_data_reversed[png-130]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_marker_draw_order_view_rotated[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_plot_3d_from_2d[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_surface3d[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_surface3d_label_offset_tick_position[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_surface3d_shaded[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_surface3d_masked[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_plot_surface_None_arg[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_surface3d_masked_strides[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_text3d[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_text3d_modification[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_trisurf3d[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_trisurf3d_shaded[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_wireframe3d[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_wireframe3dzerocstride[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_wireframe3dzerorstride[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_wireframe3dzerostrideraises", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_mixedsamplesraises", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_quiver3d[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_quiver3d_empty[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_quiver3d_masked[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_patch_modification", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_patch_collection_modification[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_poly3dcollection_verts_validation", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_poly3dcollection_closed[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_poly_collection_2d_to_3d_empty", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_poly3dcollection_alpha[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_add_collection3d_zs_array[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_add_collection3d_zs_scalar[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_axes3d_labelpad[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_axes3d_cla[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_axes3d_rotated[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_plotsurface_1d_raises", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_proj_transform", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_proj_axes_cube[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_proj_axes_cube_ortho[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_world", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_autoscale", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_unautoscale[True-x]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_unautoscale[True-y]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_unautoscale[True-z]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_unautoscale[False-x]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_unautoscale[False-y]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_unautoscale[False-z]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_unautoscale[None-x]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_unautoscale[None-y]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_unautoscale[None-z]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_axes3d_focal_length_checks", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_axes3d_focal_length[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_axes3d_ortho[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_axes3d_isometric[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_invalid_axes_limits[set_xlim3d-left-inf]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_invalid_axes_limits[set_xlim3d-left-nan]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_invalid_axes_limits[set_xlim3d-right-inf]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_invalid_axes_limits[set_xlim3d-right-nan]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_invalid_axes_limits[set_ylim3d-bottom-inf]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_invalid_axes_limits[set_ylim3d-bottom-nan]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_invalid_axes_limits[set_ylim3d-top-inf]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_invalid_axes_limits[set_ylim3d-top-nan]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_invalid_axes_limits[set_zlim3d-bottom-inf]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_invalid_axes_limits[set_zlim3d-bottom-nan]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_invalid_axes_limits[set_zlim3d-top-inf]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_invalid_axes_limits[set_zlim3d-top-nan]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::TestVoxels::test_simple[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::TestVoxels::test_edge_style[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::TestVoxels::test_named_colors[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::TestVoxels::test_rgb_data[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::TestVoxels::test_alpha[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::TestVoxels::test_xyz[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::TestVoxels::test_calling_conventions", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_line3d_set_get_data_3d", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_inverted[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_inverted_cla", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_ax3d_tickcolour", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_ticklabel_format[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_quiver3D_smoke[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_minor_ticks[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_errorbar3d_errorevery[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_errorbar3d[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_stem3d[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_equal_box_aspect[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_colorbar_pos", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_inverted_zaxis", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_set_zlim", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_shared_view[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_shared_axes_retick", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_pan", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_toolbar_zoom_pan[zoom-1-None-expected0]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_toolbar_zoom_pan[zoom-1-x-expected1]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_toolbar_zoom_pan[zoom-1-y-expected2]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_toolbar_zoom_pan[zoom-3-None-expected3]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_toolbar_zoom_pan[pan-1-None-expected4]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_toolbar_zoom_pan[pan-1-x-expected5]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_toolbar_zoom_pan[pan-1-y-expected6]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_scalarmap_update[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_subfigure_simple", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_computed_zorder[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_format_coord", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_get_axis_position", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_margins", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_margins_errors[ValueError-args0-kwargs0-margin", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_margins_errors[ValueError-args1-kwargs1-margin", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_margins_errors[ValueError-args2-kwargs2-margin", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_margins_errors[ValueError-args3-kwargs3-margin", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_margins_errors[ValueError-args4-kwargs4-margin", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_margins_errors[ValueError-args5-kwargs5-margin", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_margins_errors[TypeError-args6-kwargs6-Cannot", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_margins_errors[TypeError-args7-kwargs7-Cannot", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_margins_errors[TypeError-args8-kwargs8-Cannot", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_margins_errors[TypeError-args9-kwargs9-Must", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_text_3d[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_draw_single_lines_from_Nx1", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_pathpatch_3d[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_scatter_spiral[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_Poly3DCollection_get_facecolor", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_Poly3DCollection_get_edgecolor", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_view_init_vertical_axis[z-proj_expected0-axis_lines_expected0-tickdirs_expected0]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_view_init_vertical_axis[y-proj_expected1-axis_lines_expected1-tickdirs_expected1]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_view_init_vertical_axis[x-proj_expected2-axis_lines_expected2-tickdirs_expected2]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_arc_pathpatch[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_panecolor_rcparams[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_mutating_input_arrays_y_and_z[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_scatter_masked_color", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_surface3d_zsort_inf[png]", "lib/mpl_toolkits/mplot3d/tests/test_axes3d.py::test_Poly3DCollection_init_value_error" ]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> Added get_xmargin(), get_ymargin() and get_zmargin() and tests. ## PR summary Closes #26281 by adding `get_xmargin()`, `get_ymargin()` for` _AxesBase` and `get_zmargin()` for `Axes3D`, as well as tests for them. ## PR checklist <!-- Please mark any checkboxes that do not apply to this PR as [N/A].--> - [x] "closes #0000" is in the body of the PR description to [link the related issue](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) - [x] new and changed code is [tested](https://matplotlib.org/devdocs/devel/testing.html) - [N/A] *Plotting related* features are demonstrated in an [example](https://matplotlib.org/devdocs/devel/documenting_mpl.html#writing-examples-and-tutorials) - [ ] *New Features* and *API Changes* are noted with a [directive and release note](https://matplotlib.org/devdocs/devel/coding_guide.html#new-features-and-api-changes) - [ ] Documentation complies with [general](https://matplotlib.org/devdocs/devel/documenting_mpl.html#writing-rest-pages) and [docstring](https://matplotlib.org/devdocs/devel/documenting_mpl.html#writing-docstrings) guidelines <!-- Thank you so much for your PR! To help us review your contribution, please consider the following points: - A development guide is available at https://matplotlib.org/devdocs/devel/index.html. - Help with git and github is available at https://matplotlib.org/devdocs/devel/development_workflow.html - Create a separate branch for your changes and open the PR from this branch. Please avoid working on `main`. - The PR title should summarize the changes, for example "Raise ValueError on non-numeric input to set_xlim". Avoid non-descriptive titles such as "Addresses issue #8576". - The summary should provide at least 1-2 sentences describing the pull request in detail (Why is this change required? What problem does it solve?) and link to any relevant issues. - If you are contributing fixes to docstrings, please pay attention to https://matplotlib.org/stable/devel/documenting_mpl.html#formatting-conventions. In particular, note the difference between using single backquotes, double backquotes, and asterisks in the markup. We understand that PRs can sometimes be overwhelming, especially as the reviews start coming in. Please let us know if the reviews are unclear or the recommended next step seems overly demanding, if you would like help in addressing a reviewer's comments, or if you have been waiting too long to hear back on your PR. --> ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in lib/matplotlib/axes/_base.py] (definition of _AxesBase.get_xmargin:) def get_xmargin(self): """Retrieve autoscaling margin of the x-axis. .. versionadded:: 3.9 Returns ------- xmargin : float See Also -------- matplotlib.axes.Axes.set_xmargin""" (definition of _AxesBase.get_ymargin:) def get_ymargin(self): """Retrieve autoscaling margin of the y-axis. .. versionadded:: 3.9 Returns ------- ymargin : float See Also -------- matplotlib.axes.Axes.set_ymargin""" [end of new definitions in lib/matplotlib/axes/_base.py] [start of new definitions in lib/mpl_toolkits/mplot3d/axes3d.py] (definition of Axes3D.get_zmargin:) def get_zmargin(self): """Retrieve autoscaling margin of the z-axis. .. versionadded:: 3.9 Returns ------- zmargin : float See Also -------- mpl_toolkits.mplot3d.axes3d.Axes3D.set_zmargin""" [end of new definitions in lib/mpl_toolkits/mplot3d/axes3d.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
Here is the discussion in the issues of the pull request. <issues> [ENH]: Add get_xmargin, get_ymargin, get_zmargin axes methods ### Problem Currently, I think the only public API to retrieve the margins settings on an Axes is ax.margins(), which has a somewhat peculiar API (basically inherited from pyplot/matlab); adding get_xmargin/get_ymargin/get_zmargin Axes methods would be nice (there's already the corresponding setters). Bonus points for moving the private _xmargin/_ymargin/_zmargin to the Axis instances, adding Axis.{get,set}_margin, and using axis_method_wrapper, though I haven't checked it'll actually work. ### Proposed solution _No response_ ---------- Hi! Does zmargin exist? I couldn't find it -- both the public docs and the code in _base.py only have xmargin and ymargin. Am I missing something? It is in Axes3D. -------------------- </issues>
a4dca24d04f928a9e614db403c716237446140b2
conan-io__conan-14233
14,233
conan-io/conan
null
57c7049c758a685cdc02e870eb77617af5e45da6
2023-07-06T06:04:41Z
diff --git a/conan/tools/gnu/pkgconfigdeps.py b/conan/tools/gnu/pkgconfigdeps.py index e793711ee81..1aa86e9d472 100644 --- a/conan/tools/gnu/pkgconfigdeps.py +++ b/conan/tools/gnu/pkgconfigdeps.py @@ -1,12 +1,13 @@ import os +import re import textwrap from collections import namedtuple from jinja2 import Template, StrictUndefined +from conan.errors import ConanException from conan.internal import check_duplicated_generator from conan.tools.gnu.gnudeps_flags import GnuDepsFlags -from conan.errors import ConanException from conans.model.dependencies import get_transitive_requires from conans.util.files import save @@ -75,8 +76,8 @@ def _get_suffix(req, build_context_suffix=None): return build_context_suffix.get(req.ref.name, "") -def _get_formatted_dirs(folders, prefix_path_): - ret = [] +def _get_formatted_dirs(folder_name, folders, prefix_path_): + ret = {} for i, directory in enumerate(folders): directory = os.path.normpath(directory).replace("\\", "/") prefix = "" @@ -85,7 +86,9 @@ def _get_formatted_dirs(folders, prefix_path_): elif directory.startswith(prefix_path_): prefix = "${prefix}/" directory = os.path.relpath(directory, prefix_path_).replace("\\", "/") - ret.append("%s%s" % (prefix, directory)) + suffix = str(i) if i else "" + var_name = f"{folder_name}{suffix}" + ret[var_name] = f"{prefix}{directory}" return ret @@ -95,71 +98,19 @@ def _get_formatted_dirs(folders, prefix_path_): class _PCContentGenerator: template = textwrap.dedent("""\ - {%- macro get_libs(libdirs, cpp_info, gnudeps_flags) -%} - {%- for _ in libdirs -%} - {{ '-L"${libdir%s}"' % (loop.index0 or "") + " " }} - {%- endfor -%} - {%- for sys_lib in (cpp_info.libs + cpp_info.system_libs) -%} - {{ "-l%s" % sys_lib + " " }} - {%- endfor -%} - {%- for shared_flag in (cpp_info.sharedlinkflags + cpp_info.exelinkflags) -%} - {{ shared_flag + " " }} - {%- endfor -%} - {%- for framework in (gnudeps_flags.frameworks + gnudeps_flags.framework_paths) -%} - {{ framework + " " }} - {%- endfor -%} - {%- endmacro -%} - - {%- macro get_cflags(includedirs, cxxflags, cflags, defines) -%} - {%- for _ in includedirs -%} - {{ '-I"${includedir%s}"' % (loop.index0 or "") + " " }} - {%- endfor -%} - {%- for cxxflag in cxxflags -%} - {{ cxxflag + " " }} - {%- endfor -%} - {%- for cflag in cflags-%} - {{ cflag + " " }} - {%- endfor -%} - {%- for define in defines-%} - {{ "-D%s" % define + " " }} - {%- endfor -%} - {%- endmacro -%} - - prefix={{ prefix_path }} - {% for path in libdirs %} - {{ "libdir{}={}".format((loop.index0 or ""), path) }} - {% endfor %} - {% for path in includedirs %} - {{ "includedir%s=%s" % ((loop.index0 or ""), path) }} - {% endfor %} - {% for path in bindirs %} - {{ "bindir{}={}".format((loop.index0 or ""), path) }} + {% for k, v in pc_variables.items() %} + {{ "{}={}".format(k, v) }} {% endfor %} - {% if pkg_config_custom_content %} - # Custom PC content - {{ pkg_config_custom_content }} - {% endif %} Name: {{ name }} Description: {{ description }} Version: {{ version }} - Libs: {{ get_libs(libdirs, cpp_info, gnudeps_flags) }} - Cflags: {{ get_cflags(includedirs, cxxflags, cflags, defines) }} - {% if requires|length %} - Requires: {{ requires|join(' ') }} + {% if libflags %} + Libs: {{ libflags }} {% endif %} - """) - - shortened_template = textwrap.dedent("""\ - prefix={{ prefix_path }} - {% if pkg_config_custom_content %} - # Custom PC content - {{ pkg_config_custom_content }} + {% if cflags %} + Cflags: {{ cflags }} {% endif %} - - Name: {{ name }} - Description: {{ description }} - Version: {{ version }} {% if requires|length %} Requires: {{ requires|join(' ') }} {% endif %} @@ -175,50 +126,74 @@ def _get_prefix_path(self): else self._dep.package_folder return root_folder.replace("\\", "/") - def content(self, info): - assert isinstance(info, _PCInfo) and info.cpp_info is not None - + def _get_pc_variables(self, cpp_info): + """ + Get all the freeform variables defined by Conan and + users (through ``pkg_config_custom_content``). This last ones will override the + Conan defined variables. + """ prefix_path = self._get_prefix_path() - version = info.cpp_info.get_property("component_version") or self._dep.ref.version - libdirs = _get_formatted_dirs(info.cpp_info.libdirs, prefix_path) - includedirs = _get_formatted_dirs(info.cpp_info.includedirs, prefix_path) - bindirs = _get_formatted_dirs(info.cpp_info.bindirs, prefix_path) - custom_content = info.cpp_info.get_property("pkg_config_custom_content") - + pc_variables = {"prefix": prefix_path} + if cpp_info is None: + return pc_variables + # Already formatted directories + pc_variables.update(_get_formatted_dirs("libdir", cpp_info.libdirs, prefix_path)) + pc_variables.update(_get_formatted_dirs("includedir", cpp_info.includedirs, prefix_path)) + pc_variables.update(_get_formatted_dirs("bindir", cpp_info.bindirs, prefix_path)) + # Get the custom content introduced by user and sanitize it + custom_content = cpp_info.get_property("pkg_config_custom_content") + if isinstance(custom_content, dict): + pc_variables.update(custom_content) + elif custom_content: # Legacy: custom content is string + pc_variable_pattern = re.compile("^(.*)=(.*)") + for line in custom_content.splitlines(): + match = pc_variable_pattern.match(line) + if match: + key, value = match.group(1).strip(), match.group(2).strip() + pc_variables[key] = value + return pc_variables + + def _get_lib_flags(self, libdirvars, cpp_info): + gnudeps_flags = GnuDepsFlags(self._conanfile, cpp_info) + libdirsflags = ['-L"${%s}"' % d for d in libdirvars] + system_libs = ["-l%s" % l for l in (cpp_info.libs + cpp_info.system_libs)] + shared_flags = cpp_info.sharedlinkflags + cpp_info.exelinkflags + framework_flags = gnudeps_flags.frameworks + gnudeps_flags.framework_paths + return " ".join(libdirsflags + system_libs + shared_flags + framework_flags) + + def _get_cflags(self, includedirvars, cpp_info): + includedirsflags = ['-I"${%s}"' % d for d in includedirvars] + cxxflags = [var.replace('"', '\\"') for var in cpp_info.cxxflags] + cflags = [var.replace('"', '\\"') for var in cpp_info.cflags] + defines = ["-D%s" % var.replace('"', '\\"') for var in cpp_info.defines] + return " ".join(includedirsflags + cxxflags + cflags + defines) + + def _get_context(self, info): + pc_variables = self._get_pc_variables(info.cpp_info) context = { - "prefix_path": prefix_path, - "libdirs": libdirs, - "includedirs": includedirs, - "bindirs": bindirs, - "pkg_config_custom_content": custom_content, "name": info.name, "description": info.description, - "version": version, + "version": self._dep.ref.version, "requires": info.requires, - "cpp_info": info.cpp_info, - "cxxflags": [var.replace('"', '\\"') for var in info.cpp_info.cxxflags], - "cflags": [var.replace('"', '\\"') for var in info.cpp_info.cflags], - "defines": [var.replace('"', '\\"') for var in info.cpp_info.defines], - "gnudeps_flags": GnuDepsFlags(self._conanfile, info.cpp_info) + "pc_variables": pc_variables, + "cflags": "", + "libflags": "" } - template = Template(self.template, trim_blocks=True, lstrip_blocks=True, - undefined=StrictUndefined) - return template.render(context) + if info.cpp_info is not None: + context.update({ + "version": info.cpp_info.get_property("component_version") or self._dep.ref.version, + "cflags": self._get_cflags([d for d in pc_variables if d.startswith("includedir")], + info.cpp_info), + "libflags": self._get_lib_flags([d for d in pc_variables if d.startswith("libdir")], + info.cpp_info) + }) + return context - def shortened_content(self, info): + def content(self, info): assert isinstance(info, _PCInfo) - custom_content = info.cpp_info.get_property("pkg_config_custom_content") if info.cpp_info \ - else None - context = { - "prefix_path": self._get_prefix_path(), - "pkg_config_custom_content": custom_content, - "name": info.name, - "description": info.description, - "version": self._dep.ref.version, - "requires": info.requires - } - template = Template(self.shortened_template, trim_blocks=True, - lstrip_blocks=True, undefined=StrictUndefined) + context = self._get_context(info) + template = Template(self.template, trim_blocks=True, lstrip_blocks=True, + undefined=StrictUndefined) return template.render(context) @@ -340,7 +315,7 @@ def _update_pc_files(info): pc_files[f"{info.name}.pc"] = self._content_generator.content(info) for alias in info.aliases: alias_info = _PCInfo(alias, [info.name], f"Alias {alias} for {info.name}", None, []) - pc_files[f"{alias}.pc"] = self._content_generator.shortened_content(alias_info) + pc_files[f"{alias}.pc"] = self._content_generator.content(alias_info) pc_files = {} # If the package has no components, then we have to calculate only the root pc file @@ -365,11 +340,11 @@ def _update_pc_files(info): package_info = _PCInfo(pkg_name, pkg_requires, f"Conan package: {pkg_name}", self._dep.cpp_info, _get_package_aliases(self._dep)) # It'll be enough creating a shortened PC file. This file will be like an alias - pc_files[f"{package_info.name}.pc"] = self._content_generator.shortened_content(package_info) + pc_files[f"{package_info.name}.pc"] = self._content_generator.content(package_info) for alias in package_info.aliases: alias_info = _PCInfo(alias, [package_info.name], f"Alias {alias} for {package_info.name}", None, []) - pc_files[f"{alias}.pc"] = self._content_generator.shortened_content(alias_info) + pc_files[f"{alias}.pc"] = self._content_generator.content(alias_info) return pc_files
diff --git a/conans/test/integration/toolchains/gnu/test_pkgconfigdeps.py b/conans/test/integration/toolchains/gnu/test_pkgconfigdeps.py index e211bd6e889..fb6bc02c644 100644 --- a/conans/test/integration/toolchains/gnu/test_pkgconfigdeps.py +++ b/conans/test/integration/toolchains/gnu/test_pkgconfigdeps.py @@ -94,9 +94,7 @@ def package_info(self): expected = textwrap.dedent(""" Name: mylib Description: Conan package: mylib - Version: 0.1 - Libs:%s - Cflags: """ % " ") # ugly hack for trailing whitespace removed by IDEs + Version: 0.1""") assert "\n".join(pc_content.splitlines()[1:]) == expected @@ -173,9 +171,10 @@ def package(self): def package_info(self): custom_content = textwrap.dedent(\""" + bindir=${prefix}/my/bin/folder + fakelibdir=${prefix}/my/lib/folder datadir=${prefix}/share schemasdir=${datadir}/mylib/schemas - bindir=${prefix}/bin \""") self.cpp_info.set_property("pkg_config_custom_content", custom_content) self.cpp_info.includedirs = ["include"] @@ -187,11 +186,23 @@ def package_info(self): client.run("install --requires=pkg/0.1@ -g PkgConfigDeps") pc_content = client.load("pkg.pc") - assert "libdir=${prefix}/lib" in pc_content - assert "datadir=${prefix}/share" in pc_content - assert "schemasdir=${datadir}/mylib/schemas" in pc_content - assert "bindir=${prefix}/bin" in pc_content - assert "Name: pkg" in pc_content + prefix = pc_content.splitlines()[0] + expected = textwrap.dedent(f"""\ + {prefix} + libdir=${{prefix}}/lib + includedir=${{prefix}}/include + bindir=${{prefix}}/my/bin/folder + fakelibdir=${{prefix}}/my/lib/folder + datadir=${{prefix}}/share + schemasdir=${{datadir}}/mylib/schemas + + Name: pkg + Description: Conan package: pkg + Version: 0.1 + Libs: -L"${{libdir}}" + Cflags: -I"${{includedir}}" + """) + assert expected == pc_content def test_custom_content_and_version_components(): @@ -446,15 +457,17 @@ def package_info(self): pc_content = client.load("pkg_other_name.pc") content = textwrap.dedent(f"""\ {prefix} - # Custom PC content - + libdir=${{prefix}}/lib + includedir=${{prefix}}/include + bindir=${{prefix}}/bin datadir=${{prefix}}/share schemasdir=${{datadir}}/mylib/schemas - Name: pkg_other_name Description: Conan package: pkg_other_name Version: 0.3 + Libs: -L"${{libdir}}" + Cflags: -I"${{includedir}}" Requires: compo1 """) assert content == pc_content
[ { "components": [ { "doc": "Get all the freeform variables defined by Conan and\nusers (through ``pkg_config_custom_content``). This last ones will override the\nConan defined variables.", "lines": [ 129, 154 ], "name": "_PCContentGenerator._get_pc_variables", "signature": "def _get_pc_variables(self, cpp_info):", "type": "function" }, { "doc": "", "lines": [ 156, 162 ], "name": "_PCContentGenerator._get_lib_flags", "signature": "def _get_lib_flags(self, libdirvars, cpp_info):", "type": "function" }, { "doc": "", "lines": [ 164, 169 ], "name": "_PCContentGenerator._get_cflags", "signature": "def _get_cflags(self, includedirvars, cpp_info):", "type": "function" }, { "doc": "", "lines": [ 171, 190 ], "name": "_PCContentGenerator._get_context", "signature": "def _get_context(self, info):", "type": "function" } ], "file": "conan/tools/gnu/pkgconfigdeps.py" } ]
[ "conans/test/integration/toolchains/gnu/test_pkgconfigdeps.py::test_empty_dirs", "conans/test/integration/toolchains/gnu/test_pkgconfigdeps.py::test_custom_content", "conans/test/integration/toolchains/gnu/test_pkgconfigdeps.py::test_pkg_config_name_full_aliases" ]
[ "conans/test/integration/toolchains/gnu/test_pkgconfigdeps.py::test_pkg_config_dirs", "conans/test/integration/toolchains/gnu/test_pkgconfigdeps.py::test_system_libs", "conans/test/integration/toolchains/gnu/test_pkgconfigdeps.py::test_multiple_include", "conans/test/integration/toolchains/gnu/test_pkgconfigdeps.py::test_custom_content_and_version_components", "conans/test/integration/toolchains/gnu/test_pkgconfigdeps.py::test_pkg_with_public_deps_and_component_requires", "conans/test/integration/toolchains/gnu/test_pkgconfigdeps.py::test_pkg_with_public_deps_and_component_requires_2", "conans/test/integration/toolchains/gnu/test_pkgconfigdeps.py::test_components_and_package_pc_creation_order", "conans/test/integration/toolchains/gnu/test_pkgconfigdeps.py::test_pkgconfigdeps_with_test_requires", "conans/test/integration/toolchains/gnu/test_pkgconfigdeps.py::test_with_editable_layout", "conans/test/integration/toolchains/gnu/test_pkgconfigdeps.py::test_tool_requires", "conans/test/integration/toolchains/gnu/test_pkgconfigdeps.py::test_tool_requires_not_created_if_no_activated", "conans/test/integration/toolchains/gnu/test_pkgconfigdeps.py::test_tool_requires_raise_exception_if_exist_both_require_and_build_one", "conans/test/integration/toolchains/gnu/test_pkgconfigdeps.py::test_error_missing_pc_build_context" ]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> [PkgConfigDeps] `pkg_config_custom_content` property overwrites variables Changelog: Feature: Let `pkg_config_custom_content` overwrite default `*.pc` variables created by `PkgConfigDeps`. Changelog: Feature: Let `pkg_config_custom_content` be a dict-like object too. Docs: https://github.com/conan-io/docs/pull/3293 UPDATED: * Simplified internal `PkgConfigDeps` logic: only one template and more straightforward, one context, Python is formatting the template, etc. * `pkg_config_custom_content` overwrites Conan-defined freeform variables, not keyword metadata ones. * `pkg_config_custom_content` could be defined as a dictionary instead of a string. ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in conan/tools/gnu/pkgconfigdeps.py] (definition of _PCContentGenerator._get_pc_variables:) def _get_pc_variables(self, cpp_info): """Get all the freeform variables defined by Conan and users (through ``pkg_config_custom_content``). This last ones will override the Conan defined variables.""" (definition of _PCContentGenerator._get_lib_flags:) def _get_lib_flags(self, libdirvars, cpp_info): (definition of _PCContentGenerator._get_cflags:) def _get_cflags(self, includedirvars, cpp_info): (definition of _PCContentGenerator._get_context:) def _get_context(self, info): [end of new definitions in conan/tools/gnu/pkgconfigdeps.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
4a5b19a75db9225316c8cb022a2dfb9705a2af34
astropy__astropy-14878
14,878
astropy/astropy
5.2
88790514bdf248e43c2fb15ee18cfd3390846145
2023-05-29T22:12:40Z
diff --git a/astropy/table/row.py b/astropy/table/row.py index 03b7d13219b9..cab570e837c6 100644 --- a/astropy/table/row.py +++ b/astropy/table/row.py @@ -106,6 +106,35 @@ def __iter__(self): for col in self._table.columns.values(): yield col[index] + def get(self, key, default=None, /): + """Return the value for key if key is in the columns, else default. + + Parameters + ---------- + key : `str`, positional-only + The name of the column to look for. + default : `object`, optional, positional-only + The value to return if the ``key`` is not among the columns. + + Returns + ------- + `object` + The value in the ``key`` column of the row if present, + ``default`` otherwise. + + Examples + -------- + >>> from astropy.table import Table + >>> t = Table({"a": [2, 3, 5], "b": [7, 11, 13]}) + >>> t[0].get("a") + 2 + >>> t[1].get("b", 0) + 11 + >>> t[2].get("c", 0) + 0 + """ + return self[key] if key in self._table.columns else default + def keys(self): return self._table.columns.keys() diff --git a/docs/changes/table/14878.feature.rst b/docs/changes/table/14878.feature.rst new file mode 100644 index 000000000000..768574409629 --- /dev/null +++ b/docs/changes/table/14878.feature.rst @@ -0,0 +1,3 @@ +The new ``Row.get()`` method, analogous to ``dict.get()``, returns the value of +the specified column from the row if the column present, otherwise it returns a +fallback value, which by default is ``None``. diff --git a/docs/table/access_table.rst b/docs/table/access_table.rst index 24d0f561cab2..263ecafc9713 100644 --- a/docs/table/access_table.rst +++ b/docs/table/access_table.rst @@ -315,6 +315,36 @@ structured array by creating a copy or reference with :func:`numpy.array`:: >>> data = np.array(t, copy=False) # reference to data in t +Possibly missing columns +^^^^^^^^^^^^^^^^^^^^^^^^ + +In some cases it might not be guaranteed that a column is present in a table, +but there does exist a good default value that can be used if it is not. The +columns of a |Table| can be represented as a :class:`dict` subclass instance +through the ``columns`` attribute, which means that a replacement for missing +columns can be provided using the :meth:`dict.get` method:: + + >>> t.columns.get("b", np.zeros(len(t))) + <Column name='b' dtype='int32' length=5> + 1 + 4 + 7 + 10 + 13 + >>> t.columns.get("x", np.zeros(len(t))) + array([0., 0., 0., 0., 0.]) + +In case of a single |Row| it is possible to use its +:meth:`~astropy.table.Row.get` method without having to go through +``columns``:: + + >>> row = t[2] + >>> row.get("c", -1) + 8 + >>> row.get("y", -1) + -1 + + Table Equality --------------
diff --git a/astropy/table/tests/test_row.py b/astropy/table/tests/test_row.py index 8ad9f46ba80b..6af2f945a8e7 100644 --- a/astropy/table/tests/test_row.py +++ b/astropy/table/tests/test_row.py @@ -372,3 +372,11 @@ def test_uint_indexing(): assert repr(t[1]).splitlines() == trepr assert repr(t[np.int_(1)]).splitlines() == trepr assert repr(t[np.uint(1)]).splitlines() == trepr + + +def test_row_get(): + row = table.Table({"a": [2, 4], "b": [3, 9]})[0] + assert row.get("a") == 2 + assert row.get("x") is None + assert row.get("b", -1) == 3 + assert row.get("y", -1) == -1
diff --git a/docs/changes/table/14878.feature.rst b/docs/changes/table/14878.feature.rst new file mode 100644 index 000000000000..768574409629 --- /dev/null +++ b/docs/changes/table/14878.feature.rst @@ -0,0 +1,3 @@ +The new ``Row.get()`` method, analogous to ``dict.get()``, returns the value of +the specified column from the row if the column present, otherwise it returns a +fallback value, which by default is ``None``. diff --git a/docs/table/access_table.rst b/docs/table/access_table.rst index 24d0f561cab2..263ecafc9713 100644 --- a/docs/table/access_table.rst +++ b/docs/table/access_table.rst @@ -315,6 +315,36 @@ structured array by creating a copy or reference with :func:`numpy.array`:: >>> data = np.array(t, copy=False) # reference to data in t +Possibly missing columns +^^^^^^^^^^^^^^^^^^^^^^^^ + +In some cases it might not be guaranteed that a column is present in a table, +but there does exist a good default value that can be used if it is not. The +columns of a |Table| can be represented as a :class:`dict` subclass instance +through the ``columns`` attribute, which means that a replacement for missing +columns can be provided using the :meth:`dict.get` method:: + + >>> t.columns.get("b", np.zeros(len(t))) + <Column name='b' dtype='int32' length=5> + 1 + 4 + 7 + 10 + 13 + >>> t.columns.get("x", np.zeros(len(t))) + array([0., 0., 0., 0., 0.]) + +In case of a single |Row| it is possible to use its +:meth:`~astropy.table.Row.get` method without having to go through +``columns``:: + + >>> row = t[2] + >>> row.get("c", -1) + 8 + >>> row.get("y", -1) + -1 + + Table Equality --------------
[ { "components": [ { "doc": "Return the value for key if key is in the columns, else default.\n\nParameters\n----------\nkey : `str`, positional-only\n The name of the column to look for.\ndefault : `object`, optional, positional-only\n The value to return if the ``key`` is not among the columns.\n\nReturns\n-------\n`object`\n The value in the ``key`` column of the row if present,\n ``default`` otherwise.\n\nExamples\n--------\n>>> from astropy.table import Table\n>>> t = Table({\"a\": [2, 3, 5], \"b\": [7, 11, 13]})\n>>> t[0].get(\"a\")\n2\n>>> t[1].get(\"b\", 0)\n11\n>>> t[2].get(\"c\", 0)\n0", "lines": [ 109, 136 ], "name": "Row.get", "signature": "def get(self, key, default=None, /):", "type": "function" } ], "file": "astropy/table/row.py" } ]
[ "astropy/table/tests/test_row.py::test_row_get" ]
[ "astropy/table/tests/test_row.py::test_masked_row_with_object_col", "astropy/table/tests/test_row.py::TestRow::test_subclass[unmasked]", "astropy/table/tests/test_row.py::TestRow::test_subclass[masked]", "astropy/table/tests/test_row.py::TestRow::test_subclass[subclass]", "astropy/table/tests/test_row.py::TestRow::test_values[unmasked]", "astropy/table/tests/test_row.py::TestRow::test_values[masked]", "astropy/table/tests/test_row.py::TestRow::test_values[subclass]", "astropy/table/tests/test_row.py::TestRow::test_ref[unmasked]", "astropy/table/tests/test_row.py::TestRow::test_ref[masked]", "astropy/table/tests/test_row.py::TestRow::test_ref[subclass]", "astropy/table/tests/test_row.py::TestRow::test_left_equal[unmasked]", "astropy/table/tests/test_row.py::TestRow::test_left_equal[masked]", "astropy/table/tests/test_row.py::TestRow::test_left_equal[subclass]", "astropy/table/tests/test_row.py::TestRow::test_left_not_equal[unmasked]", "astropy/table/tests/test_row.py::TestRow::test_left_not_equal[masked]", "astropy/table/tests/test_row.py::TestRow::test_left_not_equal[subclass]", "astropy/table/tests/test_row.py::TestRow::test_right_equal[unmasked]", "astropy/table/tests/test_row.py::TestRow::test_right_equal[masked]", "astropy/table/tests/test_row.py::TestRow::test_right_equal[subclass]", "astropy/table/tests/test_row.py::TestRow::test_convert_numpy_array[unmasked]", "astropy/table/tests/test_row.py::TestRow::test_convert_numpy_array[masked]", "astropy/table/tests/test_row.py::TestRow::test_convert_numpy_array[subclass]", "astropy/table/tests/test_row.py::TestRow::test_format_row[unmasked]", "astropy/table/tests/test_row.py::TestRow::test_format_row[masked]", "astropy/table/tests/test_row.py::TestRow::test_format_row[subclass]", "astropy/table/tests/test_row.py::TestRow::test_as_void[unmasked]", "astropy/table/tests/test_row.py::TestRow::test_as_void[masked]", "astropy/table/tests/test_row.py::TestRow::test_as_void[subclass]", "astropy/table/tests/test_row.py::TestRow::test_row_and_as_void_with_objects[unmasked]", "astropy/table/tests/test_row.py::TestRow::test_row_and_as_void_with_objects[masked]", "astropy/table/tests/test_row.py::TestRow::test_row_and_as_void_with_objects[subclass]", "astropy/table/tests/test_row.py::TestRow::test_bounds_checking[unmasked]", "astropy/table/tests/test_row.py::TestRow::test_bounds_checking[masked]", "astropy/table/tests/test_row.py::TestRow::test_bounds_checking[subclass]", "astropy/table/tests/test_row.py::TestRow::test_create_rows_from_list[unmasked]", "astropy/table/tests/test_row.py::TestRow::test_create_rows_from_list[masked]", "astropy/table/tests/test_row.py::TestRow::test_create_rows_from_list[subclass]", "astropy/table/tests/test_row.py::TestRow::test_row_keys_values[unmasked]", "astropy/table/tests/test_row.py::TestRow::test_row_keys_values[masked]", "astropy/table/tests/test_row.py::TestRow::test_row_keys_values[subclass]", "astropy/table/tests/test_row.py::TestRow::test_row_as_mapping[unmasked]", "astropy/table/tests/test_row.py::TestRow::test_row_as_mapping[masked]", "astropy/table/tests/test_row.py::TestRow::test_row_as_mapping[subclass]", "astropy/table/tests/test_row.py::TestRow::test_row_as_sequence[unmasked]", "astropy/table/tests/test_row.py::TestRow::test_row_as_sequence[masked]", "astropy/table/tests/test_row.py::TestRow::test_row_as_sequence[subclass]", "astropy/table/tests/test_row.py::test_row_tuple_column_slice", "astropy/table/tests/test_row.py::test_row_tuple_column_slice_transaction", "astropy/table/tests/test_row.py::test_uint_indexing" ]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> Implement `astropy.table.Row.get()` ### Description Currently code that tries to access a column in a `Row` when the presence of the column is not guaranteed either has to check for the presence of the column beforehand or handle the resulting `KeyError` explicitly. In many cases (see e.g. https://github.com/astropy/astropy/pull/14780#discussion_r1200857265) it might be appealing to use `Row.columns.get()` instead, which allows specifying a fallback value to be used if the column is not present, but (surprisingly) `Row.columns` actually returns the `columns` from the parent table of the `Row`: https://github.com/astropy/astropy/blob/88790514bdf248e43c2fb15ee18cfd3390846145/astropy/table/row.py#L152-L154 Changing the behavior of `Row.columns` would be a backwards-incompatible change, so it is safer to implement a new `Row.get()` method. ~~When implementing the unit tests for the new feature I thought that it would be better if the test table would be a module level fixture so that it would not be recreated for every instance of the parametrized tests, and then I found it useful to share the test table with an already existing test so that it could be reused even more. Because of this I also refactored and parametrized an already existing unit test for `Row`.~~ ---------- I had to force-push the second commit because an issue and a pull request were opened while I was writing the opening message, so I had to update the change log entry filename to match the actual pull request number. From the sidelines: Definitely happy with making `Row` a bit more `dict`-like. I was wondering if `Table` should similarly get a `get` method, but I guess having to pass in a default column makes less sense. </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in astropy/table/row.py] (definition of Row.get:) def get(self, key, default=None, /): """Return the value for key if key is in the columns, else default. Parameters ---------- key : `str`, positional-only The name of the column to look for. default : `object`, optional, positional-only The value to return if the ``key`` is not among the columns. Returns ------- `object` The value in the ``key`` column of the row if present, ``default`` otherwise. Examples -------- >>> from astropy.table import Table >>> t = Table({"a": [2, 3, 5], "b": [7, 11, 13]}) >>> t[0].get("a") 2 >>> t[1].get("b", 0) 11 >>> t[2].get("c", 0) 0""" [end of new definitions in astropy/table/row.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
32bd0ffb6898c6a57b9ec1a55c13c7a0efe8d273
graphql-python__graphene-1506
1,506
graphql-python/graphene
null
8ede21e06381c096589c424960a6cfaca304badb
2023-05-29T18:07:14Z
diff --git a/graphene/types/inputobjecttype.py b/graphene/types/inputobjecttype.py index 5d2785105..fdf38ba05 100644 --- a/graphene/types/inputobjecttype.py +++ b/graphene/types/inputobjecttype.py @@ -14,6 +14,31 @@ class InputObjectTypeOptions(BaseOptions): container = None # type: InputObjectTypeContainer +# Currently in Graphene, we get a `None` whenever we access an (optional) field that was not set in an InputObjectType +# using the InputObjectType.<attribute> dot access syntax. This is ambiguous, because in this current (Graphene +# historical) arrangement, we cannot distinguish between a field not being set and a field being set to None. +# At the same time, we shouldn't break existing code that expects a `None` when accessing a field that was not set. +_INPUT_OBJECT_TYPE_DEFAULT_VALUE = None + +# To mitigate this, we provide the function `set_input_object_type_default_value` to allow users to change the default +# value returned in non-specified fields in InputObjectType to another meaningful sentinel value (e.g. Undefined) +# if they want to. This way, we can keep code that expects a `None` working while we figure out a better solution (or +# a well-documented breaking change) for this issue. + + +def set_input_object_type_default_value(default_value): + """ + Change the sentinel value returned by non-specified fields in an InputObjectType + Useful to differentiate between a field not being set and a field being set to None by using a sentinel value + (e.g. Undefined is a good sentinel value for this purpose) + + This function should be called at the beginning of the app or in some other place where it is guaranteed to + be called before any InputObjectType is defined. + """ + global _INPUT_OBJECT_TYPE_DEFAULT_VALUE + _INPUT_OBJECT_TYPE_DEFAULT_VALUE = default_value + + class InputObjectTypeContainer(dict, BaseType): # type: ignore class Meta: abstract = True @@ -21,7 +46,7 @@ class Meta: def __init__(self, *args, **kwargs): dict.__init__(self, *args, **kwargs) for key in self._meta.fields: - setattr(self, key, self.get(key, None)) + setattr(self, key, self.get(key, _INPUT_OBJECT_TYPE_DEFAULT_VALUE)) def __init_subclass__(cls, *args, **kwargs): pass diff --git a/graphene/validation/depth_limit.py b/graphene/validation/depth_limit.py index b4599e660..e0f286634 100644 --- a/graphene/validation/depth_limit.py +++ b/graphene/validation/depth_limit.py @@ -30,7 +30,7 @@ except ImportError: # backwards compatibility for v3.6 from typing import Pattern -from typing import Callable, Dict, List, Optional, Union +from typing import Callable, Dict, List, Optional, Union, Tuple from graphql import GraphQLError from graphql.validation import ValidationContext, ValidationRule @@ -82,7 +82,7 @@ def __init__(self, validation_context: ValidationContext): def get_fragments( - definitions: List[DefinitionNode], + definitions: Tuple[DefinitionNode, ...], ) -> Dict[str, FragmentDefinitionNode]: fragments = {} for definition in definitions: @@ -94,7 +94,7 @@ def get_fragments( # This will actually get both queries and mutations. # We can basically treat those the same def get_queries_and_mutations( - definitions: List[DefinitionNode], + definitions: Tuple[DefinitionNode, ...], ) -> Dict[str, OperationDefinitionNode]: operations = {}
diff --git a/graphene/types/tests/conftest.py b/graphene/types/tests/conftest.py new file mode 100644 index 000000000..43f7d7268 --- /dev/null +++ b/graphene/types/tests/conftest.py @@ -0,0 +1,12 @@ +import pytest +from graphql import Undefined + +from graphene.types.inputobjecttype import set_input_object_type_default_value + + +@pytest.fixture() +def set_default_input_object_type_to_undefined(): + """This fixture is used to change the default value of optional inputs in InputObjectTypes for specific tests""" + set_input_object_type_default_value(Undefined) + yield + set_input_object_type_default_value(None) diff --git a/graphene/types/tests/test_inputobjecttype.py b/graphene/types/tests/test_inputobjecttype.py index 0fb7e3945..0d7bcf80c 100644 --- a/graphene/types/tests/test_inputobjecttype.py +++ b/graphene/types/tests/test_inputobjecttype.py @@ -1,3 +1,5 @@ +from graphql import Undefined + from ..argument import Argument from ..field import Field from ..inputfield import InputField @@ -6,6 +8,7 @@ from ..scalars import Boolean, String from ..schema import Schema from ..unmountedtype import UnmountedType +from ... import NonNull class MyType: @@ -136,3 +139,31 @@ def resolve_is_child(self, info, parent): assert not result.errors assert result.data == {"isChild": True} + + +def test_inputobjecttype_default_input_as_undefined( + set_default_input_object_type_to_undefined, +): + class TestUndefinedInput(InputObjectType): + required_field = String(required=True) + optional_field = String() + + class Query(ObjectType): + undefined_optionals_work = Field(NonNull(Boolean), input=TestUndefinedInput()) + + def resolve_undefined_optionals_work(self, info, input: TestUndefinedInput): + # Confirm that optional_field comes as Undefined + return ( + input.required_field == "required" and input.optional_field is Undefined + ) + + schema = Schema(query=Query) + result = schema.execute( + """query basequery { + undefinedOptionalsWork(input: {requiredField: "required"}) + } + """ + ) + + assert not result.errors + assert result.data == {"undefinedOptionalsWork": True} diff --git a/graphene/types/tests/test_type_map.py b/graphene/types/tests/test_type_map.py index 55b1706e0..55665b6b8 100644 --- a/graphene/types/tests/test_type_map.py +++ b/graphene/types/tests/test_type_map.py @@ -20,8 +20,8 @@ from ..interface import Interface from ..objecttype import ObjectType from ..scalars import Int, String -from ..structures import List, NonNull from ..schema import Schema +from ..structures import List, NonNull def create_type_map(types, auto_camelcase=True): @@ -227,6 +227,18 @@ def resolve_foo_bar(self, args, info): assert foo_field.description == "Field description" +def test_inputobject_undefined(set_default_input_object_type_to_undefined): + class OtherObjectType(InputObjectType): + optional_field = String() + + type_map = create_type_map([OtherObjectType]) + assert "OtherObjectType" in type_map + graphql_type = type_map["OtherObjectType"] + + container = graphql_type.out_type({}) + assert container.optional_field is Undefined + + def test_objecttype_camelcase(): class MyObjectType(ObjectType): """Description"""
[ { "components": [ { "doc": "Change the sentinel value returned by non-specified fields in an InputObjectType\nUseful to differentiate between a field not being set and a field being set to None by using a sentinel value\n(e.g. Undefined is a good sentinel value for this purpose)\n\nThis function should be called at the beginning of the app or in some other place where it is guaranteed to\nbe called before any InputObjectType is defined.", "lines": [ 29, 39 ], "name": "set_input_object_type_default_value", "signature": "def set_input_object_type_default_value(default_value):", "type": "function" } ], "file": "graphene/types/inputobjecttype.py" } ]
[ "graphene/types/tests/test_inputobjecttype.py::test_generate_inputobjecttype", "graphene/types/tests/test_inputobjecttype.py::test_generate_inputobjecttype_with_meta", "graphene/types/tests/test_inputobjecttype.py::test_generate_inputobjecttype_with_fields", "graphene/types/tests/test_inputobjecttype.py::test_ordered_fields_in_inputobjecttype", "graphene/types/tests/test_inputobjecttype.py::test_generate_inputobjecttype_unmountedtype", "graphene/types/tests/test_inputobjecttype.py::test_generate_inputobjecttype_as_argument", "graphene/types/tests/test_inputobjecttype.py::test_generate_inputobjecttype_inherit_abstracttype", "graphene/types/tests/test_inputobjecttype.py::test_generate_inputobjecttype_inherit_abstracttype_reversed", "graphene/types/tests/test_inputobjecttype.py::test_inputobjecttype_of_input", "graphene/types/tests/test_inputobjecttype.py::test_inputobjecttype_default_input_as_undefined", "graphene/types/tests/test_type_map.py::test_enum", "graphene/types/tests/test_type_map.py::test_objecttype", "graphene/types/tests/test_type_map.py::test_required_argument_with_default_value", "graphene/types/tests/test_type_map.py::test_dynamic_objecttype", "graphene/types/tests/test_type_map.py::test_interface", "graphene/types/tests/test_type_map.py::test_inputobject", "graphene/types/tests/test_type_map.py::test_inputobject_undefined", "graphene/types/tests/test_type_map.py::test_objecttype_camelcase", "graphene/types/tests/test_type_map.py::test_objecttype_camelcase_disabled", "graphene/types/tests/test_type_map.py::test_objecttype_with_possible_types", "graphene/types/tests/test_type_map.py::test_interface_with_interfaces" ]
[]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> Allow the user to change InputObjectType's default value on non-specified inputs to a sentinel value This PR aims to remove the ambiguity that happens with `InputObjectType`s when accessing optional fields using the `input.<attribute>` "dot access" syntax. ### Current behavior: If an optional input field is defined but has not been specified in an incoming `InputObjectType`, it comes back as a `None` This is ambiguous, since the user could also have set that specific field to `None`, meaning we wouldn't be able to tell between an explicit setting to `None` versus the field not being set at all. ### Proposed behavior in this PR: Introduce a non-breaking, opt-in method to allow the users to change this default value getter behavior in InputObjectTypes to any value that they want to. Graphene already provides such concept in the form of the `graphl.Undefined` value, which is a good example of a value that the user could use to differentiate between an optional input being explicitly set to `None` versus not being set at all. The proposed API is a function called `set_input_object_type_default_value()` that allows the user to change the sentinel value that will be returned in optional inputs (it should be called early in the code, before any `InputObjectType`s are defined). The default value remains `None`, aligning with the current behavior, so as not to break existing code that relies on the current assumption. #### _(Next steps and parting thoughts)_ Moving forward, I believe it'd be best to discuss around introducing a well documented breaking change that fixes this behavior altogether, eliminating such possibility. But the current PR should allow us to keep making progress while bigger fish are being fried :fish: :cook: Thanks! ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in graphene/types/inputobjecttype.py] (definition of set_input_object_type_default_value:) def set_input_object_type_default_value(default_value): """Change the sentinel value returned by non-specified fields in an InputObjectType Useful to differentiate between a field not being set and a field being set to None by using a sentinel value (e.g. Undefined is a good sentinel value for this purpose) This function should be called at the beginning of the app or in some other place where it is guaranteed to be called before any InputObjectType is defined.""" [end of new definitions in graphene/types/inputobjecttype.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
8ede21e06381c096589c424960a6cfaca304badb
pvlib__pvlib-python-1730
1,730
pvlib/pvlib-python
0.9
cfd6e78235e9eff55308f138d4dfe79317b72299
2023-05-10T23:08:53Z
diff --git a/docs/sphinx/source/reference/irradiance/decomposition.rst b/docs/sphinx/source/reference/irradiance/decomposition.rst index 0677d6ac95..08724be38e 100644 --- a/docs/sphinx/source/reference/irradiance/decomposition.rst +++ b/docs/sphinx/source/reference/irradiance/decomposition.rst @@ -12,6 +12,7 @@ DNI estimation models irradiance.dirint irradiance.dirindex irradiance.erbs + irradiance.orgill_hollands irradiance.boland irradiance.campbell_norman irradiance.gti_dirint diff --git a/docs/sphinx/source/whatsnew/v0.10.0.rst b/docs/sphinx/source/whatsnew/v0.10.0.rst index c5e02ffbc3..80c6d9a3f3 100644 --- a/docs/sphinx/source/whatsnew/v0.10.0.rst +++ b/docs/sphinx/source/whatsnew/v0.10.0.rst @@ -29,11 +29,11 @@ Deprecations Enhancements ~~~~~~~~~~~~ +* Added a new irradiance decomposition model :py:func:`pvlib.irradiance.orgill_hollands`. (:pull:`1730`) * The return values of :py:func:`pvlib.pvsystem.calcparams_desoto`, :py:func:`pvlib.pvsystem.calcparams_cec`, and :py:func:`pvlib.pvsystem.calcparams_pvsyst` are all numeric types and have the same Python type as the `effective_irradiance` and `temp_cell` parameters. (:issue:`1626`, :pull:`1700`) - * Added `map_variables` parameter to :py:func:`pvlib.iotools.read_srml` and :py:func:`pvlib.iotools.read_srml_month_from_solardat` (:pull:`1773`) * Allow passing keyword arguments to :py:func:`scipy:scipy.optimize.brentq` and @@ -45,7 +45,6 @@ Enhancements (:issue:`1249`, :pull:`1764`) * Improved `ModelChainResult.__repr__` (:pull:`1236`) - Bug fixes ~~~~~~~~~ @@ -71,6 +70,7 @@ Requirements Contributors ~~~~~~~~~~~~ * Taos Transue (:ghuser:`reepoi`) +* Nicholas Riedel-Lyngskær (:ghuser:`nicorie`) * Adam R. Jensen (:ghuser:`AdamRJensen`) * Echedey Luis (:ghuser:`echedey-ls`) * Cliff Hansen (:ghuser:`cwhanse`) diff --git a/pvlib/irradiance.py b/pvlib/irradiance.py index af983e47b9..beec6dd0b2 100644 --- a/pvlib/irradiance.py +++ b/pvlib/irradiance.py @@ -2227,6 +2227,8 @@ def erbs(ghi, zenith, datetime_or_doy, min_cos_zenith=0.065, max_zenith=87): -------- dirint disc + orgill_hollands + boland """ dni_extra = get_extra_radiation(datetime_or_doy) @@ -2265,6 +2267,93 @@ def erbs(ghi, zenith, datetime_or_doy, min_cos_zenith=0.065, max_zenith=87): return data +def orgill_hollands(ghi, zenith, datetime_or_doy, dni_extra=None, + min_cos_zenith=0.065, max_zenith=87): + """Estimate DNI and DHI from GHI using the Orgill and Hollands model. + + The Orgill and Hollands model [1]_ estimates the diffuse fraction DF from + global horizontal irradiance through an empirical relationship between + hourly DF observations (in Toronto, Canada) and the ratio of GHI to + extraterrestrial irradiance, Kt. + + Parameters + ---------- + ghi: numeric + Global horizontal irradiance in W/m^2. + zenith: numeric + True (not refraction-corrected) zenith angles in decimal degrees. + datetime_or_doy : int, float, array, pd.DatetimeIndex + Day of year or array of days of year e.g. + pd.DatetimeIndex.dayofyear, or pd.DatetimeIndex. + dni_extra : None or numeric, default None + Extraterrestrial direct normal irradiance. [W/m2] + min_cos_zenith : numeric, default 0.065 + Minimum value of cos(zenith) to allow when calculating global + clearness index `kt`. Equivalent to zenith = 86.273 degrees. + max_zenith : numeric, default 87 + Maximum value of zenith to allow in DNI calculation. DNI will be + set to 0 for times with zenith values greater than `max_zenith`. + + Returns + ------- + data : OrderedDict or DataFrame + Contains the following keys/columns: + + * ``dni``: the modeled direct normal irradiance in W/m^2. + * ``dhi``: the modeled diffuse horizontal irradiance in + W/m^2. + * ``kt``: Ratio of global to extraterrestrial irradiance + on a horizontal plane. + + References + ---------- + .. [1] Orgill, J.F., Hollands, K.G.T., Correlation equation for hourly + diffuse radiation on a horizontal surface, Solar Energy 19(4), pp 357–359, + 1977. Eqs. 3(a), 3(b) and 3(c) + :doi:`10.1016/0038-092X(77)90006-8` + + See Also + -------- + dirint + disc + erbs + boland + """ + if dni_extra is None: + dni_extra = get_extra_radiation(datetime_or_doy) + + kt = clearness_index(ghi, zenith, dni_extra, min_cos_zenith=min_cos_zenith, + max_clearness_index=1) + + # For Kt < 0.35, set the diffuse fraction + df = 1 - 0.249*kt + + # For Kt >= 0.35 and Kt <= 0.75, set the diffuse fraction + df = np.where((kt >= 0.35) & (kt <= 0.75), + 1.557 - 1.84*kt, df) + + # For Kt > 0.75, set the diffuse fraction + df = np.where(kt > 0.75, 0.177, df) + + dhi = df * ghi + + dni = (ghi - dhi) / tools.cosd(zenith) + bad_values = (zenith > max_zenith) | (ghi < 0) | (dni < 0) + dni = np.where(bad_values, 0, dni) + # ensure that closure relationship remains valid + dhi = np.where(bad_values, ghi, dhi) + + data = OrderedDict() + data['dni'] = dni + data['dhi'] = dhi + data['kt'] = kt + + if isinstance(datetime_or_doy, pd.DatetimeIndex): + data = pd.DataFrame(data, index=datetime_or_doy) + + return data + + def boland(ghi, solar_zenith, datetime_or_doy, a_coeff=8.645, b_coeff=0.613, min_cos_zenith=0.065, max_zenith=87): r""" @@ -2326,6 +2415,7 @@ def boland(ghi, solar_zenith, datetime_or_doy, a_coeff=8.645, b_coeff=0.613, dirint disc erbs + orgill_hollands Notes -----
diff --git a/pvlib/tests/test_irradiance.py b/pvlib/tests/test_irradiance.py index d0158dad1a..ab1af612a7 100644 --- a/pvlib/tests/test_irradiance.py +++ b/pvlib/tests/test_irradiance.py @@ -821,6 +821,22 @@ def test_boland(): assert np.allclose(out, expected) +def test_orgill_hollands(): + index = pd.DatetimeIndex(['20190101']*3 + ['20190620']) + ghi = pd.Series([0, 50, 1000, 1000], index=index) + zenith = pd.Series([120, 85, 10, 10], index=index) + expected = pd.DataFrame(np.array( + [[0.0, 0.0, 0.0], + [108.731366, 40.5234370, 0.405723511], + [776.155771, 235.635779, 0.718132729], + [835.696102, 177.000000, 0.768214312]]), + columns=['dni', 'dhi', 'kt'], index=index) + + out = irradiance.orgill_hollands(ghi, zenith, index) + + assert np.allclose(out, expected) + + def test_erbs_min_cos_zenith_max_zenith(): # map out behavior under difficult conditions with various # limiting kwargs settings
diff --git a/docs/sphinx/source/reference/irradiance/decomposition.rst b/docs/sphinx/source/reference/irradiance/decomposition.rst index 0677d6ac95..08724be38e 100644 --- a/docs/sphinx/source/reference/irradiance/decomposition.rst +++ b/docs/sphinx/source/reference/irradiance/decomposition.rst @@ -12,6 +12,7 @@ DNI estimation models irradiance.dirint irradiance.dirindex irradiance.erbs + irradiance.orgill_hollands irradiance.boland irradiance.campbell_norman irradiance.gti_dirint diff --git a/docs/sphinx/source/whatsnew/v0.10.0.rst b/docs/sphinx/source/whatsnew/v0.10.0.rst index c5e02ffbc3..80c6d9a3f3 100644 --- a/docs/sphinx/source/whatsnew/v0.10.0.rst +++ b/docs/sphinx/source/whatsnew/v0.10.0.rst @@ -29,11 +29,11 @@ Deprecations Enhancements ~~~~~~~~~~~~ +* Added a new irradiance decomposition model :py:func:`pvlib.irradiance.orgill_hollands`. (:pull:`1730`) * The return values of :py:func:`pvlib.pvsystem.calcparams_desoto`, :py:func:`pvlib.pvsystem.calcparams_cec`, and :py:func:`pvlib.pvsystem.calcparams_pvsyst` are all numeric types and have the same Python type as the `effective_irradiance` and `temp_cell` parameters. (:issue:`1626`, :pull:`1700`) - * Added `map_variables` parameter to :py:func:`pvlib.iotools.read_srml` and :py:func:`pvlib.iotools.read_srml_month_from_solardat` (:pull:`1773`) * Allow passing keyword arguments to :py:func:`scipy:scipy.optimize.brentq` and @@ -45,7 +45,6 @@ Enhancements (:issue:`1249`, :pull:`1764`) * Improved `ModelChainResult.__repr__` (:pull:`1236`) - Bug fixes ~~~~~~~~~ @@ -71,6 +70,7 @@ Requirements Contributors ~~~~~~~~~~~~ * Taos Transue (:ghuser:`reepoi`) +* Nicholas Riedel-Lyngskær (:ghuser:`nicorie`) * Adam R. Jensen (:ghuser:`AdamRJensen`) * Echedey Luis (:ghuser:`echedey-ls`) * Cliff Hansen (:ghuser:`cwhanse`)
[ { "components": [ { "doc": "Estimate DNI and DHI from GHI using the Orgill and Hollands model.\n\nThe Orgill and Hollands model [1]_ estimates the diffuse fraction DF from\nglobal horizontal irradiance through an empirical relationship between\nhourly DF observations (in Toronto, Canada) and the ratio of GHI to\nextraterrestrial irradiance, Kt.\n\nParameters\n----------\nghi: numeric\n Global horizontal irradiance in W/m^2.\nzenith: numeric\n True (not refraction-corrected) zenith angles in decimal degrees.\ndatetime_or_doy : int, float, array, pd.DatetimeIndex\n Day of year or array of days of year e.g.\n pd.DatetimeIndex.dayofyear, or pd.DatetimeIndex.\ndni_extra : None or numeric, default None\n Extraterrestrial direct normal irradiance. [W/m2]\nmin_cos_zenith : numeric, default 0.065\n Minimum value of cos(zenith) to allow when calculating global\n clearness index `kt`. Equivalent to zenith = 86.273 degrees.\nmax_zenith : numeric, default 87\n Maximum value of zenith to allow in DNI calculation. DNI will be\n set to 0 for times with zenith values greater than `max_zenith`.\n\nReturns\n-------\ndata : OrderedDict or DataFrame\n Contains the following keys/columns:\n\n * ``dni``: the modeled direct normal irradiance in W/m^2.\n * ``dhi``: the modeled diffuse horizontal irradiance in\n W/m^2.\n * ``kt``: Ratio of global to extraterrestrial irradiance\n on a horizontal plane.\n\nReferences\n----------\n.. [1] Orgill, J.F., Hollands, K.G.T., Correlation equation for hourly\n diffuse radiation on a horizontal surface, Solar Energy 19(4), pp 357–359,\n 1977. Eqs. 3(a), 3(b) and 3(c)\n :doi:`10.1016/0038-092X(77)90006-8`\n\nSee Also\n--------\ndirint\ndisc\nerbs\nboland", "lines": [ 2270, 2354 ], "name": "orgill_hollands", "signature": "def orgill_hollands(ghi, zenith, datetime_or_doy, dni_extra=None, min_cos_zenith=0.065, max_zenith=87):", "type": "function" } ], "file": "pvlib/irradiance.py" } ]
[ "pvlib/tests/test_irradiance.py::test_orgill_hollands" ]
[ "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-300-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-300.0-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-testval2-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-testval3-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-testval4-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-testval5-expected5]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-testval6-expected6]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-testval7-expected7]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-testval8-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-300-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-300.0-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-testval2-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-testval3-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-testval4-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-testval5-expected5]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-testval6-expected6]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-testval7-expected7]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-testval8-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-300-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-300.0-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-testval2-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-testval3-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-testval4-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-testval5-expected5]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-testval6-expected6]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-testval7-expected7]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-testval8-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-300-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-300.0-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-testval2-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-testval3-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-testval4-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-testval5-expected5]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-testval6-expected6]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-testval7-expected7]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-testval8-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation_epoch_year", "pvlib/tests/test_irradiance.py::test_get_extra_radiation_nrel_numba", "pvlib/tests/test_irradiance.py::test_get_extra_radiation_invalid", "pvlib/tests/test_irradiance.py::test_get_ground_diffuse_simple_float", "pvlib/tests/test_irradiance.py::test_get_ground_diffuse_simple_series", "pvlib/tests/test_irradiance.py::test_get_ground_diffuse_albedo_0", "pvlib/tests/test_irradiance.py::test_get_ground_diffuse_albedo_series", "pvlib/tests/test_irradiance.py::test_grounddiffuse_albedo_invalid_surface", "pvlib/tests/test_irradiance.py::test_get_ground_diffuse_albedo_surface", "pvlib/tests/test_irradiance.py::test_isotropic_float", "pvlib/tests/test_irradiance.py::test_isotropic_series", "pvlib/tests/test_irradiance.py::test_klucher_series_float", "pvlib/tests/test_irradiance.py::test_klucher_series", "pvlib/tests/test_irradiance.py::test_haydavies", "pvlib/tests/test_irradiance.py::test_haydavies_components", "pvlib/tests/test_irradiance.py::test_reindl", "pvlib/tests/test_irradiance.py::test_king", "pvlib/tests/test_irradiance.py::test_perez", "pvlib/tests/test_irradiance.py::test_perez_components", "pvlib/tests/test_irradiance.py::test_perez_negative_horizon", "pvlib/tests/test_irradiance.py::test_perez_arrays", "pvlib/tests/test_irradiance.py::test_perez_scalar", "pvlib/tests/test_irradiance.py::test_sky_diffuse_zenith_close_to_90[isotropic]", "pvlib/tests/test_irradiance.py::test_sky_diffuse_zenith_close_to_90[klucher]", "pvlib/tests/test_irradiance.py::test_sky_diffuse_zenith_close_to_90[haydavies]", "pvlib/tests/test_irradiance.py::test_sky_diffuse_zenith_close_to_90[reindl]", "pvlib/tests/test_irradiance.py::test_sky_diffuse_zenith_close_to_90[king]", "pvlib/tests/test_irradiance.py::test_sky_diffuse_zenith_close_to_90[perez]", "pvlib/tests/test_irradiance.py::test_get_sky_diffuse_model_invalid", "pvlib/tests/test_irradiance.py::test_get_sky_diffuse_missing_dni_extra", "pvlib/tests/test_irradiance.py::test_get_sky_diffuse_missing_airmass", "pvlib/tests/test_irradiance.py::test_campbell_norman", "pvlib/tests/test_irradiance.py::test_get_total_irradiance", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_albedo[isotropic]", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_albedo[klucher]", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_albedo[haydavies]", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_albedo[reindl]", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_albedo[king]", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_albedo[perez]", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_scalars[isotropic]", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_scalars[klucher]", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_scalars[haydavies]", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_scalars[reindl]", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_scalars[king]", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_scalars[perez]", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_missing_dni_extra", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_missing_airmass", "pvlib/tests/test_irradiance.py::test_poa_components", "pvlib/tests/test_irradiance.py::test_disc_value[93193-expected0]", "pvlib/tests/test_irradiance.py::test_disc_value[None-expected1]", "pvlib/tests/test_irradiance.py::test_disc_value[101325-expected2]", "pvlib/tests/test_irradiance.py::test_disc_overirradiance", "pvlib/tests/test_irradiance.py::test_disc_min_cos_zenith_max_zenith", "pvlib/tests/test_irradiance.py::test_dirint_value", "pvlib/tests/test_irradiance.py::test_dirint_nans", "pvlib/tests/test_irradiance.py::test_dirint_tdew", "pvlib/tests/test_irradiance.py::test_dirint_no_delta_kt", "pvlib/tests/test_irradiance.py::test_dirint_coeffs", "pvlib/tests/test_irradiance.py::test_dirint_min_cos_zenith_max_zenith", "pvlib/tests/test_irradiance.py::test_gti_dirint", "pvlib/tests/test_irradiance.py::test_erbs", "pvlib/tests/test_irradiance.py::test_boland", "pvlib/tests/test_irradiance.py::test_erbs_min_cos_zenith_max_zenith", "pvlib/tests/test_irradiance.py::test_erbs_all_scalar", "pvlib/tests/test_irradiance.py::test_dirindex", "pvlib/tests/test_irradiance.py::test_dirindex_min_cos_zenith_max_zenith", "pvlib/tests/test_irradiance.py::test_dni", "pvlib/tests/test_irradiance.py::test_aoi_and_aoi_projection[0-0-0-0-0-1]", "pvlib/tests/test_irradiance.py::test_aoi_and_aoi_projection[30-180-30-180-0-1]", "pvlib/tests/test_irradiance.py::test_aoi_and_aoi_projection[30-180-150-0-180--1]", "pvlib/tests/test_irradiance.py::test_aoi_and_aoi_projection[90-0-30-60-75.5224878-0.25]", "pvlib/tests/test_irradiance.py::test_aoi_and_aoi_projection[90-0-30-170-119.4987042--0.4924038]", "pvlib/tests/test_irradiance.py::test_aoi_projection_precision", "pvlib/tests/test_irradiance.py::test_kt_kt_prime_factor", "pvlib/tests/test_irradiance.py::test_clearsky_index", "pvlib/tests/test_irradiance.py::test_clearness_index", "pvlib/tests/test_irradiance.py::test_clearness_index_zenith_independent", "pvlib/tests/test_irradiance.py::test_complete_irradiance", "pvlib/tests/test_irradiance.py::test_louche" ]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> add orgill hollands decomposition <!-- Thank you for your contribution! The following items must be addressed before the code can be merged. Please don't hesitate to ask for help if you're unsure of how to accomplish any of the items. Feel free to remove checklist items that are not relevant to your change. --> - [x] I am familiar with the [contributing guidelines](https://pvlib-python.readthedocs.io/en/latest/contributing.html) - [x] Tests added - [x] Updates entries in [`docs/sphinx/source/reference`](https://github.com/pvlib/pvlib-python/blob/main/docs/sphinx/source/reference) for API changes. - [x] Adds description and name entries in the appropriate "what's new" file in [`docs/sphinx/source/whatsnew`](https://github.com/pvlib/pvlib-python/tree/main/docs/sphinx/source/whatsnew) for all changes. Includes link to the GitHub Issue with `` :issue:`num` `` or this Pull Request with `` :pull:`num` ``. Includes contributor name and/or GitHub username (link with `` :ghuser:`user` ``). - [x] New code is fully documented. Includes [numpydoc](https://numpydoc.readthedocs.io/en/latest/format.html) compliant docstrings, examples, and comments where necessary. - [x] Pull request is nearly complete and ready for detailed review. - [x] Maintainer: Appropriate GitHub Labels (including `remote-data`) and Milestone are assigned to the Pull Request and linked Issue. <!-- Brief description of the problem and proposed solution (if not already fully described in the issue linked to above): --> This PR adds the Orgill and Hollands decomposition model (https://doi.org/10.1016/0038-092X(77)90006-8) to the irradiance module. ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in pvlib/irradiance.py] (definition of orgill_hollands:) def orgill_hollands(ghi, zenith, datetime_or_doy, dni_extra=None, min_cos_zenith=0.065, max_zenith=87): """Estimate DNI and DHI from GHI using the Orgill and Hollands model. The Orgill and Hollands model [1]_ estimates the diffuse fraction DF from global horizontal irradiance through an empirical relationship between hourly DF observations (in Toronto, Canada) and the ratio of GHI to extraterrestrial irradiance, Kt. Parameters ---------- ghi: numeric Global horizontal irradiance in W/m^2. zenith: numeric True (not refraction-corrected) zenith angles in decimal degrees. datetime_or_doy : int, float, array, pd.DatetimeIndex Day of year or array of days of year e.g. pd.DatetimeIndex.dayofyear, or pd.DatetimeIndex. dni_extra : None or numeric, default None Extraterrestrial direct normal irradiance. [W/m2] min_cos_zenith : numeric, default 0.065 Minimum value of cos(zenith) to allow when calculating global clearness index `kt`. Equivalent to zenith = 86.273 degrees. max_zenith : numeric, default 87 Maximum value of zenith to allow in DNI calculation. DNI will be set to 0 for times with zenith values greater than `max_zenith`. Returns ------- data : OrderedDict or DataFrame Contains the following keys/columns: * ``dni``: the modeled direct normal irradiance in W/m^2. * ``dhi``: the modeled diffuse horizontal irradiance in W/m^2. * ``kt``: Ratio of global to extraterrestrial irradiance on a horizontal plane. References ---------- .. [1] Orgill, J.F., Hollands, K.G.T., Correlation equation for hourly diffuse radiation on a horizontal surface, Solar Energy 19(4), pp 357–359, 1977. Eqs. 3(a), 3(b) and 3(c) :doi:`10.1016/0038-092X(77)90006-8` See Also -------- dirint disc erbs boland""" [end of new definitions in pvlib/irradiance.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
d53f97e984bfdd268aa92f8bf482ced0edda0110
joke2k__faker-1848
1,848
joke2k/faker
null
d93d8a0d42b7a92d8b386d73c85886b2633124e7
2023-04-22T05:52:53Z
diff --git a/faker/providers/phone_number/en_US/__init__.py b/faker/providers/phone_number/en_US/__init__.py index bb0b77df84..ac1367e8bf 100644 --- a/faker/providers/phone_number/en_US/__init__.py +++ b/faker/providers/phone_number/en_US/__init__.py @@ -37,3 +37,14 @@ class Provider(PhoneNumberProvider): "001-###-###-####x####", "001-###-###-####x#####", ) + + basic_formats = ( + # basic 10-digit phone number format with no extensions + "##########", + "###-###-####", + "(###)###-####", + ) + + def basic_phone_number(self) -> str: + pattern: str = self.random_element(self.basic_formats) + return self.numerify(self.generator.parse(pattern))
diff --git a/tests/providers/test_phone_number.py b/tests/providers/test_phone_number.py index 8fd54ec316..1bb38daf9e 100644 --- a/tests/providers/test_phone_number.py +++ b/tests/providers/test_phone_number.py @@ -364,3 +364,18 @@ def test_phone_number(self, faker, num_samples): for _ in range(num_samples): phone_number = faker.phone_number() assert any([re.match(pattern, phone_number) for pattern in patterns]) + + +class TestEnUs: + """Test En_US phone provider methods""" + + def test_basic_phone_number(self, faker, num_samples): + pattern_no_whitespaces: Pattern = re.compile( + r"\d{9}", + ) + pattern_dashes: Pattern = re.compile(r"\d{3}-\d{3}-\d{4}") + pattern_parens: Pattern = re.compile(r"\(\d{3}\)\d{3}-\d{4}") + patterns = [pattern_no_whitespaces, pattern_dashes, pattern_parens] + for _ in range(num_samples): + phone_number = faker.basic_phone_number() + assert any([re.match(pattern, phone_number) for pattern in patterns])
[ { "components": [ { "doc": "", "lines": [ 48, 50 ], "name": "Provider.basic_phone_number", "signature": "def basic_phone_number(self) -> str:", "type": "function" } ], "file": "faker/providers/phone_number/en_US/__init__.py" } ]
[ "tests/providers/test_phone_number.py::TestEnUs::test_basic_phone_number" ]
[ "tests/providers/test_phone_number.py::TestPhoneNumber::test_country_calling_code", "tests/providers/test_phone_number.py::TestPhoneNumber::test_msisdn", "tests/providers/test_phone_number.py::TestAzAz::test_phone_number", "tests/providers/test_phone_number.py::TestAzAz::test_cellphone_number", "tests/providers/test_phone_number.py::TestAzAz::test_landline_number", "tests/providers/test_phone_number.py::TestJaJp::test_phone_number", "tests/providers/test_phone_number.py::TestPtBr::test_phone_number", "tests/providers/test_phone_number.py::TestPtBr::test_msisdn", "tests/providers/test_phone_number.py::TestPtBr::test_cellphone", "tests/providers/test_phone_number.py::TestPtBr::test_service_phone", "tests/providers/test_phone_number.py::TestHuHu::test_phone_number", "tests/providers/test_phone_number.py::TestThTh::test_phone_number", "tests/providers/test_phone_number.py::TestHyAm::test_phone_number", "tests/providers/test_phone_number.py::TestEnPh::test_globe_mobile_number", "tests/providers/test_phone_number.py::TestEnPh::test_smart_mobile_number", "tests/providers/test_phone_number.py::TestEnPh::test_sun_mobile_number", "tests/providers/test_phone_number.py::TestEnPh::test_mobile_number", "tests/providers/test_phone_number.py::TestEnPh::test_globe_area2_landline_number", "tests/providers/test_phone_number.py::TestEnPh::test_pldt_area2_landline_number", "tests/providers/test_phone_number.py::TestEnPh::test_bayantel_area2_landline_number", "tests/providers/test_phone_number.py::TestEnPh::test_misc_area2_landline_number", "tests/providers/test_phone_number.py::TestEnPh::test_area2_landline_number", "tests/providers/test_phone_number.py::TestEnPh::test_non_area2_landline_number", "tests/providers/test_phone_number.py::TestEnPh::test_landline_number", "tests/providers/test_phone_number.py::TestFilPh::test_globe_mobile_number", "tests/providers/test_phone_number.py::TestFilPh::test_smart_mobile_number", "tests/providers/test_phone_number.py::TestFilPh::test_sun_mobile_number", "tests/providers/test_phone_number.py::TestFilPh::test_mobile_number", "tests/providers/test_phone_number.py::TestFilPh::test_globe_area2_landline_number", "tests/providers/test_phone_number.py::TestFilPh::test_pldt_area2_landline_number", "tests/providers/test_phone_number.py::TestFilPh::test_bayantel_area2_landline_number", "tests/providers/test_phone_number.py::TestFilPh::test_misc_area2_landline_number", "tests/providers/test_phone_number.py::TestFilPh::test_area2_landline_number", "tests/providers/test_phone_number.py::TestFilPh::test_non_area2_landline_number", "tests/providers/test_phone_number.py::TestFilPh::test_landline_number", "tests/providers/test_phone_number.py::TestTlPh::test_globe_mobile_number", "tests/providers/test_phone_number.py::TestTlPh::test_smart_mobile_number", "tests/providers/test_phone_number.py::TestTlPh::test_sun_mobile_number", "tests/providers/test_phone_number.py::TestTlPh::test_mobile_number", "tests/providers/test_phone_number.py::TestTlPh::test_globe_area2_landline_number", "tests/providers/test_phone_number.py::TestTlPh::test_pldt_area2_landline_number", "tests/providers/test_phone_number.py::TestTlPh::test_bayantel_area2_landline_number", "tests/providers/test_phone_number.py::TestTlPh::test_misc_area2_landline_number", "tests/providers/test_phone_number.py::TestTlPh::test_area2_landline_number", "tests/providers/test_phone_number.py::TestTlPh::test_non_area2_landline_number", "tests/providers/test_phone_number.py::TestTlPh::test_landline_number", "tests/providers/test_phone_number.py::TestTaIn::test_phone_number", "tests/providers/test_phone_number.py::TestEsCo::test_phone_number", "tests/providers/test_phone_number.py::TestEsEs::test_phone_number", "tests/providers/test_phone_number.py::TestArAe::test_cellphone_number", "tests/providers/test_phone_number.py::TestArAe::test_telephone_number", "tests/providers/test_phone_number.py::TestArAe::test_toll_number", "tests/providers/test_phone_number.py::TestArAe::test_service_phone_number", "tests/providers/test_phone_number.py::TestArAe::test_phone_number", "tests/providers/test_phone_number.py::TestFrFr::test_phone_number" ]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> add a separate basic number format for US issue ticket: https://github.com/joke2k/faker/issues/1847 ### What does this change Adds a 'basic phone number' type to en_US to comply with some form requirements, as well as a unit test. ### What was wrong Some forms do not allow for phone formats with extensions or country codes. As a result, the faker get_phone function for en_US doesn't work for all cases. ### How this fixes it Adds a function that allows the user to only use 'basic' ten-digit phone numbers and standard formatting. ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in faker/providers/phone_number/en_US/__init__.py] (definition of Provider.basic_phone_number:) def basic_phone_number(self) -> str: [end of new definitions in faker/providers/phone_number/en_US/__init__.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
6edfdbf6ae90b0153309e3bf066aa3b2d16494a7
matplotlib__matplotlib-25686
25,686
matplotlib/matplotlib
3.7
b86ebbafe4673583345d0a01a6ea205af34c58dc
2023-04-14T21:31:42Z
diff --git a/doc/users/next_whats_new/get_suptitle.rst b/doc/users/next_whats_new/get_suptitle.rst new file mode 100644 index 000000000000..b03ad10b1b4c --- /dev/null +++ b/doc/users/next_whats_new/get_suptitle.rst @@ -0,0 +1,4 @@ +``Figure.get_suptitle()``, ``Figure.get_supxlabel()``, ``Figure.get_supylabel()`` +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +These methods return the strings set by ``Figure.suptitle()``, ``Figure.supxlabel()`` +and ``Figure.supylabel()`` respectively. diff --git a/lib/matplotlib/figure.py b/lib/matplotlib/figure.py index 7fdcc8cb6627..970bf957d4bf 100644 --- a/lib/matplotlib/figure.py +++ b/lib/matplotlib/figure.py @@ -388,6 +388,11 @@ def suptitle(self, t, **kwargs): 'size': 'figure.titlesize', 'weight': 'figure.titleweight'} return self._suplabels(t, info, **kwargs) + def get_suptitle(self): + """Return the suptitle as string or an empty string if not set.""" + text_obj = self._suptitle + return "" if text_obj is None else text_obj.get_text() + @_docstring.Substitution(x0=0.5, y0=0.01, name='supxlabel', ha='center', va='bottom', rc='label') @_docstring.copy(_suplabels) @@ -398,6 +403,11 @@ def supxlabel(self, t, **kwargs): 'size': 'figure.labelsize', 'weight': 'figure.labelweight'} return self._suplabels(t, info, **kwargs) + def get_supxlabel(self): + """Return the supxlabel as string or an empty string if not set.""" + text_obj = self._supxlabel + return "" if text_obj is None else text_obj.get_text() + @_docstring.Substitution(x0=0.02, y0=0.5, name='supylabel', ha='left', va='center', rc='label') @_docstring.copy(_suplabels) @@ -409,6 +419,11 @@ def supylabel(self, t, **kwargs): 'weight': 'figure.labelweight'} return self._suplabels(t, info, **kwargs) + def get_supylabel(self): + """Return the supylabel as string or an empty string if not set.""" + text_obj = self._supylabel + return "" if text_obj is None else text_obj.get_text() + def get_edgecolor(self): """Get the edge color of the Figure rectangle.""" return self.patch.get_edgecolor() diff --git a/lib/matplotlib/figure.pyi b/lib/matplotlib/figure.pyi index ee21892f32ac..f4c31506a2e1 100644 --- a/lib/matplotlib/figure.pyi +++ b/lib/matplotlib/figure.pyi @@ -90,8 +90,11 @@ class FigureBase(Artist): def get_children(self) -> list[Artist]: ... def contains(self, mouseevent: MouseEvent) -> tuple[bool, dict[Any, Any]]: ... def suptitle(self, t: str, **kwargs) -> Text: ... + def get_suptitle(self) -> str: ... def supxlabel(self, t: str, **kwargs) -> Text: ... + def get_supxlabel(self) -> str: ... def supylabel(self, t: str, **kwargs) -> Text: ... + def get_supylabel(self) -> str: ... def get_edgecolor(self) -> ColorType: ... def get_facecolor(self) -> ColorType: ... def get_frameon(self) -> bool: ...
diff --git a/lib/matplotlib/tests/test_figure.py b/lib/matplotlib/tests/test_figure.py index 4188ca878fed..d8f137ddd61a 100644 --- a/lib/matplotlib/tests/test_figure.py +++ b/lib/matplotlib/tests/test_figure.py @@ -302,6 +302,19 @@ def test_suptitle_subfigures(): assert sf2.get_facecolor() == (1.0, 1.0, 1.0, 1.0) +def test_get_suptitle_supxlabel_supylabel(): + fig, ax = plt.subplots() + assert fig.get_suptitle() == "" + assert fig.get_supxlabel() == "" + assert fig.get_supylabel() == "" + fig.suptitle('suptitle') + assert fig.get_suptitle() == 'suptitle' + fig.supxlabel('supxlabel') + assert fig.get_supxlabel() == 'supxlabel' + fig.supylabel('supylabel') + assert fig.get_supylabel() == 'supylabel' + + @image_comparison(['alpha_background'], # only test png and svg. The PDF output appears correct, # but Ghostscript does not preserve the background color.
diff --git a/doc/users/next_whats_new/get_suptitle.rst b/doc/users/next_whats_new/get_suptitle.rst new file mode 100644 index 000000000000..b03ad10b1b4c --- /dev/null +++ b/doc/users/next_whats_new/get_suptitle.rst @@ -0,0 +1,4 @@ +``Figure.get_suptitle()``, ``Figure.get_supxlabel()``, ``Figure.get_supylabel()`` +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +These methods return the strings set by ``Figure.suptitle()``, ``Figure.supxlabel()`` +and ``Figure.supylabel()`` respectively. diff --git a/lib/matplotlib/figure.pyi b/lib/matplotlib/figure.pyi index ee21892f32ac..f4c31506a2e1 100644 --- a/lib/matplotlib/figure.pyi +++ b/lib/matplotlib/figure.pyi @@ -90,8 +90,11 @@ class FigureBase(Artist): def get_children(self) -> list[Artist]: ... def contains(self, mouseevent: MouseEvent) -> tuple[bool, dict[Any, Any]]: ... def suptitle(self, t: str, **kwargs) -> Text: ... + def get_suptitle(self) -> str: ... def supxlabel(self, t: str, **kwargs) -> Text: ... + def get_supxlabel(self) -> str: ... def supylabel(self, t: str, **kwargs) -> Text: ... + def get_supylabel(self) -> str: ... def get_edgecolor(self) -> ColorType: ... def get_facecolor(self) -> ColorType: ... def get_frameon(self) -> bool: ...
[ { "components": [ { "doc": "Return the suptitle as string or an empty string if not set.", "lines": [ 391, 394 ], "name": "FigureBase.get_suptitle", "signature": "def get_suptitle(self):", "type": "function" }, { "doc": "Return the supxlabel as string or an empty string if not set.", "lines": [ 406, 409 ], "name": "FigureBase.get_supxlabel", "signature": "def get_supxlabel(self):", "type": "function" }, { "doc": "Return the supylabel as string or an empty string if not set.", "lines": [ 422, 425 ], "name": "FigureBase.get_supylabel", "signature": "def get_supylabel(self):", "type": "function" } ], "file": "lib/matplotlib/figure.py" } ]
[ "lib/matplotlib/tests/test_figure.py::test_get_suptitle_supxlabel_supylabel" ]
[ "lib/matplotlib/tests/test_figure.py::test_align_labels[png]", "lib/matplotlib/tests/test_figure.py::test_align_labels_stray_axes", "lib/matplotlib/tests/test_figure.py::test_figure_label", "lib/matplotlib/tests/test_figure.py::test_fignum_exists", "lib/matplotlib/tests/test_figure.py::test_clf_keyword", "lib/matplotlib/tests/test_figure.py::test_figure[png]", "lib/matplotlib/tests/test_figure.py::test_figure_legend[png]", "lib/matplotlib/tests/test_figure.py::test_gca", "lib/matplotlib/tests/test_figure.py::test_add_subplot_subclass", "lib/matplotlib/tests/test_figure.py::test_add_subplot_invalid", "lib/matplotlib/tests/test_figure.py::test_suptitle[png]", "lib/matplotlib/tests/test_figure.py::test_suptitle_fontproperties", "lib/matplotlib/tests/test_figure.py::test_suptitle_subfigures", "lib/matplotlib/tests/test_figure.py::test_alpha[png]", "lib/matplotlib/tests/test_figure.py::test_too_many_figures", "lib/matplotlib/tests/test_figure.py::test_iterability_axes_argument", "lib/matplotlib/tests/test_figure.py::test_set_fig_size", "lib/matplotlib/tests/test_figure.py::test_axes_remove", "lib/matplotlib/tests/test_figure.py::test_figaspect", "lib/matplotlib/tests/test_figure.py::test_autofmt_xdate[both]", "lib/matplotlib/tests/test_figure.py::test_autofmt_xdate[major]", "lib/matplotlib/tests/test_figure.py::test_autofmt_xdate[minor]", "lib/matplotlib/tests/test_figure.py::test_change_dpi", "lib/matplotlib/tests/test_figure.py::test_invalid_figure_size[1-nan]", "lib/matplotlib/tests/test_figure.py::test_invalid_figure_size[-1-1]", "lib/matplotlib/tests/test_figure.py::test_invalid_figure_size[inf-1]", "lib/matplotlib/tests/test_figure.py::test_invalid_figure_add_axes", "lib/matplotlib/tests/test_figure.py::test_subplots_shareax_loglabels", "lib/matplotlib/tests/test_figure.py::test_savefig", "lib/matplotlib/tests/test_figure.py::test_savefig_warns", "lib/matplotlib/tests/test_figure.py::test_savefig_backend", "lib/matplotlib/tests/test_figure.py::test_savefig_pixel_ratio[Agg]", "lib/matplotlib/tests/test_figure.py::test_savefig_pixel_ratio[Cairo]", "lib/matplotlib/tests/test_figure.py::test_savefig_preserve_layout_engine", "lib/matplotlib/tests/test_figure.py::test_savefig_locate_colorbar", "lib/matplotlib/tests/test_figure.py::test_savefig_transparent[png]", "lib/matplotlib/tests/test_figure.py::test_figure_repr", "lib/matplotlib/tests/test_figure.py::test_valid_layouts", "lib/matplotlib/tests/test_figure.py::test_invalid_layouts", "lib/matplotlib/tests/test_figure.py::test_tightlayout_autolayout_deconflict[png]", "lib/matplotlib/tests/test_figure.py::test_layout_change_warning[constrained]", "lib/matplotlib/tests/test_figure.py::test_layout_change_warning[compressed]", "lib/matplotlib/tests/test_figure.py::test_add_artist[png]", "lib/matplotlib/tests/test_figure.py::test_fspath[png]", "lib/matplotlib/tests/test_figure.py::test_fspath[pdf]", "lib/matplotlib/tests/test_figure.py::test_fspath[ps]", "lib/matplotlib/tests/test_figure.py::test_fspath[eps]", "lib/matplotlib/tests/test_figure.py::test_fspath[svg]", "lib/matplotlib/tests/test_figure.py::test_tightbbox", "lib/matplotlib/tests/test_figure.py::test_axes_removal", "lib/matplotlib/tests/test_figure.py::test_removed_axis", "lib/matplotlib/tests/test_figure.py::test_figure_clear[clear]", "lib/matplotlib/tests/test_figure.py::test_figure_clear[clf]", "lib/matplotlib/tests/test_figure.py::test_clf_not_redefined", "lib/matplotlib/tests/test_figure.py::test_picking_does_not_stale", "lib/matplotlib/tests/test_figure.py::test_add_subplot_twotuple", "lib/matplotlib/tests/test_figure.py::test_animated_with_canvas_change[png]", "lib/matplotlib/tests/test_figure.py::TestSubplotMosaic::test_basic[x0-png]", "lib/matplotlib/tests/test_figure.py::TestSubplotMosaic::test_basic[x1-png]", "lib/matplotlib/tests/test_figure.py::TestSubplotMosaic::test_basic[x2-png]", "lib/matplotlib/tests/test_figure.py::TestSubplotMosaic::test_basic[x3-png]", "lib/matplotlib/tests/test_figure.py::TestSubplotMosaic::test_all_nested[png]", "lib/matplotlib/tests/test_figure.py::TestSubplotMosaic::test_nested[png]", "lib/matplotlib/tests/test_figure.py::TestSubplotMosaic::test_nested_tuple[png]", "lib/matplotlib/tests/test_figure.py::TestSubplotMosaic::test_nested_width_ratios", "lib/matplotlib/tests/test_figure.py::TestSubplotMosaic::test_nested_height_ratios", "lib/matplotlib/tests/test_figure.py::TestSubplotMosaic::test_empty[x0-None-png]", "lib/matplotlib/tests/test_figure.py::TestSubplotMosaic::test_empty[x1-SKIP-png]", "lib/matplotlib/tests/test_figure.py::TestSubplotMosaic::test_empty[x2-0-png]", "lib/matplotlib/tests/test_figure.py::TestSubplotMosaic::test_empty[x3-None-png]", "lib/matplotlib/tests/test_figure.py::TestSubplotMosaic::test_empty[x4-SKIP-png]", "lib/matplotlib/tests/test_figure.py::TestSubplotMosaic::test_empty[x5-0-png]", "lib/matplotlib/tests/test_figure.py::TestSubplotMosaic::test_fail_list_of_str", "lib/matplotlib/tests/test_figure.py::TestSubplotMosaic::test_subplot_kw[subplot_kw0-png]", "lib/matplotlib/tests/test_figure.py::TestSubplotMosaic::test_subplot_kw[subplot_kw1-png]", "lib/matplotlib/tests/test_figure.py::TestSubplotMosaic::test_subplot_kw[None-png]", "lib/matplotlib/tests/test_figure.py::TestSubplotMosaic::test_per_subplot_kw[BC-png]", "lib/matplotlib/tests/test_figure.py::TestSubplotMosaic::test_per_subplot_kw[multi_value1-png]", "lib/matplotlib/tests/test_figure.py::TestSubplotMosaic::test_string_parser", "lib/matplotlib/tests/test_figure.py::TestSubplotMosaic::test_per_subplot_kw_expander", "lib/matplotlib/tests/test_figure.py::TestSubplotMosaic::test_extra_per_subplot_kw", "lib/matplotlib/tests/test_figure.py::TestSubplotMosaic::test_single_str_input[AAA\\nBBB-png]", "lib/matplotlib/tests/test_figure.py::TestSubplotMosaic::test_single_str_input[\\nAAA\\nBBB\\n-png]", "lib/matplotlib/tests/test_figure.py::TestSubplotMosaic::test_single_str_input[ABC\\nDEF-png]", "lib/matplotlib/tests/test_figure.py::TestSubplotMosaic::test_fail[x0-(?m)we", "lib/matplotlib/tests/test_figure.py::TestSubplotMosaic::test_fail[x1-There", "lib/matplotlib/tests/test_figure.py::TestSubplotMosaic::test_fail[AAA\\nc\\nBBB-All", "lib/matplotlib/tests/test_figure.py::TestSubplotMosaic::test_fail[x3-All", "lib/matplotlib/tests/test_figure.py::TestSubplotMosaic::test_hashable_keys[png]", "lib/matplotlib/tests/test_figure.py::TestSubplotMosaic::test_user_order[abc]", "lib/matplotlib/tests/test_figure.py::TestSubplotMosaic::test_user_order[cab]", "lib/matplotlib/tests/test_figure.py::TestSubplotMosaic::test_user_order[bca]", "lib/matplotlib/tests/test_figure.py::TestSubplotMosaic::test_user_order[cba]", "lib/matplotlib/tests/test_figure.py::TestSubplotMosaic::test_user_order[acb]", "lib/matplotlib/tests/test_figure.py::TestSubplotMosaic::test_user_order[bac]", "lib/matplotlib/tests/test_figure.py::TestSubplotMosaic::test_nested_user_order", "lib/matplotlib/tests/test_figure.py::TestSubplotMosaic::test_share_all", "lib/matplotlib/tests/test_figure.py::test_reused_gridspec", "lib/matplotlib/tests/test_figure.py::test_subfigure[png]", "lib/matplotlib/tests/test_figure.py::test_subfigure_tightbbox", "lib/matplotlib/tests/test_figure.py::test_subfigure_dpi", "lib/matplotlib/tests/test_figure.py::test_subfigure_ss[png]", "lib/matplotlib/tests/test_figure.py::test_subfigure_double[png]", "lib/matplotlib/tests/test_figure.py::test_subfigure_spanning", "lib/matplotlib/tests/test_figure.py::test_subfigure_ticks", "lib/matplotlib/tests/test_figure.py::test_subfigure_scatter_size[png]", "lib/matplotlib/tests/test_figure.py::test_subfigure_pdf", "lib/matplotlib/tests/test_figure.py::test_add_subplot_kwargs", "lib/matplotlib/tests/test_figure.py::test_add_axes_kwargs", "lib/matplotlib/tests/test_figure.py::test_ginput", "lib/matplotlib/tests/test_figure.py::test_waitforbuttonpress", "lib/matplotlib/tests/test_figure.py::test_kwargs_pass", "lib/matplotlib/tests/test_figure.py::test_rcparams[png]", "lib/matplotlib/tests/test_figure.py::test_deepcopy", "lib/matplotlib/tests/test_figure.py::test_unpickle_with_device_pixel_ratio", "lib/matplotlib/tests/test_figure.py::test_gridspec_no_mutate_input", "lib/matplotlib/tests/test_figure.py::test_savefig_metadata[eps]", "lib/matplotlib/tests/test_figure.py::test_savefig_metadata[pdf]", "lib/matplotlib/tests/test_figure.py::test_savefig_metadata[png]", "lib/matplotlib/tests/test_figure.py::test_savefig_metadata[ps]", "lib/matplotlib/tests/test_figure.py::test_savefig_metadata[svg]", "lib/matplotlib/tests/test_figure.py::test_savefig_metadata[svgz]", "lib/matplotlib/tests/test_figure.py::test_savefig_metadata_error[jpeg]", "lib/matplotlib/tests/test_figure.py::test_savefig_metadata_error[jpg]", "lib/matplotlib/tests/test_figure.py::test_savefig_metadata_error[tif]", "lib/matplotlib/tests/test_figure.py::test_savefig_metadata_error[tiff]", "lib/matplotlib/tests/test_figure.py::test_savefig_metadata_error[webp]", "lib/matplotlib/tests/test_figure.py::test_savefig_metadata_error[raw]", "lib/matplotlib/tests/test_figure.py::test_savefig_metadata_error[rgba]" ]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> Add Figure methods get_suptitle(), get_subxlabel(), get_supylabel() ## PR Summary We had no public API to optain these values. The API is modelled analogous to `Axes.get_title()` / `Axes.get_x/ylabel()`, i.e. returning a string (and not the Text object) and returning an empty string if no text has been set yet. Side remark. It's historic and unfortunate that the setters don't have the `set_` prefix (in contrast to e.g. `set_title()`). Nevertheless `get_*` is the only sane choice for the getters introduced here. ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in lib/matplotlib/figure.py] (definition of FigureBase.get_suptitle:) def get_suptitle(self): """Return the suptitle as string or an empty string if not set.""" (definition of FigureBase.get_supxlabel:) def get_supxlabel(self): """Return the supxlabel as string or an empty string if not set.""" (definition of FigureBase.get_supylabel:) def get_supylabel(self): """Return the supylabel as string or an empty string if not set.""" [end of new definitions in lib/matplotlib/figure.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
a4dca24d04f928a9e614db403c716237446140b2
pvlib__pvlib-python-1705
1,705
pvlib/pvlib-python
0.9
5596be380227cc71ef67fa066683f1edd22606b0
2023-03-23T20:46:35Z
diff --git a/docs/sphinx/source/reference/irradiance/decomposition.rst b/docs/sphinx/source/reference/irradiance/decomposition.rst index f0d1495889..0677d6ac95 100644 --- a/docs/sphinx/source/reference/irradiance/decomposition.rst +++ b/docs/sphinx/source/reference/irradiance/decomposition.rst @@ -15,3 +15,5 @@ DNI estimation models irradiance.boland irradiance.campbell_norman irradiance.gti_dirint + irradiance.louche + diff --git a/docs/sphinx/source/whatsnew/v0.9.6.rst b/docs/sphinx/source/whatsnew/v0.9.6.rst index 9e295dbc3c..6578e6849f 100644 --- a/docs/sphinx/source/whatsnew/v0.9.6.rst +++ b/docs/sphinx/source/whatsnew/v0.9.6.rst @@ -23,6 +23,7 @@ Deprecations Enhancements ~~~~~~~~~~~~ +* Added a new irradiance decomposition model :py:func:`pvlib.irradiance.louche`. (:pull:`1705`) * Add optional encoding parameter to :py:func:`pvlib.iotools.read_tmy3`. (:issue:`1732`, :pull:`1737`) * Added function to retrieve horizon data from PVGIS @@ -79,3 +80,4 @@ Contributors * Andy Lam (:ghuser:`@andylam598`) * :ghuser:`ooprathamm` * Kevin Anderson (:ghuser:`kandersolar`) + diff --git a/pvlib/irradiance.py b/pvlib/irradiance.py index 83527c7604..af983e47b9 100644 --- a/pvlib/irradiance.py +++ b/pvlib/irradiance.py @@ -3117,3 +3117,64 @@ def complete_irradiance(solar_zenith, 'dhi': dhi, 'dni': dni}) return component_sum_df + + +def louche(ghi, solar_zenith, datetime_or_doy, max_zenith=90): + """ + Determine DNI and DHI from GHI using the Louche model. + + Parameters + ---------- + ghi : numeric + Global horizontal irradiance. [W/m^2] + + solar_zenith : numeric + True (not refraction-corrected) zenith angles in decimal + degrees. Angles must be >=0 and <=90. + + datetime_or_doy : numeric, pandas.DatetimeIndex + Day of year or array of days of year e.g. + pd.DatetimeIndex.dayofyear, or pd.DatetimeIndex. + + Returns + ------- + data: OrderedDict or DataFrame + Contains the following keys/columns: + + * ``dni``: the modeled direct normal irradiance in W/m^2. + * ``dhi``: the modeled diffuse horizontal irradiance in + W/m^2. + * ``kt``: Ratio of global to extraterrestrial irradiance + on a horizontal plane. + + References + ------- + .. [1] Louche A, Notton G, Poggi P, Simonnot G. Correlations for direct + normal and global horizontal irradiation on a French Mediterranean site. + Solar Energy 1991;46:261-6. :doi:`10.1016/0038-092X(91)90072-5` + + """ + + I0 = get_extra_radiation(datetime_or_doy) + + Kt = clearness_index(ghi, solar_zenith, I0) + + kb = -10.627*Kt**5 + 15.307*Kt**4 - 5.205 * \ + Kt**3 + 0.994*Kt**2 - 0.059*Kt + 0.002 + dni = kb*I0 + dhi = ghi - dni*tools.cosd(solar_zenith) + + bad_values = (solar_zenith > max_zenith) | (ghi < 0) | (dni < 0) + dni = np.where(bad_values, 0, dni) + # ensure that closure relationship remains valid + dhi = np.where(bad_values, ghi, dhi) + + data = OrderedDict() + data['dni'] = dni + data['dhi'] = dhi + data['kt'] = Kt + + if isinstance(datetime_or_doy, pd.DatetimeIndex): + data = pd.DataFrame(data, index=datetime_or_doy) + + return data
diff --git a/pvlib/tests/test_irradiance.py b/pvlib/tests/test_irradiance.py index cffdd23e40..d0158dad1a 100644 --- a/pvlib/tests/test_irradiance.py +++ b/pvlib/tests/test_irradiance.py @@ -246,6 +246,7 @@ def test_haydavies_components(irrad_data, ephem_data, dni_et): assert_allclose(result['horizon'], expected['horizon'][-1], atol=1e-4) assert isinstance(result, dict) + def test_reindl(irrad_data, ephem_data, dni_et): result = irradiance.reindl( 40, 180, irrad_data['dhi'], irrad_data['dni'], irrad_data['ghi'], @@ -903,8 +904,12 @@ def test_dirindex(times): assert np.allclose(out, expected_out, rtol=tolerance, atol=0, equal_nan=True) tol_dirint = 0.2 - assert np.allclose(out.values, dirint_close_values, rtol=tol_dirint, atol=0, - equal_nan=True) + assert np.allclose( + out.values, + dirint_close_values, + rtol=tol_dirint, + atol=0, + equal_nan=True) def test_dirindex_min_cos_zenith_max_zenith(): @@ -1203,3 +1208,20 @@ def test_complete_irradiance(): dhi=None, dni=i.dni, dni_clear=clearsky.dni) + + +def test_louche(): + + index = pd.DatetimeIndex(['20190101']*3 + ['20190620']*1) + ghi = pd.Series([0, 50, 1000, 1000], index=index) + zenith = pd.Series([91, 85, 10, 10], index=index) + expected = pd.DataFrame(np.array( + [[0, 0, 0], + [130.089669, 38.661938, 0.405724], + [828.498650, 184.088106, 0.718133], + [887.407348, 126.074364, 0.768214]]), + columns=['dni', 'dhi', 'kt'], index=index) + + out = irradiance.louche(ghi, zenith, index) + + assert_frame_equal(out, expected)
diff --git a/docs/sphinx/source/reference/irradiance/decomposition.rst b/docs/sphinx/source/reference/irradiance/decomposition.rst index f0d1495889..0677d6ac95 100644 --- a/docs/sphinx/source/reference/irradiance/decomposition.rst +++ b/docs/sphinx/source/reference/irradiance/decomposition.rst @@ -15,3 +15,5 @@ DNI estimation models irradiance.boland irradiance.campbell_norman irradiance.gti_dirint + irradiance.louche + diff --git a/docs/sphinx/source/whatsnew/v0.9.6.rst b/docs/sphinx/source/whatsnew/v0.9.6.rst index 9e295dbc3c..6578e6849f 100644 --- a/docs/sphinx/source/whatsnew/v0.9.6.rst +++ b/docs/sphinx/source/whatsnew/v0.9.6.rst @@ -23,6 +23,7 @@ Deprecations Enhancements ~~~~~~~~~~~~ +* Added a new irradiance decomposition model :py:func:`pvlib.irradiance.louche`. (:pull:`1705`) * Add optional encoding parameter to :py:func:`pvlib.iotools.read_tmy3`. (:issue:`1732`, :pull:`1737`) * Added function to retrieve horizon data from PVGIS @@ -79,3 +80,4 @@ Contributors * Andy Lam (:ghuser:`@andylam598`) * :ghuser:`ooprathamm` * Kevin Anderson (:ghuser:`kandersolar`) +
[ { "components": [ { "doc": "Determine DNI and DHI from GHI using the Louche model.\n\nParameters\n----------\nghi : numeric\n Global horizontal irradiance. [W/m^2]\n\nsolar_zenith : numeric\n True (not refraction-corrected) zenith angles in decimal\n degrees. Angles must be >=0 and <=90.\n\ndatetime_or_doy : numeric, pandas.DatetimeIndex\n Day of year or array of days of year e.g.\n pd.DatetimeIndex.dayofyear, or pd.DatetimeIndex.\n\nReturns\n-------\ndata: OrderedDict or DataFrame\n Contains the following keys/columns:\n\n * ``dni``: the modeled direct normal irradiance in W/m^2.\n * ``dhi``: the modeled diffuse horizontal irradiance in\n W/m^2.\n * ``kt``: Ratio of global to extraterrestrial irradiance\n on a horizontal plane.\n\nReferences\n-------\n.. [1] Louche A, Notton G, Poggi P, Simonnot G. Correlations for direct\n normal and global horizontal irradiation on a French Mediterranean site.\n Solar Energy 1991;46:261-6. :doi:`10.1016/0038-092X(91)90072-5`", "lines": [ 3122, 3180 ], "name": "louche", "signature": "def louche(ghi, solar_zenith, datetime_or_doy, max_zenith=90):", "type": "function" } ], "file": "pvlib/irradiance.py" } ]
[ "pvlib/tests/test_irradiance.py::test_louche" ]
[ "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-300-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-300.0-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-testval2-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-testval3-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-testval4-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-testval5-expected5]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-testval6-expected6]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-testval7-expected7]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[asce-testval8-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-300-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-300.0-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-testval2-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-testval3-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-testval4-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-testval5-expected5]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-testval6-expected6]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-testval7-expected7]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[spencer-testval8-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-300-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-300.0-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-testval2-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-testval3-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-testval4-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-testval5-expected5]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-testval6-expected6]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-testval7-expected7]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[nrel-testval8-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-300-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-300.0-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-testval2-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-testval3-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-testval4-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-testval5-expected5]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-testval6-expected6]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-testval7-expected7]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation[pyephem-testval8-1383.636203]", "pvlib/tests/test_irradiance.py::test_get_extra_radiation_epoch_year", "pvlib/tests/test_irradiance.py::test_get_extra_radiation_nrel_numba", "pvlib/tests/test_irradiance.py::test_get_extra_radiation_invalid", "pvlib/tests/test_irradiance.py::test_get_ground_diffuse_simple_float", "pvlib/tests/test_irradiance.py::test_get_ground_diffuse_simple_series", "pvlib/tests/test_irradiance.py::test_get_ground_diffuse_albedo_0", "pvlib/tests/test_irradiance.py::test_get_ground_diffuse_albedo_series", "pvlib/tests/test_irradiance.py::test_grounddiffuse_albedo_invalid_surface", "pvlib/tests/test_irradiance.py::test_get_ground_diffuse_albedo_surface", "pvlib/tests/test_irradiance.py::test_isotropic_float", "pvlib/tests/test_irradiance.py::test_isotropic_series", "pvlib/tests/test_irradiance.py::test_klucher_series_float", "pvlib/tests/test_irradiance.py::test_klucher_series", "pvlib/tests/test_irradiance.py::test_haydavies", "pvlib/tests/test_irradiance.py::test_haydavies_components", "pvlib/tests/test_irradiance.py::test_reindl", "pvlib/tests/test_irradiance.py::test_king", "pvlib/tests/test_irradiance.py::test_perez", "pvlib/tests/test_irradiance.py::test_perez_components", "pvlib/tests/test_irradiance.py::test_perez_negative_horizon", "pvlib/tests/test_irradiance.py::test_perez_arrays", "pvlib/tests/test_irradiance.py::test_perez_scalar", "pvlib/tests/test_irradiance.py::test_sky_diffuse_zenith_close_to_90[isotropic]", "pvlib/tests/test_irradiance.py::test_sky_diffuse_zenith_close_to_90[klucher]", "pvlib/tests/test_irradiance.py::test_sky_diffuse_zenith_close_to_90[haydavies]", "pvlib/tests/test_irradiance.py::test_sky_diffuse_zenith_close_to_90[reindl]", "pvlib/tests/test_irradiance.py::test_sky_diffuse_zenith_close_to_90[king]", "pvlib/tests/test_irradiance.py::test_sky_diffuse_zenith_close_to_90[perez]", "pvlib/tests/test_irradiance.py::test_get_sky_diffuse_model_invalid", "pvlib/tests/test_irradiance.py::test_get_sky_diffuse_missing_dni_extra", "pvlib/tests/test_irradiance.py::test_get_sky_diffuse_missing_airmass", "pvlib/tests/test_irradiance.py::test_campbell_norman", "pvlib/tests/test_irradiance.py::test_get_total_irradiance", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_albedo[isotropic]", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_albedo[klucher]", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_albedo[haydavies]", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_albedo[reindl]", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_albedo[king]", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_albedo[perez]", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_scalars[isotropic]", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_scalars[klucher]", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_scalars[haydavies]", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_scalars[reindl]", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_scalars[king]", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_scalars[perez]", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_missing_dni_extra", "pvlib/tests/test_irradiance.py::test_get_total_irradiance_missing_airmass", "pvlib/tests/test_irradiance.py::test_poa_components", "pvlib/tests/test_irradiance.py::test_disc_value[93193-expected0]", "pvlib/tests/test_irradiance.py::test_disc_value[None-expected1]", "pvlib/tests/test_irradiance.py::test_disc_value[101325-expected2]", "pvlib/tests/test_irradiance.py::test_disc_overirradiance", "pvlib/tests/test_irradiance.py::test_disc_min_cos_zenith_max_zenith", "pvlib/tests/test_irradiance.py::test_dirint_value", "pvlib/tests/test_irradiance.py::test_dirint_nans", "pvlib/tests/test_irradiance.py::test_dirint_tdew", "pvlib/tests/test_irradiance.py::test_dirint_no_delta_kt", "pvlib/tests/test_irradiance.py::test_dirint_coeffs", "pvlib/tests/test_irradiance.py::test_dirint_min_cos_zenith_max_zenith", "pvlib/tests/test_irradiance.py::test_gti_dirint", "pvlib/tests/test_irradiance.py::test_erbs", "pvlib/tests/test_irradiance.py::test_boland", "pvlib/tests/test_irradiance.py::test_erbs_min_cos_zenith_max_zenith", "pvlib/tests/test_irradiance.py::test_erbs_all_scalar", "pvlib/tests/test_irradiance.py::test_dirindex", "pvlib/tests/test_irradiance.py::test_dirindex_min_cos_zenith_max_zenith", "pvlib/tests/test_irradiance.py::test_dni", "pvlib/tests/test_irradiance.py::test_aoi_and_aoi_projection[0-0-0-0-0-1]", "pvlib/tests/test_irradiance.py::test_aoi_and_aoi_projection[30-180-30-180-0-1]", "pvlib/tests/test_irradiance.py::test_aoi_and_aoi_projection[30-180-150-0-180--1]", "pvlib/tests/test_irradiance.py::test_aoi_and_aoi_projection[90-0-30-60-75.5224878-0.25]", "pvlib/tests/test_irradiance.py::test_aoi_and_aoi_projection[90-0-30-170-119.4987042--0.4924038]", "pvlib/tests/test_irradiance.py::test_aoi_projection_precision", "pvlib/tests/test_irradiance.py::test_kt_kt_prime_factor", "pvlib/tests/test_irradiance.py::test_clearsky_index", "pvlib/tests/test_irradiance.py::test_clearness_index", "pvlib/tests/test_irradiance.py::test_clearness_index_zenith_independent", "pvlib/tests/test_irradiance.py::test_complete_irradiance" ]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> Implement `pvlib.irradiance.louche` decomposition model - [x] Fulfills pvl_louche from #2 - [x] I am familiar with the [contributing guidelines](https://pvlib-python.readthedocs.io/en/latest/contributing.html) - [x] Tests added - [x] Updates entries in [`docs/sphinx/source/reference`](https://github.com/pvlib/pvlib-python/blob/main/docs/sphinx/source/reference) for API changes. - [x] Adds description and name entries in the appropriate "what's new" file in [`docs/sphinx/source/whatsnew`](https://github.com/pvlib/pvlib-python/tree/main/docs/sphinx/source/whatsnew) for all changes. Includes link to the GitHub Issue with `` :issue:`num` `` or this Pull Request with `` :pull:`num` ``. Includes contributor name and/or GitHub username (link with `` :ghuser:`user` ``). - [x] New code is fully documented. Includes [numpydoc](https://numpydoc.readthedocs.io/en/latest/format.html) compliant docstrings, examples, and comments where necessary. - [x] Pull request is nearly complete and ready for detailed review. - [x] Maintainer: Appropriate GitHub Labels (including `remote-data`) and Milestone are assigned to the Pull Request and linked Issue. <!-- Brief description of the problem and proposed solution (if not already fully described in the issue linked to above): --> ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in pvlib/irradiance.py] (definition of louche:) def louche(ghi, solar_zenith, datetime_or_doy, max_zenith=90): """Determine DNI and DHI from GHI using the Louche model. Parameters ---------- ghi : numeric Global horizontal irradiance. [W/m^2] solar_zenith : numeric True (not refraction-corrected) zenith angles in decimal degrees. Angles must be >=0 and <=90. datetime_or_doy : numeric, pandas.DatetimeIndex Day of year or array of days of year e.g. pd.DatetimeIndex.dayofyear, or pd.DatetimeIndex. Returns ------- data: OrderedDict or DataFrame Contains the following keys/columns: * ``dni``: the modeled direct normal irradiance in W/m^2. * ``dhi``: the modeled diffuse horizontal irradiance in W/m^2. * ``kt``: Ratio of global to extraterrestrial irradiance on a horizontal plane. References ------- .. [1] Louche A, Notton G, Poggi P, Simonnot G. Correlations for direct normal and global horizontal irradiation on a French Mediterranean site. Solar Energy 1991;46:261-6. :doi:`10.1016/0038-092X(91)90072-5`""" [end of new definitions in pvlib/irradiance.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
d53f97e984bfdd268aa92f8bf482ced0edda0110
conan-io__conan-13509
13,509
conan-io/conan
null
03a29d352ae7d68751336fa10846e8b03ded5537
2023-03-23T00:01:46Z
diff --git a/conan/tools/files/__init__.py b/conan/tools/files/__init__.py index 2517002f97d..f47cd2beffd 100644 --- a/conan/tools/files/__init__.py +++ b/conan/tools/files/__init__.py @@ -1,5 +1,6 @@ from conan.tools.files.files import load, save, mkdir, rmdir, rm, ftp_download, download, get, \ - rename, chdir, unzip, replace_in_file, collect_libs, check_md5, check_sha1, check_sha256 + rename, chdir, unzip, replace_in_file, collect_libs, check_md5, check_sha1, check_sha256, \ + move_folder_contents from conan.tools.files.patches import patch, apply_conandata_patches, export_conandata_patches from conan.tools.files.cpp_package import CppPackage diff --git a/conan/tools/files/files.py b/conan/tools/files/files.py index e46e02b2f2f..36453bb30d4 100644 --- a/conan/tools/files/files.py +++ b/conan/tools/files/files.py @@ -544,18 +544,39 @@ def collect_libs(conanfile, folder=None): # TODO: Do NOT document this yet. It is unclear the interface, maybe should be split -def swap_child_folder(parent_folder, child_folder): +def move_folder_contents(src_folder, dst_folder): """ replaces the current folder contents with the contents of one child folder. This is used in the SCM monorepo flow, when it is necessary to use one subproject subfolder to replace the whole cloned git repo + /base-folder /base-folder + /pkg (src folder) /other/<otherfiles> + /other/<otherfiles> /pkg/<pkgfiles> + /pkg/<pkgfiles> <files> + <files> + /siblings + <siblingsfiles> """ - for f in os.listdir(parent_folder): - if f != child_folder: - path = os.path.join(parent_folder, f) - if os.path.isfile(path): - os.remove(path) + # Remove potential "siblings" folders not wanted + src_folder_name = os.path.basename(src_folder) + for f in os.listdir(dst_folder): + if f != src_folder_name: # FIXME: Only works for 1st level subfolder + dst = os.path.join(dst_folder, f) + if os.path.isfile(dst): + os.remove(dst) else: - _internal_rmdir(path) - child = os.path.join(parent_folder, child_folder) - for f in os.listdir(child): - shutil.move(os.path.join(child, f), os.path.join(parent_folder, f)) + _internal_rmdir(dst) + + # Move all the contents + for f in os.listdir(src_folder): + src = os.path.join(src_folder, f) + dst = os.path.join(dst_folder, f) + if not os.path.exists(dst): + shutil.move(src, dst_folder) + else: + for sub_src in os.listdir(src): + shutil.move(os.path.join(src, sub_src), dst) + _internal_rmdir(src) + try: + os.rmdir(src_folder) + except OSError: + pass
diff --git a/conans/test/functional/tools/scm/test_git.py b/conans/test/functional/tools/scm/test_git.py index 0b3d822a33f..a4e873b86a1 100644 --- a/conans/test/functional/tools/scm/test_git.py +++ b/conans/test/functional/tools/scm/test_git.py @@ -6,6 +6,8 @@ import pytest import six +from conans.test.assets.cmake import gen_cmakelists +from conans.test.assets.sources import gen_function_cpp from conans.test.utils.scm import create_local_git_repo, git_add_changes_commit, git_create_bare_repo from conans.test.utils.test_files import temp_folder from conans.test.utils.tools import TestClient @@ -484,8 +486,7 @@ class TestGitMonorepoSCMFlow: import os, shutil from conan import ConanFile from conan.tools.scm import Git - from conan.tools.files import load, update_conandata - from conan.tools.files.files import swap_child_folder + from conan.tools.files import load, update_conandata, move_folder_contents class Pkg(ConanFile): name = "{pkg}" @@ -509,7 +510,8 @@ def source(self): sources = self.conan_data["sources"] git.clone(url=sources["url"], target=".") git.checkout(commit=sources["commit"]) - swap_child_folder(self.source_folder, sources["folder"]) + move_folder_contents(os.path.join(self.source_folder, sources["folder"]), + self.source_folder) def build(self): cmake = os.path.join(self.source_folder, "CMakeLists.txt") @@ -558,6 +560,80 @@ def test_full_scm(self): assert "pkg2/0.1: MYCMAKE-BUILD: mycmake2!" in c2.out assert "pkg2/0.1: MYFILE-BUILD: my2header!" in c2.out + @pytest.mark.tool_cmake + def test_exports_sources_common_code_layout(self): + """ This is a copy of test_exports_sources_common_code_layout in test_in_subfolder.py + but instead of using "exports", trying to implement it with Git features + """ + c = TestClient() + conanfile = textwrap.dedent(""" + import os + from conan import ConanFile + from conan.tools.cmake import cmake_layout, CMake + from conan.tools.files import load, copy, save, update_conandata, move_folder_contents + from conan.tools.scm import Git + + class Pkg(ConanFile): + name = "pkg" + version = "0.1" + settings = "os", "compiler", "build_type", "arch" + generators = "CMakeToolchain" + + def export(self): + git = Git(self) + scm_url, scm_commit = git.get_url_and_commit() + update_conandata(self, {"sources": {"commit": scm_commit, "url": scm_url}}) + + def layout(self): + self.folders.root = ".." + self.folders.subproject = "pkg" + cmake_layout(self) + + def source(self): + git = Git(self) + sources = self.conan_data["sources"] + git.clone(url=sources["url"], target=".") + git.checkout(commit=sources["commit"]) + # Layout is pkg/pkg/<files> and pkg/common/<files> + # Final we want is pkg/<files> and common/<files> + # NOTE: This abs_path is IMPORTANT to avoid the trailing "." + src_folder = os.path.abspath(self.source_folder) + move_folder_contents(src_folder, os.path.dirname(src_folder)) + + def build(self): + cmake = CMake(self) + cmake.configure() + cmake.build() + self.run(os.path.join(self.cpp.build.bindirs[0], "myapp")) + """) + cmake_include = "include(${CMAKE_CURRENT_LIST_DIR}/../common/myutils.cmake)" + c.save({"pkg/conanfile.py": conanfile, + "pkg/app.cpp": gen_function_cpp(name="main", includes=["../common/myheader"], + preprocessor=["MYDEFINE"]), + "pkg/CMakeLists.txt": gen_cmakelists(appsources=["app.cpp"], + custom_content=cmake_include), + "common/myutils.cmake": 'message(STATUS "MYUTILS.CMAKE!")', + "common/myheader.h": '#define MYDEFINE "MYDEFINEVALUE"'}) + c.init_git_repo() + + c.run("create pkg") + assert "MYUTILS.CMAKE!" in c.out + assert "main: Release!" in c.out + assert "MYDEFINE: MYDEFINEVALUE" in c.out + + # Local flow + c.run("install pkg") + c.run("build pkg") + assert "MYUTILS.CMAKE!" in c.out + assert "main: Release!" in c.out + assert "MYDEFINE: MYDEFINEVALUE" in c.out + + c.run("install pkg -s build_type=Debug") + c.run("build pkg") + assert "MYUTILS.CMAKE!" in c.out + assert "main: Debug!" in c.out + assert "MYDEFINE: MYDEFINEVALUE" in c.out + class TestConanFileSubfolder: """verify that we can have a conanfile in a subfolder
[ { "components": [ { "doc": "replaces the current folder contents with the contents of one child folder. This\nis used in the SCM monorepo flow, when it is necessary to use one subproject subfolder\nto replace the whole cloned git repo\n/base-folder /base-folder\n /pkg (src folder) /other/<otherfiles>\n /other/<otherfiles> /pkg/<pkgfiles>\n /pkg/<pkgfiles> <files>\n <files>\n /siblings\n <siblingsfiles>", "lines": [ 547, 582 ], "name": "move_folder_contents", "signature": "def move_folder_contents(src_folder, dst_folder):", "type": "function" } ], "file": "conan/tools/files/files.py" } ]
[ "conans/test/functional/tools/scm/test_git.py::TestGitMonorepoSCMFlow::test_full_scm" ]
[ "conans/test/functional/tools/scm/test_git.py::TestGitBasicCapture::test_capture_commit_local", "conans/test/functional/tools/scm/test_git.py::TestGitBasicCapture::test_capture_remote_url", "conans/test/functional/tools/scm/test_git.py::TestGitBasicCapture::test_capture_remote_pushed_commit", "conans/test/functional/tools/scm/test_git.py::TestGitCaptureSCM::test_capture_commit_local", "conans/test/functional/tools/scm/test_git.py::TestGitCaptureSCM::test_capture_remote_url", "conans/test/functional/tools/scm/test_git.py::TestGitCaptureSCM::test_capture_remote_pushed_commit", "conans/test/functional/tools/scm/test_git.py::TestGitBasicClone::test_clone_checkout", "conans/test/functional/tools/scm/test_git.py::TestGitCloneWithArgs::test_clone_specify_branch_or_tag", "conans/test/functional/tools/scm/test_git.py::TestGitCloneWithArgs::test_clone_invalid_branch_argument", "conans/test/functional/tools/scm/test_git.py::TestGitBasicSCMFlow::test_full_scm", "conans/test/functional/tools/scm/test_git.py::TestGitBasicSCMFlow::test_branch_flow", "conans/test/functional/tools/scm/test_git.py::TestGitBasicSCMFlowSubfolder::test_full_scm", "conans/test/functional/tools/scm/test_git.py::TestConanFileSubfolder::test_conanfile_subfolder", "conans/test/functional/tools/scm/test_git.py::TestConanFileSubfolder::test_git_run", "conans/test/functional/tools/scm/test_git.py::TestGitIncluded::test_git_included", "conans/test/functional/tools/scm/test_git.py::TestGitIncluded::test_git_included_subfolder" ]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> new move_folder_contents() file helper to re-arrange repos Changelog: Feature: New ``move_folder_contents()`` file helper to re-arrange repos folders. Docs: https://github.com/conan-io/docs/pull/3196 Close https://github.com/conan-io/conan/issues/12360 This was already private internal to implement some tests, but tests are a public use case, so it should be made public, I have refactored, improved, and added more tests for this helper. ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in conan/tools/files/files.py] (definition of move_folder_contents:) def move_folder_contents(src_folder, dst_folder): """replaces the current folder contents with the contents of one child folder. This is used in the SCM monorepo flow, when it is necessary to use one subproject subfolder to replace the whole cloned git repo /base-folder /base-folder /pkg (src folder) /other/<otherfiles> /other/<otherfiles> /pkg/<pkgfiles> /pkg/<pkgfiles> <files> <files> /siblings <siblingsfiles>""" [end of new definitions in conan/tools/files/files.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
4a5b19a75db9225316c8cb022a2dfb9705a2af34
conan-io__conan-13354
13,354
conan-io/conan
null
d6058bbb690819ded29eb283cd9329a92aea3d56
2023-03-07T08:38:34Z
diff --git a/conan/api/subapi/config.py b/conan/api/subapi/config.py index 98faa962e73..f0d9c405e47 100644 --- a/conan/api/subapi/config.py +++ b/conan/api/subapi/config.py @@ -21,3 +21,7 @@ def install(self, path_or_url, verify_ssl, config_type=None, args=None, def get(self, name, default=None, check_type=None): app = ConanApp(self.conan_api.cache_folder) return app.cache.new_config.get(name, default=default, check_type=check_type) + + def show(self, pattern): + app = ConanApp(self.conan_api.cache_folder) + return app.cache.new_config.show(pattern) diff --git a/conan/cli/commands/config.py b/conan/cli/commands/config.py index fd7fae5a0a4..b8b58437960 100644 --- a/conan/cli/commands/config.py +++ b/conan/cli/commands/config.py @@ -66,3 +66,14 @@ def config_list(conan_api, parser, subparser, *args): """ parser.parse_args(*args) return BUILT_IN_CONFS + + +@conan_subcommand(formatters={"text": list_text_formatter, "json": default_json_formatter}) +def config_show(conan_api, parser, subparser, *args): + """ + Get the value of the specified conf + """ + subparser.add_argument('pattern', help='Conf item(s) pattern for which to query their value') + args = parser.parse_args(*args) + + return conan_api.config.show(args.pattern) diff --git a/conans/model/conf.py b/conans/model/conf.py index cab702ddf58..c273e70da88 100644 --- a/conans/model/conf.py +++ b/conans/model/conf.py @@ -1,5 +1,6 @@ import re import os +import fnmatch from collections import OrderedDict @@ -306,6 +307,11 @@ def pop(self, conf_name, default=None): self._values.pop(conf_name, None) return value + def show(self, fnpattern, pattern=""): + return {key: self.get(key) + for key in self._values.keys() + if fnmatch.fnmatch(pattern + key, fnpattern)} + def copy(self): c = Conf() c._values = self._values.copy() @@ -475,12 +481,30 @@ def __bool__(self): def get(self, conf_name, default=None, check_type=None): """ - Get the value of the conf name requested and convert it to the [type]-like passed. + Get the value of the conf name requested and convert it to the [type]-like passed. """ pattern, name = self._split_pattern_name(conf_name) return self._pattern_confs.get(pattern, Conf()).get(name, default=default, check_type=check_type) + def show(self, fnpattern): + """ + Get the value of the confs that match the requested pattern + """ + result = {} + + for patter_key, patter_conf in self._pattern_confs.items(): + if patter_key is None: + patter_key = "" + else: + patter_key += ":" + + pattern_values = patter_conf.show(fnpattern, patter_key) + result.update({patter_key + pattern_subkey: pattern_subvalue + for pattern_subkey, pattern_subvalue in pattern_values.items()}) + + return result + def pop(self, conf_name, default=None): """ Remove the conf name passed.
diff --git a/conans/test/integration/command/config_test.py b/conans/test/integration/command/config_test.py index 1ff1e502137..b47bf91ae2c 100644 --- a/conans/test/integration/command/config_test.py +++ b/conans/test/integration/command/config_test.py @@ -108,3 +108,46 @@ def _assert_config_not_exists(path): _assert_config_exists("foo") os.listdir(tc.current_folder) + + +def test_config_show(): + globalconf = textwrap.dedent(""" + tools.build:jobs=42 + tools.files.download:retry_wait=10 + tools.files.download:retry=7 + core.net.http:timeout=30 + core.net.http:max_retries=5 + zlib/*:user.mycategory:retry=True + zlib/*:user.mycategory:foo=0 + zlib/*:user.myothercategory:foo=0 + """) + tc = TestClient() + tc.save_home({"global.conf": globalconf}) + tc.run("config show tools.build:jobs") + assert "42" in tc.out + + tc.run("config show core*") + assert "core.net.http:timeout" in tc.out + assert "30" in tc.out + assert "core.net.http:max_retries" in tc.out + assert "5" in tc.out + + tc.run("config show *retr*") + assert "tools.files.download:retry_wait" in tc.out + assert "tools.files.download:retry" in tc.out + assert "core.net.http:max_retries" in tc.out + assert "zlib/*:user.mycategory:retry" in tc.out + + tc.run("config show zlib*") + assert "zlib/*:user.mycategory:retry" in tc.out + assert "zlib/*:user.mycategory:foo" in tc.out + assert "zlib/*:user.myothercategory:foo" in tc.out + + tc.run("config show zlib/*") + assert "zlib/*:user.mycategory:retry" in tc.out + assert "zlib/*:user.mycategory:foo" in tc.out + assert "zlib/*:user.myothercategory:foo" in tc.out + + tc.run("config show zlib/*:foo") + assert "zlib/*:user.mycategory:foo" in tc.out + assert "zlib/*:user.myothercategory:foo" in tc.out
[ { "components": [ { "doc": "", "lines": [ 25, 27 ], "name": "ConfigAPI.show", "signature": "def show(self, pattern):", "type": "function" } ], "file": "conan/api/subapi/config.py" }, { "components": [ { "doc": "Get the value of the specified conf", "lines": [ 72, 79 ], "name": "config_show", "signature": "def config_show(conan_api, parser, subparser, *args):", "type": "function" } ], "file": "conan/cli/commands/config.py" }, { "components": [ { "doc": "", "lines": [ 310, 313 ], "name": "Conf.show", "signature": "def show(self, fnpattern, pattern=\"\"):", "type": "function" }, { "doc": "Get the value of the confs that match the requested pattern", "lines": [ 490, 506 ], "name": "ConfDefinition.show", "signature": "def show(self, fnpattern):", "type": "function" } ], "file": "conans/model/conf.py" } ]
[ "conans/test/integration/command/config_test.py::test_config_show" ]
[ "conans/test/integration/command/config_test.py::test_missing_subarguments", "conans/test/integration/command/config_test.py::TestConfigHome::test_config_home_default", "conans/test/integration/command/config_test.py::TestConfigHome::test_api_uses_env_var_home", "conans/test/integration/command/config_test.py::test_config_list", "conans/test/integration/command/config_test.py::test_config_install", "conans/test/integration/command/config_test.py::test_config_install_conanignore" ]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> Add `conan config show <conf>` command Changelog: Feature: Add `conan config show <conf>` command. Docs: https://github.com/conan-io/docs/pull/3091 Let's you get the value for any given configuration. This is the simplest implementation, which does not allow you to input additional profiles nor conf values in the cli, so for now just works from the global.conf, but can be extended in the future: - Allow to take into account profiles and conf values supplied by the CLI - Pass a pattern to match the confs against and show the values of every matching ones ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in conan/api/subapi/config.py] (definition of ConfigAPI.show:) def show(self, pattern): [end of new definitions in conan/api/subapi/config.py] [start of new definitions in conan/cli/commands/config.py] (definition of config_show:) def config_show(conan_api, parser, subparser, *args): """Get the value of the specified conf""" [end of new definitions in conan/cli/commands/config.py] [start of new definitions in conans/model/conf.py] (definition of Conf.show:) def show(self, fnpattern, pattern=""): (definition of ConfDefinition.show:) def show(self, fnpattern): """Get the value of the confs that match the requested pattern""" [end of new definitions in conans/model/conf.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
4a5b19a75db9225316c8cb022a2dfb9705a2af34
tobymao__sqlglot-1252
1,252
tobymao/sqlglot
null
c371ac055a7546d8215d3a2acc0d1a64f43a07f1
2023-03-05T07:24:58Z
diff --git a/sqlglot/expressions.py b/sqlglot/expressions.py index c8223c2466..7fdab534ae 100644 --- a/sqlglot/expressions.py +++ b/sqlglot/expressions.py @@ -2407,6 +2407,18 @@ def window(self, *expressions, append=True, dialect=None, copy=True, **opts) -> **opts, ) + def qualify(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: + return _apply_conjunction_builder( + *expressions, + instance=self, + arg="qualify", + append=append, + into=Qualify, + dialect=dialect, + copy=copy, + **opts, + ) + def distinct(self, distinct=True, copy=True) -> Select: """ Set the OFFSET expression. diff --git a/sqlglot/parser.py b/sqlglot/parser.py index 182f895526..445a68ebd1 100644 --- a/sqlglot/parser.py +++ b/sqlglot/parser.py @@ -434,6 +434,7 @@ class Parser(metaclass=_Parser): exp.Having: lambda self: self._parse_having(), exp.With: lambda self: self._parse_with(), exp.Window: lambda self: self._parse_named_window(), + exp.Qualify: lambda self: self._parse_qualify(), "JOIN_TYPE": lambda self: self._parse_join_side_and_kind(), }
diff --git a/tests/test_build.py b/tests/test_build.py index fbfbb62f7e..718e471508 100644 --- a/tests/test_build.py +++ b/tests/test_build.py @@ -504,6 +504,12 @@ def test_build(self): .window("d AS (PARTITION BY g ORDER BY h)"), "SELECT AVG(a) OVER b, MIN(c) OVER d FROM table WINDOW b AS (PARTITION BY e ORDER BY f), d AS (PARTITION BY g ORDER BY h)", ), + ( + lambda: select("*") + .from_("table") + .qualify("row_number() OVER (PARTITION BY a ORDER BY b) = 1"), + "SELECT * FROM table QUALIFY ROW_NUMBER() OVER (PARTITION BY a ORDER BY b) = 1", + ), ]: with self.subTest(sql): self.assertEqual(expression().sql(dialect[0] if dialect else None), sql)
[ { "components": [ { "doc": "", "lines": [ 2410, 2419 ], "name": "Select.qualify", "signature": "def qualify(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:", "type": "function" } ], "file": "sqlglot/expressions.py" } ]
[ "tests/test_build.py::TestBuild::test_build" ]
[]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> Implement qualify builder. Added a qualify builder. Note -- `make check` made a bunch of unrelated formatting changes. ---------- did you have the latest dev environment installed? can you try again with a fresh one ? it's hard for me to tell what's changed I followed these steps: 1. Clone a fresh repo. 2. Create a fresh virtualenv and activate it. 3. Ran `make install-dev; make install-pre-commit; make check`. I am guessing that would create a fresh repo? Let me pick-and-choose each of the diffs to accept so I skip all the formatting ones -- but it looks like `make check` is doing this? </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in sqlglot/expressions.py] (definition of Select.qualify:) def qualify(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: [end of new definitions in sqlglot/expressions.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
ceb42fabad60312699e4b15936aeebac00e22e4d
tfranzel__drf-spectacular-953
953
tfranzel/drf-spectacular
null
43a4474f3c51de32dc553f75abe4c44ea674340d
2023-03-03T14:30:35Z
diff --git a/drf_spectacular/utils.py b/drf_spectacular/utils.py index 03b52b4b..c795b0f1 100644 --- a/drf_spectacular/utils.py +++ b/drf_spectacular/utils.py @@ -64,11 +64,19 @@ def create(self, request, *args, **kwargs): *drf-spectacular* processes the serializer. In those cases you can explicitly state the mapping with ``{'legal': LegalPersonSerializer, ...}``, but it is then your responsibility to have a valid mapping. + + It is also permissible to provide a callable with no parameters for ``serializers``, + such as a lambda that will return an appropriate list or dict when evaluated. """ def __init__( self, component_name: str, - serializers: Union[Sequence[_SerializerType], Dict[str, _SerializerType]], + serializers: Union[ + Sequence[_SerializerType], + Dict[str, _SerializerType], + Callable[[], Sequence[_SerializerType]], + Callable[[], Dict[str, _SerializerType]] + ], resource_type_field_name: Optional[str], many: Optional[bool] = None, ): @@ -88,6 +96,16 @@ def __new__(cls, *args, **kwargs): instance._many = many return instance + @property + def serializers(self): + if callable(self._serializers): + self._serializers = self._serializers() + return self._serializers + + @serializers.setter + def serializers(self, value): + self._serializers = value + @property def data(self): self._trap()
diff --git a/tests/test_polymorphic.py b/tests/test_polymorphic.py index 22e63298..2f5665cf 100644 --- a/tests/test_polymorphic.py +++ b/tests/test_polymorphic.py @@ -93,8 +93,27 @@ def create(self, request, *args, **kwargs): def partial_update(self, request, *args, **kwargs): return Response({}) # pragma: no cover + lambda_poly_proxy = PolymorphicProxySerializer( + component_name='MetaPerson', + serializers=lambda: [LegalPersonSerializer, NaturalPersonSerializer], + resource_type_field_name='type', + ) + + class LambdaPersonViewSet(viewsets.GenericViewSet): + @extend_schema(request=lambda_poly_proxy, responses=lambda_poly_proxy) + def create(self, request, *args, **kwargs): + return Response({}) # pragma: no cover + + @extend_schema( + request=lambda_poly_proxy, + responses=lambda_poly_proxy, + parameters=[OpenApiParameter('id', int, OpenApiParameter.PATH)], + ) + def partial_update(self, request, *args, **kwargs): + return Response({}) # pragma: no cover + -@pytest.mark.parametrize('viewset', [ImplicitPersonViewSet, ExplicitPersonViewSet]) +@pytest.mark.parametrize('viewset', [ImplicitPersonViewSet, ExplicitPersonViewSet, LambdaPersonViewSet]) def test_polymorphic(no_warnings, viewset): assert_schema( generate_schema('persons', viewset),
[ { "components": [ { "doc": "", "lines": [ 106, 107 ], "name": "PolymorphicProxySerializer.serializers", "signature": "def serializers(self, value):", "type": "function" } ], "file": "drf_spectacular/utils.py" } ]
[ "tests/test_polymorphic.py::test_polymorphic[LambdaPersonViewSet]" ]
[ "tests/test_polymorphic.py::test_polymorphic[ImplicitPersonViewSet]", "tests/test_polymorphic.py::test_polymorphic[ExplicitPersonViewSet]", "tests/test_polymorphic.py::test_polymorphic_serializer_as_field_via_extend_schema_field", "tests/test_polymorphic.py::test_polymorphic_serializer_as_method_field_via_extend_schema_field", "tests/test_polymorphic.py::test_stripped_down_polymorphic_serializer", "tests/test_polymorphic.py::test_many_polymorphic_serializer_extend_schema[True]", "tests/test_polymorphic.py::test_many_polymorphic_serializer_extend_schema[False]", "tests/test_polymorphic.py::test_many_polymorphic_proxy_serializer_extend_schema_field[True]", "tests/test_polymorphic.py::test_many_polymorphic_proxy_serializer_extend_schema_field[False]", "tests/test_polymorphic.py::test_polymorphic_proxy_serializer_misusage", "tests/test_polymorphic.py::test_polymorphic_split_request_with_ro_serializer[True]", "tests/test_polymorphic.py::test_polymorphic_split_request_with_ro_serializer[False]", "tests/test_polymorphic.py::test_polymorphic_forced_many_false", "tests/test_polymorphic.py::test_polymorphic_manual_many" ]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> Add option to provide a callable for PolymorphicProxySerializer.serializers Adding a minor feature that we found useful in our own use of `PolymorphicProxySerializer` - the ability to initialize it with a callable (such as a lambda) that returns a list/dict of `serializers` when evaluated, rather than needing to provide the list of serializers up front at declaration time. In our case this was useful because we have a polymorphic schema method field that can return a serializer corresponding to any subclass of a given abstract base model, not all of which may already be defined/imported at the time the field is declared. Being able to provide a callback that can be deferred until the time the schema is actually generated made our implementation easier. ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in drf_spectacular/utils.py] (definition of PolymorphicProxySerializer.serializers:) def serializers(self, value): [end of new definitions in drf_spectacular/utils.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
22b78d6cd3f292ce2952382bcc2b7aefe228a1dd
sympy__sympy-24698
24,698
sympy/sympy
1.12
a767a207cbacc969ea0a65276ecca7855bd79aa5
2023-02-10T11:07:28Z
diff --git a/doc/src/modules/physics/control/lti.rst b/doc/src/modules/physics/control/lti.rst index 5c28064dce51..fcd94ef218c8 100644 --- a/doc/src/modules/physics/control/lti.rst +++ b/doc/src/modules/physics/control/lti.rst @@ -32,3 +32,5 @@ lti :members: .. autofunction:: bilinear + +.. autofunction:: backward_diff diff --git a/sympy/physics/control/__init__.py b/sympy/physics/control/__init__.py index 9bdddcb2e3e9..26d8a87de2f9 100644 --- a/sympy/physics/control/__init__.py +++ b/sympy/physics/control/__init__.py @@ -1,5 +1,5 @@ from .lti import (TransferFunction, Series, MIMOSeries, Parallel, MIMOParallel, - Feedback, MIMOFeedback, TransferFunctionMatrix, bilinear) + Feedback, MIMOFeedback, TransferFunctionMatrix, bilinear, backward_diff) from .control_plots import (pole_zero_numerical_data, pole_zero_plot, step_response_numerical_data, step_response_plot, impulse_response_numerical_data, impulse_response_plot, ramp_response_numerical_data, ramp_response_plot, bode_magnitude_numerical_data, bode_phase_numerical_data, bode_magnitude_plot, @@ -7,7 +7,7 @@ __all__ = ['TransferFunction', 'Series', 'MIMOSeries', 'Parallel', 'MIMOParallel', 'Feedback', 'MIMOFeedback', 'TransferFunctionMatrix','bilinear', - 'pole_zero_numerical_data', + 'backward_diff', 'pole_zero_numerical_data', 'pole_zero_plot', 'step_response_numerical_data', 'step_response_plot', 'impulse_response_numerical_data', 'impulse_response_plot', 'ramp_response_numerical_data', 'ramp_response_plot', diff --git a/sympy/physics/control/lti.py b/sympy/physics/control/lti.py index 74e0b905cd19..aabefcaf6984 100644 --- a/sympy/physics/control/lti.py +++ b/sympy/physics/control/lti.py @@ -22,7 +22,7 @@ from mpmath.libmp.libmpf import prec_to_dps __all__ = ['TransferFunction', 'Series', 'MIMOSeries', 'Parallel', 'MIMOParallel', - 'Feedback', 'MIMOFeedback', 'TransferFunctionMatrix', 'bilinear'] + 'Feedback', 'MIMOFeedback', 'TransferFunctionMatrix', 'bilinear', 'backward_diff'] def _roots(poly, var): @@ -35,8 +35,8 @@ def _roots(poly, var): def bilinear(tf, sample_per): """ - Returns falling coeffs of H(z) from numerator and denominator. - H(z) is the corresponding discretized transfer function, + Returns falling coefficients of H(z) from numerator and denominator. + Where H(z) is the corresponding discretized transfer function, discretized with the bilinear transform method. H(z) is obtained from the continuous transfer function H(s) by substituting s(z) = 2/T * (z-1)/(z+1) into H(s), where T is the @@ -44,7 +44,6 @@ def bilinear(tf, sample_per): Coefficients are falling, i.e. H(z) = (az+b)/(cz+d) is returned as [a, b], [c, d]. - Examples ======== @@ -58,9 +57,10 @@ def bilinear(tf, sample_per): [2*L + R*T, -2*L + R*T] """ - z = Symbol('z') # discrete variable z + T = sample_per # and sample period T s = tf.var + z = s # dummy discrete variable z np = tf.num.as_poly(s).all_coeffs() dp = tf.den.as_poly(s).all_coeffs() @@ -76,6 +76,49 @@ def bilinear(tf, sample_per): return num_coefs, den_coefs +def backward_diff(tf, sample_per): + """ + Returns falling coefficients of H(z) from numerator and denominator. + Where H(z) is the corresponding discretized transfer function, + discretized with the backward difference transform method. + H(z) is obtained from the continuous transfer function H(s) + by substituting s(z) = (z-1)/(T*z) into H(s), where T is the + sample period. + Coefficients are falling, i.e. H(z) = (az+b)/(cz+d) is returned + as [a, b], [c, d]. + + Examples + ======== + + >>> from sympy.physics.control.lti import TransferFunction, backward_diff + >>> from sympy.abc import s, L, R, T + >>> tf = TransferFunction(1, s*L + R, s) + >>> numZ, denZ = backward_diff(tf, T) + >>> numZ + [T, 0] + >>> denZ + [L + R*T, -L] + """ + + T = sample_per # and sample period T + s = tf.var + z = s # dummy discrete variable z + + np = tf.num.as_poly(s).all_coeffs() + dp = tf.den.as_poly(s).all_coeffs() + + # The next line results from multiplying H(z) with z^N/z^N + + N = max(len(np), len(dp)) - 1 + num = Add(*[ T**(N-i)*c*(z-1)**i*(z)**(N-i) for c, i in zip(np[::-1], range(len(np))) ]) + den = Add(*[ T**(N-i)*c*(z-1)**i*(z)**(N-i) for c, i in zip(dp[::-1], range(len(dp))) ]) + + num_coefs = num.as_poly(z).all_coeffs() + den_coefs = den.as_poly(z).all_coeffs() + + return num_coefs, den_coefs + + class LinearTimeInvariant(Basic, EvalfMixin): """A common class for all the Linear Time-Invariant Dynamical Systems."""
diff --git a/sympy/physics/control/tests/test_lti.py b/sympy/physics/control/tests/test_lti.py index eeea0d4638c4..5d0f4b67e28c 100644 --- a/sympy/physics/control/tests/test_lti.py +++ b/sympy/physics/control/tests/test_lti.py @@ -14,7 +14,8 @@ from sympy.core.containers import Tuple from sympy.matrices import ImmutableMatrix, Matrix from sympy.physics.control import (TransferFunction, Series, Parallel, - Feedback, TransferFunctionMatrix, MIMOSeries, MIMOParallel, MIMOFeedback, bilinear) + Feedback, TransferFunctionMatrix, MIMOSeries, MIMOParallel, MIMOFeedback, + bilinear, backward_diff) from sympy.testing.pytest import raises a, x, b, s, g, d, p, k, a0, a1, a2, b0, b1, b2, tau, zeta, wn, T = symbols('a, x, b, s, g, d, p, k,\ @@ -1231,3 +1232,14 @@ def test_TransferFunction_bilinear(): tf_test_manual = TransferFunction(s*T+T, s*(T*b+2*a)+T*b-2*a, s) assert S.Zero == (tf_test_bilinear-tf_test_manual).simplify().num + +def test_TransferFunction_backward_diff(): + # simple transfer function, e.g. ohms law + tf = TransferFunction(1, a*s+b, s) + numZ, denZ = backward_diff(tf, T) + # discretized transfer function with coefs from tf.bilinear() + tf_test_bilinear = TransferFunction(s*numZ[0]+numZ[1], s*denZ[0]+denZ[1], s) + # corresponding tf with manually calculated coefs + tf_test_manual = TransferFunction(s*T, s*(T*b+a)-a, s) + + assert S.Zero == (tf_test_bilinear-tf_test_manual).simplify().num
diff --git a/doc/src/modules/physics/control/lti.rst b/doc/src/modules/physics/control/lti.rst index 5c28064dce51..fcd94ef218c8 100644 --- a/doc/src/modules/physics/control/lti.rst +++ b/doc/src/modules/physics/control/lti.rst @@ -32,3 +32,5 @@ lti :members: .. autofunction:: bilinear + +.. autofunction:: backward_diff
[ { "components": [ { "doc": "Returns falling coefficients of H(z) from numerator and denominator.\nWhere H(z) is the corresponding discretized transfer function,\ndiscretized with the backward difference transform method.\nH(z) is obtained from the continuous transfer function H(s)\nby substituting s(z) = (z-1)/(T*z) into H(s), where T is the\nsample period.\nCoefficients are falling, i.e. H(z) = (az+b)/(cz+d) is returned\nas [a, b], [c, d].\n\nExamples\n========\n\n>>> from sympy.physics.control.lti import TransferFunction, backward_diff\n>>> from sympy.abc import s, L, R, T\n>>> tf = TransferFunction(1, s*L + R, s)\n>>> numZ, denZ = backward_diff(tf, T)\n>>> numZ\n[T, 0]\n>>> denZ\n[L + R*T, -L]", "lines": [ 79, 119 ], "name": "backward_diff", "signature": "def backward_diff(tf, sample_per):", "type": "function" } ], "file": "sympy/physics/control/lti.py" } ]
[ "test_TransferFunction_construction", "test_TransferFunction_functions", "test_TransferFunction_addition_and_subtraction", "test_TransferFunction_multiplication_and_division", "test_TransferFunction_is_proper", "test_TransferFunction_is_strictly_proper", "test_TransferFunction_is_biproper", "test_Series_construction", "test_MIMOSeries_construction", "test_Series_functions", "test_MIMOSeries_functions", "test_Parallel_construction", "test_MIMOParallel_construction", "test_Parallel_functions", "test_MIMOParallel_functions", "test_Feedback_construction", "test_Feedback_functions", "test_MIMOFeedback_construction", "test_MIMOFeedback_errors", "test_MIMOFeedback_functions", "test_TransferFunctionMatrix_construction", "test_TransferFunctionMatrix_functions", "test_TransferFunction_bilinear" ]
[]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> backward_diff discretization of cont. transfer function # Added backward difference discretization method to physics.control.lti #### References to other Issues or PRs It is a 1 to 1 extension of [PR 24558](https://github.com/sympy/sympy/pull/24558) #### Brief description of what is fixed or changed Added function ``` backward_diff(tf, sample_per) ``` In full analogy of ``` bilinear(tf, sample_per) ``` In practical use of contiuous transfer function $H(s)$ (corresponding to differential eq.)one eventually needs the dicsretized version $H(z)$ (corresponding to difference eq.). * bilinear renders coefficients for trapezoidal integration scheme * backward_diff renders coefficients for backward difference integration scheme Both methdos preserve the stability of the continuous input transfer function. #### Other comments SymPy would obtain more than one symbolic discretizatin methods of continuous transfer functions. As the numerical counterparts from the scientific computing with python eco system https://python-control.readthedocs.io/en/latest/generated/control.sample_system.html https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.cont2discrete.html#scipy.signal.cont2discrete #### Release Notes <!-- BEGIN RELEASE NOTES --> NO ENTRY <!-- END RELEASE NOTES --> ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in sympy/physics/control/lti.py] (definition of backward_diff:) def backward_diff(tf, sample_per): """Returns falling coefficients of H(z) from numerator and denominator. Where H(z) is the corresponding discretized transfer function, discretized with the backward difference transform method. H(z) is obtained from the continuous transfer function H(s) by substituting s(z) = (z-1)/(T*z) into H(s), where T is the sample period. Coefficients are falling, i.e. H(z) = (az+b)/(cz+d) is returned as [a, b], [c, d]. Examples ======== >>> from sympy.physics.control.lti import TransferFunction, backward_diff >>> from sympy.abc import s, L, R, T >>> tf = TransferFunction(1, s*L + R, s) >>> numZ, denZ = backward_diff(tf, T) >>> numZ [T, 0] >>> denZ [L + R*T, -L]""" [end of new definitions in sympy/physics/control/lti.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
22520ed5f4a9b2b6c4b6b314b4748878f1b4b662
scrapy__scrapy-5821
5,821
scrapy/scrapy
null
b337c986ca1188f4b26d30c9ae4bb7ff457ed505
2023-02-01T02:18:00Z
diff --git a/scrapy/settings/__init__.py b/scrapy/settings/__init__.py index fde8fdde424..a3b849f7b2f 100644 --- a/scrapy/settings/__init__.py +++ b/scrapy/settings/__init__.py @@ -293,6 +293,13 @@ def set(self, name, value, priority="project"): else: self.attributes[name].set(value, priority) + def setdefault(self, name, default=None, priority="project"): + if name not in self: + self.set(name, default, priority) + return default + + return self.attributes[name].value + def setdict(self, values, priority="project"): self.update(values, priority)
diff --git a/tests/test_settings/__init__.py b/tests/test_settings/__init__.py index 2a3b2d529dc..cb948c84c69 100644 --- a/tests/test_settings/__init__.py +++ b/tests/test_settings/__init__.py @@ -65,6 +65,19 @@ class BaseSettingsTest(unittest.TestCase): def setUp(self): self.settings = BaseSettings() + def test_setdefault_not_existing_value(self): + settings = BaseSettings() + value = settings.setdefault("TEST_OPTION", "value") + self.assertEqual(settings["TEST_OPTION"], "value") + self.assertEqual(value, "value") + self.assertIsNotNone(value) + + def test_setdefault_existing_value(self): + settings = BaseSettings({"TEST_OPTION": "value"}) + value = settings.setdefault("TEST_OPTION", None) + self.assertEqual(settings["TEST_OPTION"], "value") + self.assertEqual(value, "value") + def test_set_new_attribute(self): self.settings.set("TEST_OPTION", "value", 0) self.assertIn("TEST_OPTION", self.settings.attributes)
[ { "components": [ { "doc": "", "lines": [ 296, 301 ], "name": "BaseSettings.setdefault", "signature": "def setdefault(self, name, default=None, priority=\"project\"):", "type": "function" } ], "file": "scrapy/settings/__init__.py" } ]
[ "tests/test_settings/__init__.py::BaseSettingsTest::test_setdefault_not_existing_value" ]
[ "tests/test_settings/__init__.py::SettingsGlobalFuncsTest::test_get_settings_priority", "tests/test_settings/__init__.py::SettingsAttributeTest::test_overwrite_basesettings", "tests/test_settings/__init__.py::SettingsAttributeTest::test_repr", "tests/test_settings/__init__.py::SettingsAttributeTest::test_set_equal_priority", "tests/test_settings/__init__.py::SettingsAttributeTest::test_set_greater_priority", "tests/test_settings/__init__.py::SettingsAttributeTest::test_set_less_priority", "tests/test_settings/__init__.py::BaseSettingsTest::test_copy", "tests/test_settings/__init__.py::BaseSettingsTest::test_copy_to_dict", "tests/test_settings/__init__.py::BaseSettingsTest::test_delete", "tests/test_settings/__init__.py::BaseSettingsTest::test_freeze", "tests/test_settings/__init__.py::BaseSettingsTest::test_frozencopy", "tests/test_settings/__init__.py::BaseSettingsTest::test_get", "tests/test_settings/__init__.py::BaseSettingsTest::test_getpriority", "tests/test_settings/__init__.py::BaseSettingsTest::test_getwithbase", "tests/test_settings/__init__.py::BaseSettingsTest::test_maxpriority", "tests/test_settings/__init__.py::BaseSettingsTest::test_set_calls_settings_attributes_methods_on_update", "tests/test_settings/__init__.py::BaseSettingsTest::test_set_instance_identity_on_update", "tests/test_settings/__init__.py::BaseSettingsTest::test_set_new_attribute", "tests/test_settings/__init__.py::BaseSettingsTest::test_set_settingsattribute", "tests/test_settings/__init__.py::BaseSettingsTest::test_setdefault_existing_value", "tests/test_settings/__init__.py::BaseSettingsTest::test_setdict_alias", "tests/test_settings/__init__.py::BaseSettingsTest::test_setitem", "tests/test_settings/__init__.py::BaseSettingsTest::test_setmodule_alias", "tests/test_settings/__init__.py::BaseSettingsTest::test_setmodule_by_path", "tests/test_settings/__init__.py::BaseSettingsTest::test_setmodule_only_load_uppercase_vars", "tests/test_settings/__init__.py::BaseSettingsTest::test_update", "tests/test_settings/__init__.py::BaseSettingsTest::test_update_jsonstring", "tests/test_settings/__init__.py::SettingsTest::test_autopromote_dicts", "tests/test_settings/__init__.py::SettingsTest::test_getdict_autodegrade_basesettings", "tests/test_settings/__init__.py::SettingsTest::test_initial_defaults", "tests/test_settings/__init__.py::SettingsTest::test_initial_values", "tests/test_settings/__init__.py::SettingsTest::test_passing_objects_as_values" ]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> Added `setdefault` to `BaseSettings` Added the `setdefault` method to the `BaseSettings` class. Now `setdefault` works as expected, if the _key_ does not exist in `BaseSettings` then this _key_ will be added and _default value_ will be assigned to it and this _value_ will be returned. For example: ```python from scrapy.settings import BaseSettings settings = BaseSettings() # 'some_key' does not exist in BaseSettings, so it returns 'default_value' print(settings.setdefault("some_key", "default_value")) # 'some_key' now gets 'default_value' print(settings.get("some_key")) ``` Closes https://github.com/scrapy/scrapy/issues/5811 ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in scrapy/settings/__init__.py] (definition of BaseSettings.setdefault:) def setdefault(self, name, default=None, priority="project"): [end of new definitions in scrapy/settings/__init__.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
57a5460529ff71c42e4d0381265b1b512b1eb09b
conan-io__conan-12980
12,980
conan-io/conan
null
7931acac1b4627f22bc9f3db5cc57d29ddfa16ac
2023-01-26T00:38:06Z
diff --git a/conans/client/cache/cache.py b/conans/client/cache/cache.py index c29f087bb17..7e6f0bb7804 100644 --- a/conans/client/cache/cache.py +++ b/conans/client/cache/cache.py @@ -2,6 +2,7 @@ import platform from typing import List +import yaml from jinja2 import Template @@ -10,6 +11,7 @@ from conans.client.cache.remote_registry import RemoteRegistry from conans.client.conf import default_settings_yml from conans.client.store.localdb import LocalDB +from conans.errors import ConanException from conans.model.conf import ConfDefinition from conans.model.package_ref import PkgReference from conans.model.recipe_ref import RecipeReference @@ -202,8 +204,37 @@ def settings(self): """Returns {setting: [value, ...]} defining all the possible settings without values""" self.initialize_settings() - content = load(self.settings_path) - return Settings.loads(content) + + def _load_settings(path): + try: + return yaml.safe_load(load(path)) or {} + except yaml.YAMLError as ye: + raise ConanException("Invalid settings.yml format: {}".format(ye)) + + settings = _load_settings(self.settings_path) + user_settings_file = os.path.join(self.cache_folder, "settings_user.yml") + if os.path.exists(user_settings_file): + settings_user = _load_settings(user_settings_file) + + def appending_recursive_dict_update(d, u): + # Not the same behavior as conandata_update, because this append lists + for k, v in u.items(): + if isinstance(v, list): + current = d.get(k) or [] + d[k] = current + [value for value in v if value not in current] + elif isinstance(v, dict): + current = d.get(k) or {} + d[k] = appending_recursive_dict_update(current, v) + else: + d[k] = v + return d + + appending_recursive_dict_update(settings, settings_user) + + try: + return Settings(settings) + except AttributeError as e: + raise ConanException("Invalid settings.yml format: {}".format(e)) def initialize_settings(self): # TODO: This is called by ConfigAPI.init(), maybe move everything there?
diff --git a/conans/test/integration/settings/test_settings_user.py b/conans/test/integration/settings/test_settings_user.py new file mode 100644 index 00000000000..e911b14669f --- /dev/null +++ b/conans/test/integration/settings/test_settings_user.py @@ -0,0 +1,54 @@ +import os +import textwrap + +from conans.test.assets.genconanfile import GenConanfile +from conans.test.utils.tools import TestClient +from conans.util.files import save + + +def test_settings_user(): + c = TestClient() + settings_user = textwrap.dedent("""\ + os: + Windows: + subsystem: [new_sub] + Linux: + new_versions: ["a", "b", "c"] + new_os: + new_global: ["42", "21"] + """) + save(os.path.join(c.cache_folder, "settings_user.yml"), settings_user) + c.save({"conanfile.py": GenConanfile().with_settings("os").with_settings("new_global")}) + # New settings are there + c.run("install . -s os=Windows -s os.subsystem=new_sub -s new_global=42") + assert "new_global=42" in c.out + assert "os.subsystem=new_sub" in c.out + # Existing values of subsystem are still there + c.run("install . -s os=Windows -s os.subsystem=msys2 -s new_global=42") + assert "new_global=42" in c.out + assert "os.subsystem=msys2" in c.out + # Completely new values, not appended, but new, are there + c.run("install . -s os=Linux -s os.new_versions=a -s new_global=42") + assert "new_global=42" in c.out + assert "os.new_versions=a" in c.out + # Existing values of OSs are also there + c.run("install . -s os=Macos -s new_global=42") + assert "os=Macos" in c.out + assert "new_global=42" in c.out + + +def test_settings_user_subdict(): + c = TestClient() + settings_user = textwrap.dedent("""\ + other_new: + other1: + other2: + version: [1, 2, 3] + """) + save(os.path.join(c.cache_folder, "settings_user.yml"), settings_user) + c.save({"conanfile.py": GenConanfile().with_settings("other_new")}) + c.run("install . -s other_new=other1") + assert "other_new=other1" in c.out + c.run("install . -s other_new=other2 -s other_new.version=2") + assert "other_new=other2" in c.out + assert "other_new.version=2" in c.out
[ { "components": [ { "doc": "", "lines": [ 208, 212 ], "name": "ClientCache.settings._load_settings", "signature": "def _load_settings(path):", "type": "function" }, { "doc": "", "lines": [ 219, 230 ], "name": "ClientCache.settings.appending_recursive_dict_update", "signature": "def appending_recursive_dict_update(d, u):", "type": "function" } ], "file": "conans/client/cache/cache.py" } ]
[ "conans/test/integration/settings/test_settings_user.py::test_settings_user", "conans/test/integration/settings/test_settings_user.py::test_settings_user_subdict" ]
[]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> [develop2] Propose new settings_user.yml Changelog: Feature: Users can define their own settings in `settings_user.yml` that will be merged with the Conan `settings.yml`. Close https://github.com/conan-io/conan/issues/8261 Close https://github.com/conan-io/conan/issues/12422 The main blocker for https://github.com/conan-io/conan/issues/8261 was the idea that it is necessary to do the round-trip for the ``yml`` file. It seems that is more doable to update the in-memory dictionaries, this is a proof of concept. ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in conans/client/cache/cache.py] (definition of ClientCache.settings._load_settings:) def _load_settings(path): (definition of ClientCache.settings.appending_recursive_dict_update:) def appending_recursive_dict_update(d, u): [end of new definitions in conans/client/cache/cache.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
4a5b19a75db9225316c8cb022a2dfb9705a2af34
huggingface__accelerate-991
991
huggingface/accelerate
null
5858ac62b4546547fa69ffbf9a7f8bd1d1b1f43c
2023-01-19T20:16:40Z
diff --git a/src/accelerate/accelerator.py b/src/accelerate/accelerator.py index 7075c4dcdb6..ec29ac07bce 100644 --- a/src/accelerate/accelerator.py +++ b/src/accelerate/accelerator.py @@ -18,11 +18,13 @@ import shutil import sys import warnings +from collections import OrderedDict from contextlib import contextmanager from functools import wraps -from typing import List, Optional, Union +from typing import Callable, List, Optional, Union import torch +import torch.utils.hooks as hooks from .checkpointing import load_accelerator_state, load_custom_state, save_accelerator_state, save_custom_state from .data_loader import DataLoaderDispatcher, prepare_data_loader @@ -403,6 +405,10 @@ def __init__( self._dataloaders = [] self._custom_objects = [] + # Hooks + self._load_model_state_pre_hook = OrderedDict() + self._save_model_state_pre_hook = OrderedDict() + # RNG Types self.rng_types = rng_types if self.rng_types is None: @@ -1613,6 +1619,38 @@ def save(self, obj, f): """ save(obj, f) + def register_save_state_pre_hook(self, hook: Callable[..., None]) -> hooks.RemovableHandle: + """ + Registers a pre hook to be run before `save_checkpoint` is called in [`Accelerator.save_state`]. + + Args: + hook (`Callable`): + A function to be called in [`Accelerator.save_state`] before `save_checkpoint`. + + The hook should have the following signature: + + `hook(models: List[torch.nn.Module], weights: List[Dict[str, torch.Tensor]], input_dir: str) -> None` + + The `models` argument are the models as saved in the accelerator state under `accelerator._models`, `weigths` + argument are the state dicts of the `models`, and the `input_dir` argument is the `input_dir` argument passed + to [`Accelerator.load_state`]. + + <Tip> + + Should only be used in conjunction with [`Accelerator.register_load_state_pre_hook`]. Can be useful to save + configurations in addition to model weights. Can also be used to overwrite model saving with a customized + method. In this case, make sure to remove already loaded weights from the weights list. + + </Tip> + + Returns: + `torch.utils.hooks.RemovableHandle`: a handle that can be used to remove the added hook by calling + `handle.remove()` + """ + handle = hooks.RemovableHandle(self._save_model_state_pre_hook) + self._save_model_state_pre_hook[handle.id] = hook + return handle + def save_state(self, output_dir: str = None, **save_model_func_kwargs): """ Saves the current states of the model, optimizer, scaler, RNG generators, and registered objects to a folder. @@ -1699,6 +1737,11 @@ def save_state(self, output_dir: str = None, **save_model_func_kwargs): elif self.distributed_type not in [DistributedType.MEGATRON_LM]: schedulers = self._schedulers + # Call model loading hooks that might have been registered with + # accelerator.register_model_state_hook + for hook in self._save_model_state_pre_hook.values(): + hook(self._models, weights, output_dir) + save_location = save_accelerator_state( output_dir, weights, optimizers, schedulers, self.state.process_index, self.scaler ) @@ -1707,6 +1750,37 @@ def save_state(self, output_dir: str = None, **save_model_func_kwargs): self.project_configuration.iteration += 1 return save_location + def register_load_state_pre_hook(self, hook: Callable[..., None]) -> hooks.RemovableHandle: + """ + Registers a pre hook to be run before [`load_checkpoint`] is called in [`Accelerator.load_state`]. + + Args: + hook (`Callable`): + A function to be called in [`Accelerator.load_state`] before `load_checkpoint`. + + The hook should have the following signature: + + `hook(models: List[torch.nn.Module], input_dir: str) -> None` + + The `models` argument are the models as saved in the accelerator state under `accelerator._models`, and the + `input_dir` argument is the `input_dir` argument passed to [`Accelerator.load_state`]. + + <Tip> + + Should only be used in conjunction with [`Accelerator.register_save_state_pre_hook`]. Can be useful to load + configurations in addition to model weights. Can also be used to overwrite model loading with a customized + method. In this case, make sure to remove already loaded models from the models list. + + </Tip> + + Returns: + `torch.utils.hooks.RemovableHandle`: a handle that can be used to remove the added hook by calling + `handle.remove()` + """ + handle = hooks.RemovableHandle(self._load_model_state_pre_hook) + self._load_model_state_pre_hook[handle.id] = hook + return handle + def load_state(self, input_dir: str, **load_model_func_kwargs): """ Loads the current states of the model, optimizer, scaler, RNG generators, and registered objects. @@ -1769,6 +1843,11 @@ def load_state(self, input_dir: str, **load_model_func_kwargs): elif self.distributed_type not in [DistributedType.MEGATRON_LM]: schedulers = self._schedulers + # Call model loading hooks that might have been registered with + # accelerator.register_model_state_hook + for hook in self._load_model_state_pre_hook.values(): + hook(models, input_dir) + load_accelerator_state( input_dir, models, optimizers, schedulers, self.state.process_index, self.scaler, **load_model_func_kwargs )
diff --git a/tests/test_accelerator.py b/tests/test_accelerator.py index 19d6c1655b4..511d4daae62 100644 --- a/tests/test_accelerator.py +++ b/tests/test_accelerator.py @@ -1,3 +1,6 @@ +import json +import os +import tempfile import unittest import torch @@ -17,6 +20,15 @@ def create_components(): return model, optimizer, scheduler, train_dl, valid_dl +def get_signature(model): + return (model.weight.abs().sum() + model.bias.abs().sum()).item() + + +def load_random_weights(model): + state = torch.nn.Linear(*tuple(model.weight.T.shape)).state_dict() + model.load_state_dict(state) + + class AcceleratorTester(unittest.TestCase): def test_prepared_objects_are_referenced(self): accelerator = Accelerator() @@ -49,3 +61,83 @@ def test_free_memory_dereferences_prepared_components(self): self.assertTrue(len(accelerator._schedulers) == 0) self.assertTrue(len(accelerator._dataloaders) == 0) AcceleratorState._reset_state() + + def test_save_load_model(self): + accelerator = Accelerator() + model, optimizer, scheduler, train_dl, valid_dl = create_components() + accelerator.prepare(model, optimizer, scheduler, train_dl, valid_dl) + + model_signature = get_signature(model) + + with tempfile.TemporaryDirectory() as tmpdirname: + accelerator.save_state(tmpdirname) + + # make sure random weights don't match + load_random_weights(model) + self.assertTrue(abs(model_signature - get_signature(model)) > 1e-3) + + # make sure loaded weights match + accelerator.load_state(tmpdirname) + self.assertTrue(abs(model_signature - get_signature(model)) < 1e-3) + + def test_save_load_model_with_hooks(self): + accelerator = Accelerator() + model, optimizer, scheduler, train_dl, valid_dl = create_components() + accelerator.prepare(model, optimizer, scheduler, train_dl, valid_dl) + + model_signature = get_signature(model) + + # saving hook + def save_config(models, weights, output_dir): + config = {"class_name": models[0].__class__.__name__} + + with open(os.path.join(output_dir, "data.json"), "w") as f: + json.dump(config, f) + + # loading hook + def load_config(models, input_dir): + with open(os.path.join(input_dir, "data.json"), "r") as f: + config = json.load(f) + + models[0].class_name = config["class_name"] + + save_hook = accelerator.register_save_state_pre_hook(save_config) + load_hook = accelerator.register_load_state_pre_hook(load_config) + + with tempfile.TemporaryDirectory() as tmpdirname: + accelerator.save_state(tmpdirname) + + # make sure random weights don't match with hooks + load_random_weights(model) + self.assertTrue(abs(model_signature - get_signature(model)) > 1e-3) + + # random class name to verify correct one is loaded + model.class_name = "random" + + # make sure loaded weights match with hooks + accelerator.load_state(tmpdirname) + self.assertTrue(abs(model_signature - get_signature(model)) < 1e-3) + + # mode.class_name is loaded from config + self.assertTrue(model.class_name == model.__class__.__name__) + + # remove hooks + save_hook.remove() + load_hook.remove() + + with tempfile.TemporaryDirectory() as tmpdirname: + accelerator.save_state(tmpdirname) + + # make sure random weights don't match with hooks removed + load_random_weights(model) + self.assertTrue(abs(model_signature - get_signature(model)) > 1e-3) + + # random class name to verify correct one is loaded + model.class_name = "random" + + # make sure loaded weights match with hooks removed + accelerator.load_state(tmpdirname) + self.assertTrue(abs(model_signature - get_signature(model)) < 1e-3) + + # mode.class_name is NOT loaded from config + self.assertTrue(model.class_name != model.__class__.__name__)
[ { "components": [ { "doc": "Registers a pre hook to be run before `save_checkpoint` is called in [`Accelerator.save_state`].\n\nArgs:\n hook (`Callable`):\n A function to be called in [`Accelerator.save_state`] before `save_checkpoint`.\n\nThe hook should have the following signature:\n\n`hook(models: List[torch.nn.Module], weights: List[Dict[str, torch.Tensor]], input_dir: str) -> None`\n\nThe `models` argument are the models as saved in the accelerator state under `accelerator._models`, `weigths`\nargument are the state dicts of the `models`, and the `input_dir` argument is the `input_dir` argument passed\nto [`Accelerator.load_state`].\n\n<Tip>\n\nShould only be used in conjunction with [`Accelerator.register_load_state_pre_hook`]. Can be useful to save\nconfigurations in addition to model weights. Can also be used to overwrite model saving with a customized\nmethod. In this case, make sure to remove already loaded weights from the weights list.\n\n</Tip>\n\nReturns:\n `torch.utils.hooks.RemovableHandle`: a handle that can be used to remove the added hook by calling\n `handle.remove()`", "lines": [ 1622, 1652 ], "name": "Accelerator.register_save_state_pre_hook", "signature": "def register_save_state_pre_hook(self, hook: Callable[..., None]) -> hooks.RemovableHandle:", "type": "function" }, { "doc": "Registers a pre hook to be run before [`load_checkpoint`] is called in [`Accelerator.load_state`].\n\nArgs:\n hook (`Callable`):\n A function to be called in [`Accelerator.load_state`] before `load_checkpoint`.\n\nThe hook should have the following signature:\n\n`hook(models: List[torch.nn.Module], input_dir: str) -> None`\n\nThe `models` argument are the models as saved in the accelerator state under `accelerator._models`, and the\n`input_dir` argument is the `input_dir` argument passed to [`Accelerator.load_state`].\n\n<Tip>\n\nShould only be used in conjunction with [`Accelerator.register_save_state_pre_hook`]. Can be useful to load\nconfigurations in addition to model weights. Can also be used to overwrite model loading with a customized\nmethod. In this case, make sure to remove already loaded models from the models list.\n\n</Tip>\n\nReturns:\n `torch.utils.hooks.RemovableHandle`: a handle that can be used to remove the added hook by calling\n `handle.remove()`", "lines": [ 1753, 1782 ], "name": "Accelerator.register_load_state_pre_hook", "signature": "def register_load_state_pre_hook(self, hook: Callable[..., None]) -> hooks.RemovableHandle:", "type": "function" } ], "file": "src/accelerate/accelerator.py" } ]
[ "tests/test_accelerator.py::AcceleratorTester::test_save_load_model_with_hooks" ]
[ "tests/test_accelerator.py::AcceleratorTester::test_free_memory_dereferences_prepared_components", "tests/test_accelerator.py::AcceleratorTester::test_prepared_objects_are_referenced", "tests/test_accelerator.py::AcceleratorTester::test_save_load_model" ]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> Saving and loading state hooks With this design we would have the necessary freedom to save & load models as wished in `diffusers`. Possible solution to: https://github.com/huggingface/accelerate/issues/976 The idea would be for loading: - loop over the `models` and if a certain type of model, e.g. UNet, we call `from_pretrained(...)` and remove it from the list so it's not called after. For saving: - loop over the passed `self._models` and passed `weights` and if `self_models` if of certain type (e.g. UNet) we call `save_pretrained(...)` and remove only from the weights list so it's not called after. Design is heavily inspired by the hooks in: https://pytorch.org/docs/stable/_modules/torch/nn/modules/module.html#Module If this is ok, happy to write tests and better docs and try it out. cc @sgugger @pcuenca ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in src/accelerate/accelerator.py] (definition of Accelerator.register_save_state_pre_hook:) def register_save_state_pre_hook(self, hook: Callable[..., None]) -> hooks.RemovableHandle: """Registers a pre hook to be run before `save_checkpoint` is called in [`Accelerator.save_state`]. Args: hook (`Callable`): A function to be called in [`Accelerator.save_state`] before `save_checkpoint`. The hook should have the following signature: `hook(models: List[torch.nn.Module], weights: List[Dict[str, torch.Tensor]], input_dir: str) -> None` The `models` argument are the models as saved in the accelerator state under `accelerator._models`, `weigths` argument are the state dicts of the `models`, and the `input_dir` argument is the `input_dir` argument passed to [`Accelerator.load_state`]. <Tip> Should only be used in conjunction with [`Accelerator.register_load_state_pre_hook`]. Can be useful to save configurations in addition to model weights. Can also be used to overwrite model saving with a customized method. In this case, make sure to remove already loaded weights from the weights list. </Tip> Returns: `torch.utils.hooks.RemovableHandle`: a handle that can be used to remove the added hook by calling `handle.remove()`""" (definition of Accelerator.register_load_state_pre_hook:) def register_load_state_pre_hook(self, hook: Callable[..., None]) -> hooks.RemovableHandle: """Registers a pre hook to be run before [`load_checkpoint`] is called in [`Accelerator.load_state`]. Args: hook (`Callable`): A function to be called in [`Accelerator.load_state`] before `load_checkpoint`. The hook should have the following signature: `hook(models: List[torch.nn.Module], input_dir: str) -> None` The `models` argument are the models as saved in the accelerator state under `accelerator._models`, and the `input_dir` argument is the `input_dir` argument passed to [`Accelerator.load_state`]. <Tip> Should only be used in conjunction with [`Accelerator.register_save_state_pre_hook`]. Can be useful to load configurations in addition to model weights. Can also be used to overwrite model loading with a customized method. In this case, make sure to remove already loaded models from the models list. </Tip> Returns: `torch.utils.hooks.RemovableHandle`: a handle that can be used to remove the added hook by calling `handle.remove()`""" [end of new definitions in src/accelerate/accelerator.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
08101b9dde2b1a9658c2e363e3e9f5663ba06073
joke2k__faker-1783
1,783
joke2k/faker
null
348708251a1093fb83c5b7cf83c1fb210a62125d
2023-01-12T11:33:31Z
diff --git a/faker/providers/misc/__init__.py b/faker/providers/misc/__init__.py index b37953ab9d..5fd22ea0f6 100644 --- a/faker/providers/misc/__init__.py +++ b/faker/providers/misc/__init__.py @@ -488,6 +488,21 @@ def psv( delimiter="|", ) + def json_bytes( + self, + data_columns: Optional[List] = None, + num_rows: int = 10, + indent: Optional[int] = None, + cls: Optional[Type[json.JSONEncoder]] = None, + ) -> bytes: + """ + Generate random JSON structure and return as bytes. + + For more information on the different arguments of this method, refer to + :meth:`json() <faker.providers.misc.Provider.json>` which is used under the hood. + """ + return self.json(data_columns=data_columns, num_rows=num_rows, indent=indent, cls=cls).encode() + def json( self, data_columns: Optional[List] = None,
diff --git a/tests/providers/test_misc.py b/tests/providers/test_misc.py index 695defe7f2..f50822f39a 100644 --- a/tests/providers/test_misc.py +++ b/tests/providers/test_misc.py @@ -697,6 +697,13 @@ def test_json_type_integrity_datetime_no_encoder(self, faker_with_foobar): with pytest.raises(TypeError): faker_with_foobar.json(**kwargs) + def test_json_bytes(self, faker_with_foobar): + kwargs = {"data_columns": {"item1": "foo_bar"}, "num_rows": 1} + json_data_bytes = faker_with_foobar.json_bytes(**kwargs) + assert isinstance(json_data_bytes, bytes) + json_data = json.loads(json_data_bytes.decode()) + assert json_data["item1"] == "FooBar" + def test_fixed_width_with_arguments(self, faker_with_foobar): kwargs = { "data_columns": [
[ { "components": [ { "doc": "Generate random JSON structure and return as bytes.\n\nFor more information on the different arguments of this method, refer to\n:meth:`json() <faker.providers.misc.Provider.json>` which is used under the hood.", "lines": [ 491, 504 ], "name": "Provider.json_bytes", "signature": "def json_bytes( self, data_columns: Optional[List] = None, num_rows: int = 10, indent: Optional[int] = None, cls: Optional[Type[json.JSONEncoder]] = None, ) -> bytes:", "type": "function" } ], "file": "faker/providers/misc/__init__.py" } ]
[ "tests/providers/test_misc.py::TestMiscProvider::test_json_bytes" ]
[ "tests/providers/test_misc.py::TestMiscProvider::test_uuid4_str", "tests/providers/test_misc.py::TestMiscProvider::test_uuid4_int", "tests/providers/test_misc.py::TestMiscProvider::test_uuid4_uuid_object", "tests/providers/test_misc.py::TestMiscProvider::test_uuid4_seedability", "tests/providers/test_misc.py::TestMiscProvider::test_zip_invalid_file", "tests/providers/test_misc.py::TestMiscProvider::test_zip_one_byte_undersized", "tests/providers/test_misc.py::TestMiscProvider::test_zip_exact_minimum_size", "tests/providers/test_misc.py::TestMiscProvider::test_zip_over_minimum_size", "tests/providers/test_misc.py::TestMiscProvider::test_zip_compression_py3", "tests/providers/test_misc.py::TestMiscProvider::test_tar_invalid_file", "tests/providers/test_misc.py::TestMiscProvider::test_tar_one_byte_undersized", "tests/providers/test_misc.py::TestMiscProvider::test_tar_exact_minimum_size", "tests/providers/test_misc.py::TestMiscProvider::test_tar_over_minimum_size", "tests/providers/test_misc.py::TestMiscProvider::test_tar_compression_py3", "tests/providers/test_misc.py::TestMiscProvider::test_image_no_pillow", "tests/providers/test_misc.py::TestMiscProvider::test_dsv_with_invalid_values", "tests/providers/test_misc.py::TestMiscProvider::test_dsv_no_header", "tests/providers/test_misc.py::TestMiscProvider::test_dsv_with_valid_header", "tests/providers/test_misc.py::TestMiscProvider::test_dsv_with_row_ids", "tests/providers/test_misc.py::TestMiscProvider::test_dsv_data_columns", "tests/providers/test_misc.py::TestMiscProvider::test_dsv_csvwriter_kwargs", "tests/providers/test_misc.py::TestMiscProvider::test_csv_helper_method", "tests/providers/test_misc.py::TestMiscProvider::test_tsv_helper_method", "tests/providers/test_misc.py::TestMiscProvider::test_psv_helper_method", "tests/providers/test_misc.py::TestMiscProvider::test_json_with_arguments", "tests/providers/test_misc.py::TestMiscProvider::test_json_multiple_rows", "tests/providers/test_misc.py::TestMiscProvider::test_json_passthrough_values", "tests/providers/test_misc.py::TestMiscProvider::test_json_type_integrity_int", "tests/providers/test_misc.py::TestMiscProvider::test_json_type_integrity_float", "tests/providers/test_misc.py::TestMiscProvider::test_json_invalid_data_columns", "tests/providers/test_misc.py::TestMiscProvider::test_json_list_format_invalid_arguments_type", "tests/providers/test_misc.py::TestMiscProvider::test_json_list_format_nested_list_of_values", "tests/providers/test_misc.py::TestMiscProvider::test_json_list_format_nested_list_of_objects", "tests/providers/test_misc.py::TestMiscProvider::test_json_list_format_nested_objects", "tests/providers/test_misc.py::TestMiscProvider::test_json_dict_format_nested_list_of_values", "tests/providers/test_misc.py::TestMiscProvider::test_json_dict_format_nested_list_of_objects", "tests/providers/test_misc.py::TestMiscProvider::test_json_dict_format_nested_objects", "tests/providers/test_misc.py::TestMiscProvider::test_json_type_integrity_datetime_using_encoder", "tests/providers/test_misc.py::TestMiscProvider::test_json_type_integrity_datetime_no_encoder", "tests/providers/test_misc.py::TestMiscProvider::test_fixed_width_with_arguments", "tests/providers/test_misc.py::TestMiscProvider::test_fixed_width_invalid_arguments_type", "tests/providers/test_misc.py::TestMiscProvider::test_md5", "tests/providers/test_misc.py::TestMiscProvider::test_sha1", "tests/providers/test_misc.py::TestMiscProvider::test_sha256" ]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> Add method to generate JSON as bytes ### What does this change Add wrapper method around the JSON provider to generate JSON as bytes. ### What was wrong I use Faker through factory boy and couldn't find a convenient way to achieve that. The change is quite small so I thought it could be a nice addition to the library. ### How this fixes it Wraps the existing JSON provider and encode its output to bytes. ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in faker/providers/misc/__init__.py] (definition of Provider.json_bytes:) def json_bytes( self, data_columns: Optional[List] = None, num_rows: int = 10, indent: Optional[int] = None, cls: Optional[Type[json.JSONEncoder]] = None, ) -> bytes: """Generate random JSON structure and return as bytes. For more information on the different arguments of this method, refer to :meth:`json() <faker.providers.misc.Provider.json>` which is used under the hood.""" [end of new definitions in faker/providers/misc/__init__.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
6edfdbf6ae90b0153309e3bf066aa3b2d16494a7
conan-io__conan-12889
12,889
conan-io/conan
null
ea235dc8a4719b71e13d3734855bff4600f62b06
2023-01-11T15:05:44Z
diff --git a/conan/tools/gnu/autotoolstoolchain.py b/conan/tools/gnu/autotoolstoolchain.py index 61e159ea4fd..b870bd5b032 100644 --- a/conan/tools/gnu/autotoolstoolchain.py +++ b/conan/tools/gnu/autotoolstoolchain.py @@ -224,23 +224,28 @@ def update_autoreconf_args(self, updated_flags): # FIXME: Remove all these update_xxxx whenever xxxx_args are dicts or new ones replace them def _update_flags(self, attr_name, updated_flags): - _new_flags = [] - self_args = getattr(self, attr_name) - for index, flag in enumerate(self_args): - flag_name = flag.split("=")[0] - if flag_name in updated_flags: - new_flag_value = updated_flags[flag_name] - # if {"build": None} is passed, then "--build=xxxx" will be pruned - if new_flag_value is None: - continue - elif not new_flag_value: - _new_flags.append(flag_name) + + def _list_to_dict(flags): + ret = {} + for flag in flags: + # Only splitting if "=" is there + option = flag.split("=", 1) + if len(option) == 2: + ret[option[0]] = option[1] else: - _new_flags.append(f"{flag_name}={new_flag_value}") - else: - _new_flags.append(flag) + ret[option[0]] = "" + return ret + + def _dict_to_list(flags): + return [f"{k}={v}" if v else k for k, v in flags.items() if v is not None] + + self_args = getattr(self, attr_name) + # FIXME: if xxxxx_args -> dict-type at some point, all these lines could be removed + options = _list_to_dict(self_args) + # Add/update/remove the current xxxxx_args with the new flags given + options.update(updated_flags) # Update the current ones - setattr(self, attr_name, _new_flags) + setattr(self, attr_name, _dict_to_list(options)) def generate_args(self): args = {"configure_args": args_to_string(self.configure_args),
diff --git a/conans/test/unittests/tools/gnu/autotoolschain_test.py b/conans/test/unittests/tools/gnu/autotoolschain_test.py index 026acc933a0..61a20034a2d 100644 --- a/conans/test/unittests/tools/gnu/autotoolschain_test.py +++ b/conans/test/unittests/tools/gnu/autotoolschain_test.py @@ -189,20 +189,22 @@ def test_check_configure_args_overwriting_and_deletion(save_args, cross_building def test_update_or_prune_any_args(cross_building_conanfile): at = AutotoolsToolchain(cross_building_conanfile) at.configure_args.append("--enable-flag1=false") - at.make_args.append("--complex-flag=complex-value") # Update configure_args at.update_configure_args({"--prefix": "/my/other/prefix", "--build": None, # prune value - "--enable-flag1": ""}) + "--enable-flag1": "", # without value + "-NEW-FLAG": "no" # new flag + }) new_configure_args = args_to_string(at.configure_args) assert "--prefix=/my/other/prefix" in new_configure_args assert "--build=" not in new_configure_args # pruned assert "--enable-flag1" in new_configure_args # flag without value + assert "-NEW-FLAG=no" in new_configure_args # new flag # Update autoreconf_args at.update_autoreconf_args({"--force": None}) new_autoreconf_args = args_to_string(at.autoreconf_args) assert "'--force" not in new_autoreconf_args - # Update make_args - at.update_make_args({"--complex-flag": "new-value"}) + # Add new value to make_args + at.update_make_args({"--new-complex-flag": "new-value"}) new_make_args = args_to_string(at.make_args) - assert "--complex-flag=new-value" in new_make_args + assert "--new-complex-flag=new-value" in new_make_args
[ { "components": [ { "doc": "", "lines": [ 228, 237 ], "name": "AutotoolsToolchain._update_flags._list_to_dict", "signature": "def _list_to_dict(flags):", "type": "function" }, { "doc": "", "lines": [ 239, 240 ], "name": "AutotoolsToolchain._update_flags._dict_to_list", "signature": "def _dict_to_list(flags):", "type": "function" } ], "file": "conan/tools/gnu/autotoolstoolchain.py" } ]
[ "conans/test/unittests/tools/gnu/autotoolschain_test.py::test_update_or_prune_any_args" ]
[ "conans/test/unittests/tools/gnu/autotoolschain_test.py::test_get_gnu_triplet_for_cross_building", "conans/test/unittests/tools/gnu/autotoolschain_test.py::test_get_toolchain_cppstd", "conans/test/unittests/tools/gnu/autotoolschain_test.py::test_msvc_runtime[static-Debug-MTd]", "conans/test/unittests/tools/gnu/autotoolschain_test.py::test_msvc_runtime[static-Release-MT]", "conans/test/unittests/tools/gnu/autotoolschain_test.py::test_msvc_runtime[dynamic-Debug-MDd]", "conans/test/unittests/tools/gnu/autotoolschain_test.py::test_msvc_runtime[dynamic-Release-MD]", "conans/test/unittests/tools/gnu/autotoolschain_test.py::test_visual_runtime[MTd]", "conans/test/unittests/tools/gnu/autotoolschain_test.py::test_visual_runtime[MT]", "conans/test/unittests/tools/gnu/autotoolschain_test.py::test_visual_runtime[MDd]", "conans/test/unittests/tools/gnu/autotoolschain_test.py::test_visual_runtime[MD]", "conans/test/unittests/tools/gnu/autotoolschain_test.py::test_get_gnu_triplet_for_cross_building_raise_error", "conans/test/unittests/tools/gnu/autotoolschain_test.py::test_compilers_mapping", "conans/test/unittests/tools/gnu/autotoolschain_test.py::test_linker_scripts", "conans/test/unittests/tools/gnu/autotoolschain_test.py::test_check_configure_args_overwriting_and_deletion" ]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> [AutotoolsToolchain] Improve `update_xxxxx_args` behavior Changelog: Feature: AutotoolsToolchain helper functions: `update_configure_args`, `update_make_args`, and `update_autoreconf_args` can also add new values Docs: https://github.com/conan-io/docs/pull/2895 Summary: before this change, it was only possible to update/remove existing values. Now, you could add new ones. Trying to avoid weird situations like: ```python tc = AutotoolsToolchain(self) tc.configure_args.extend([ "--datarootdir=${prefix}/lib", # do not use share "--disable-layoutex", "--disable-layout"]) tc.update_configure_args({"--force": None}) ``` After my change, then it could be reduced to: ```python tc = AutotoolsToolchain(self) tc.update_configure_args({ "--force": None, "--datarootdir": "${prefix}/lib", # do not use share "--disable-layoutex": "", "--disable-layout": ""}) ``` Both are working, but I think the latest one could be the expected behavior. WDYT? ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in conan/tools/gnu/autotoolstoolchain.py] (definition of AutotoolsToolchain._update_flags._list_to_dict:) def _list_to_dict(flags): (definition of AutotoolsToolchain._update_flags._dict_to_list:) def _dict_to_list(flags): [end of new definitions in conan/tools/gnu/autotoolstoolchain.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
4a5b19a75db9225316c8cb022a2dfb9705a2af34
conan-io__conan-12887
12,887
conan-io/conan
null
f3fb6c41246669646243f0c7d83c2c444743d896
2023-01-11T12:43:17Z
diff --git a/conan/tools/microsoft/__init__.py b/conan/tools/microsoft/__init__.py index 79598b28e5f..9c0bb920d5f 100644 --- a/conan/tools/microsoft/__init__.py +++ b/conan/tools/microsoft/__init__.py @@ -1,7 +1,7 @@ from conan.tools.microsoft.layout import vs_layout from conan.tools.microsoft.msbuild import MSBuild from conan.tools.microsoft.msbuilddeps import MSBuildDeps -from conan.tools.microsoft.subsystems import unix_path +from conan.tools.microsoft.subsystems import unix_path, unix_path_package_info_legacy from conan.tools.microsoft.toolchain import MSBuildToolchain from conan.tools.microsoft.nmaketoolchain import NMakeToolchain from conan.tools.microsoft.nmakedeps import NMakeDeps diff --git a/conan/tools/microsoft/subsystems.py b/conan/tools/microsoft/subsystems.py index 55789e8ea81..5d1a59e3559 100644 --- a/conan/tools/microsoft/subsystems.py +++ b/conan/tools/microsoft/subsystems.py @@ -1,6 +1,12 @@ from conans.client.subsystems import deduce_subsystem, subsystem_path +from conans.client.tools.win import unix_path as unix_path_legacy_tools def unix_path(conanfile, path, scope="build"): subsystem = deduce_subsystem(conanfile, scope=scope) return subsystem_path(subsystem, path) + +def unix_path_package_info_legacy(conanfile, path, path_flavor=None): + # Call legacy implementation, which has different logic + # to autodeduce the subsystem type for the conversion. + return unix_path_legacy_tools(path, path_flavor)
diff --git a/conans/test/unittests/tools/microsoft/test_subsystem.py b/conans/test/unittests/tools/microsoft/test_subsystem.py index 65e5423e8c6..0e010e23afb 100644 --- a/conans/test/unittests/tools/microsoft/test_subsystem.py +++ b/conans/test/unittests/tools/microsoft/test_subsystem.py @@ -1,19 +1,20 @@ +import mock import textwrap - import pytest -from conan.tools.microsoft import unix_path +from conan.tools.microsoft import unix_path, unix_path_package_info_legacy from conans.model.conf import ConfDefinition from conans.test.utils.mocks import MockSettings, ConanFileMock - -@pytest.mark.parametrize("subsystem, expected_path", [ +expected_results = [ ("msys2", '/c/path/to/stuff'), ("msys", '/c/path/to/stuff'), ("cygwin", '/cygdrive/c/path/to/stuff'), ("wsl", '/mnt/c/path/to/stuff'), ("sfu", '/dev/fs/C/path/to/stuff') -]) +] + +@pytest.mark.parametrize("subsystem, expected_path", expected_results) def test_unix_path(subsystem, expected_path): c = ConfDefinition() c.loads(textwrap.dedent("""\ @@ -29,3 +30,19 @@ def test_unix_path(subsystem, expected_path): path = unix_path(conanfile, "c:/path/to/stuff") assert expected_path == path + +@mock.patch("platform.system", mock.MagicMock(return_value='Windows')) +@pytest.mark.parametrize("subsystem, expected_path", expected_results) +def test_unix_path_package_info_legacy_windows(subsystem, expected_path): + test_path = "c:/path/to/stuff" + conanfile = ConanFileMock() + package_info_legacy_path = unix_path_package_info_legacy(conanfile, test_path, path_flavor=subsystem) + assert expected_path == package_info_legacy_path + +@mock.patch("platform.system", mock.MagicMock(return_value='Darwin')) +@pytest.mark.parametrize("subsystem, expected_path", expected_results) +def test_unix_path_package_info_legacy_not_windows(subsystem, expected_path): + test_path = "c:/path/to/stuff" + conanfile = ConanFileMock() + package_info_legacy_path = unix_path_package_info_legacy(conanfile, test_path, path_flavor=subsystem) + assert test_path == package_info_legacy_path \ No newline at end of file
[ { "components": [ { "doc": "", "lines": [ 9, 12 ], "name": "unix_path_package_info_legacy", "signature": "def unix_path_package_info_legacy(conanfile, path, path_flavor=None):", "type": "function" } ], "file": "conan/tools/microsoft/subsystems.py" } ]
[ "conans/test/unittests/tools/microsoft/test_subsystem.py::test_unix_path[msys2-/c/path/to/stuff]", "conans/test/unittests/tools/microsoft/test_subsystem.py::test_unix_path[msys-/c/path/to/stuff]", "conans/test/unittests/tools/microsoft/test_subsystem.py::test_unix_path[cygwin-/cygdrive/c/path/to/stuff]", "conans/test/unittests/tools/microsoft/test_subsystem.py::test_unix_path[wsl-/mnt/c/path/to/stuff]", "conans/test/unittests/tools/microsoft/test_subsystem.py::test_unix_path[sfu-/dev/fs/C/path/to/stuff]", "conans/test/unittests/tools/microsoft/test_subsystem.py::test_unix_path_package_info_legacy_windows[msys2-/c/path/to/stuff]", "conans/test/unittests/tools/microsoft/test_subsystem.py::test_unix_path_package_info_legacy_windows[msys-/c/path/to/stuff]", "conans/test/unittests/tools/microsoft/test_subsystem.py::test_unix_path_package_info_legacy_windows[cygwin-/cygdrive/c/path/to/stuff]", "conans/test/unittests/tools/microsoft/test_subsystem.py::test_unix_path_package_info_legacy_windows[wsl-/mnt/c/path/to/stuff]", "conans/test/unittests/tools/microsoft/test_subsystem.py::test_unix_path_package_info_legacy_windows[sfu-/dev/fs/C/path/to/stuff]", "conans/test/unittests/tools/microsoft/test_subsystem.py::test_unix_path_package_info_legacy_not_windows[msys2-/c/path/to/stuff]", "conans/test/unittests/tools/microsoft/test_subsystem.py::test_unix_path_package_info_legacy_not_windows[msys-/c/path/to/stuff]", "conans/test/unittests/tools/microsoft/test_subsystem.py::test_unix_path_package_info_legacy_not_windows[cygwin-/cygdrive/c/path/to/stuff]", "conans/test/unittests/tools/microsoft/test_subsystem.py::test_unix_path_package_info_legacy_not_windows[wsl-/mnt/c/path/to/stuff]", "conans/test/unittests/tools/microsoft/test_subsystem.py::test_unix_path_package_info_legacy_not_windows[sfu-/dev/fs/C/path/to/stuff]" ]
[]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> Add unix_path_package_info_legacy compatibility function Changelog: Feature: Add `unix_path_package_info_legacy` function for those cases in which it is used in `package_info` in recipes that require compatibility with Conan 1.x. In Conan 2, path conversions should not be performed in the `package_info` method. Docs: https://github.com/conan-io/docs/pull/2894 ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in conan/tools/microsoft/subsystems.py] (definition of unix_path_package_info_legacy:) def unix_path_package_info_legacy(conanfile, path, path_flavor=None): [end of new definitions in conan/tools/microsoft/subsystems.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
4a5b19a75db9225316c8cb022a2dfb9705a2af34
conan-io__conan-12886
12,886
conan-io/conan
null
0f73ed743ffd5d9cfeef54bfbc1547d08ce6436d
2023-01-11T12:19:11Z
diff --git a/conan/tools/microsoft/__init__.py b/conan/tools/microsoft/__init__.py index 79598b28e5f..9c0bb920d5f 100644 --- a/conan/tools/microsoft/__init__.py +++ b/conan/tools/microsoft/__init__.py @@ -1,7 +1,7 @@ from conan.tools.microsoft.layout import vs_layout from conan.tools.microsoft.msbuild import MSBuild from conan.tools.microsoft.msbuilddeps import MSBuildDeps -from conan.tools.microsoft.subsystems import unix_path +from conan.tools.microsoft.subsystems import unix_path, unix_path_package_info_legacy from conan.tools.microsoft.toolchain import MSBuildToolchain from conan.tools.microsoft.nmaketoolchain import NMakeToolchain from conan.tools.microsoft.nmakedeps import NMakeDeps diff --git a/conan/tools/microsoft/subsystems.py b/conan/tools/microsoft/subsystems.py index 55789e8ea81..62600065c3e 100644 --- a/conan/tools/microsoft/subsystems.py +++ b/conan/tools/microsoft/subsystems.py @@ -4,3 +4,10 @@ def unix_path(conanfile, path, scope="build"): subsystem = deduce_subsystem(conanfile, scope=scope) return subsystem_path(subsystem, path) + +def unix_path_package_info_legacy(conanfile, path, path_flavor=None): + message = f"The use of 'unix_path_legacy_compat' is deprecated in Conan 2.0 and does not " \ + f"perform path conversions. This is retained for compatibility with Conan 1.x " \ + f"and will be removed in a future version." + conanfile.output.warning(message) + return path
diff --git a/conans/test/unittests/tools/microsoft/test_subsystem.py b/conans/test/unittests/tools/microsoft/test_subsystem.py index 65e5423e8c6..3af3cf3c860 100644 --- a/conans/test/unittests/tools/microsoft/test_subsystem.py +++ b/conans/test/unittests/tools/microsoft/test_subsystem.py @@ -2,7 +2,7 @@ import pytest -from conan.tools.microsoft import unix_path +from conan.tools.microsoft import unix_path, unix_path_package_info_legacy from conans.model.conf import ConfDefinition from conans.test.utils.mocks import MockSettings, ConanFileMock @@ -27,5 +27,9 @@ def test_unix_path(subsystem, expected_path): conanfile.settings = settings conanfile.settings_build = settings - path = unix_path(conanfile, "c:/path/to/stuff") + test_path = "c:/path/to/stuff" + path = unix_path(conanfile, test_path) assert expected_path == path + + package_info_legacy_path = unix_path_package_info_legacy(conanfile, test_path, path_flavor=subsystem) + assert package_info_legacy_path == test_path
[ { "components": [ { "doc": "", "lines": [ 8, 13 ], "name": "unix_path_package_info_legacy", "signature": "def unix_path_package_info_legacy(conanfile, path, path_flavor=None):", "type": "function" } ], "file": "conan/tools/microsoft/subsystems.py" } ]
[ "conans/test/unittests/tools/microsoft/test_subsystem.py::test_unix_path[msys2-/c/path/to/stuff]", "conans/test/unittests/tools/microsoft/test_subsystem.py::test_unix_path[msys-/c/path/to/stuff]", "conans/test/unittests/tools/microsoft/test_subsystem.py::test_unix_path[cygwin-/cygdrive/c/path/to/stuff]", "conans/test/unittests/tools/microsoft/test_subsystem.py::test_unix_path[wsl-/mnt/c/path/to/stuff]", "conans/test/unittests/tools/microsoft/test_subsystem.py::test_unix_path[sfu-/dev/fs/C/path/to/stuff]" ]
[]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> Add unix_path_package_info_legacy compatibility function Changelog: Feature: Add `unix_path_package_info_legacy` function for those cases in which it is used in `package_info` in recipes that require compatibility with Conan 1.x. In Conan 2, path conversions should not be performed in the `package_info` method. Docs: https://github.com/conan-io/docs/pull/XXXX ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in conan/tools/microsoft/subsystems.py] (definition of unix_path_package_info_legacy:) def unix_path_package_info_legacy(conanfile, path, path_flavor=None): [end of new definitions in conan/tools/microsoft/subsystems.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
4a5b19a75db9225316c8cb022a2dfb9705a2af34
conan-io__conan-12873
12,873
conan-io/conan
null
6e1f2bb60a430f2567480ddeaba19cafb20fbcb2
2023-01-09T13:36:32Z
diff --git a/conan/tools/android/__init__.py b/conan/tools/android/__init__.py new file mode 100644 index 00000000000..c969bbebd07 --- /dev/null +++ b/conan/tools/android/__init__.py @@ -0,0 +1,1 @@ +from conan.tools.android.utils import android_abi diff --git a/conan/tools/android/utils.py b/conan/tools/android/utils.py new file mode 100644 index 00000000000..12a5e7551db --- /dev/null +++ b/conan/tools/android/utils.py @@ -0,0 +1,31 @@ +from conan.errors import ConanException + + +def android_abi(conanfile, context="host"): + """ + Returns Android-NDK ABI + :param conanfile: ConanFile instance + :param context: either "host", "build" or "target" + :return: Android-NDK ABI + """ + if context not in ("host", "build", "target"): + raise ConanException(f"context argument must be either 'host', 'build' or 'target', was '{context}'") + + try: + settings = getattr(conanfile, f"settings_{context}") + except AttributeError: + if context == "host": + settings = conanfile.settings + else: + raise ConanException(f"settings_{context} not declared in recipe") + arch = settings.get_safe("arch") + # https://cmake.org/cmake/help/latest/variable/CMAKE_ANDROID_ARCH_ABI.html + return { + "armv5el": "armeabi", + "armv5hf": "armeabi", + "armv5": "armeabi", + "armv6": "armeabi-v6", + "armv7": "armeabi-v7a", + "armv7hf": "armeabi-v7a", + "armv8": "arm64-v8a", + }.get(arch, arch) diff --git a/conan/tools/cmake/toolchain/blocks.py b/conan/tools/cmake/toolchain/blocks.py index 5846f009705..2e217ec3b2a 100644 --- a/conan/tools/cmake/toolchain/blocks.py +++ b/conan/tools/cmake/toolchain/blocks.py @@ -6,6 +6,7 @@ from jinja2 import Template from conan.tools._compilers import architecture_flag, libcxx_flags +from conan.tools.android.utils import android_abi from conan.tools.apple.apple import is_apple_os, to_apple_arch from conan.tools.build import build_jobs from conan.tools.build.cross_building import cross_building @@ -286,11 +287,6 @@ def context(self): if os_ != "Android": return - android_abi = {"x86": "x86", - "x86_64": "x86_64", - "armv7": "armeabi-v7a", - "armv8": "arm64-v8a"}.get(str(self._conanfile.settings.arch)) - # TODO: only 'c++_shared' y 'c++_static' supported? # https://developer.android.com/ndk/guides/cpp-support libcxx_str = self._conanfile.settings.get_safe("compiler.libcxx") @@ -302,7 +298,7 @@ def context(self): ctxt_toolchain = { 'android_platform': 'android-' + str(self._conanfile.settings.os.api_level), - 'android_abi': android_abi, + 'android_abi': android_abi(self._conanfile), 'android_stl': libcxx_str, 'android_ndk_path': android_ndk_path, }
diff --git a/conans/test/unittests/tools/android/__init__.py b/conans/test/unittests/tools/android/__init__.py new file mode 100644 index 00000000000..e69de29bb2d diff --git a/conans/test/unittests/tools/android/test_android_tools.py b/conans/test/unittests/tools/android/test_android_tools.py new file mode 100644 index 00000000000..038bd0b461e --- /dev/null +++ b/conans/test/unittests/tools/android/test_android_tools.py @@ -0,0 +1,79 @@ +from conans.test.utils.mocks import ConanFileMock, MockSettings +from conans.errors import ConanException +from conan.tools.android import android_abi + +from pytest import raises + +def test_tools_android_abi(): + settings_linux = MockSettings({"os": "Linux", "arch": "foo"}) + + for (arch, expected) in [ + ("armv5el", "armeabi"), + ("armv5hf", "armeabi"), + ("armv5", "armeabi"), + ("armv6", "armeabi-v6"), + ("armv7", "armeabi-v7a"), + ("armv7hf", "armeabi-v7a"), + ("armv8", "arm64-v8a"), + ("x86", "x86"), + ("x86_64", "x86_64"), + ("mips", "mips"), + ("mips_64", "mips_64"), + ]: + conanfile = ConanFileMock() + settings_android = MockSettings({"os": "Android", "arch": arch}) + + # 1 profile (legacy native build) + conanfile.settings = settings_android + assert android_abi(conanfile) == expected + assert android_abi(conanfile, context="host") == expected + + with raises(ConanException): + assert android_abi(conanfile, context="build") == expected + + with raises(ConanException): + assert android_abi(conanfile, context="target") == expected + + # 2 profiles + ## native build + conanfile.settings = settings_android + conanfile.settings_host = settings_android + conanfile.settings_build = settings_android + assert android_abi(conanfile) == expected + assert android_abi(conanfile, context="host") == expected + assert android_abi(conanfile, context="build") == expected + + with raises(ConanException): + assert android_abi(conanfile, context="target") == expected + + ## cross-build from Android to Linux (quite hypothetical) + conanfile.settings = settings_linux + conanfile.settings_host = settings_linux + conanfile.settings_build = settings_android + assert android_abi(conanfile) != expected + assert android_abi(conanfile, context="host") != expected + assert android_abi(conanfile, context="build") == expected + + with raises(ConanException): + assert android_abi(conanfile, context="target") + + ## cross-build a recipe from Linux to Android: + ### test android_abi in recipe itself + conanfile.settings = settings_android + conanfile.settings_host = settings_android + conanfile.settings_build = settings_linux + assert android_abi(conanfile) == expected + assert android_abi(conanfile, context="host") == expected + assert android_abi(conanfile, context="build") != expected + with raises(ConanException): + android_abi(conanfile, context="target") + + ### test android_abi in "compiler recipe" (ie a android-ndk recipe in tool_requires of recipe being cross-build) + conanfile.settings = settings_linux + conanfile.settings_host = settings_linux + conanfile.settings_build = settings_linux + conanfile.settings_target = settings_android + assert android_abi(conanfile) != expected + assert android_abi(conanfile, context="host") != expected + assert android_abi(conanfile, context="build") != expected + assert android_abi(conanfile, context="target") == expected
[ { "components": [ { "doc": "Returns Android-NDK ABI\n:param conanfile: ConanFile instance\n:param context: either \"host\", \"build\" or \"target\"\n:return: Android-NDK ABI", "lines": [ 4, 31 ], "name": "android_abi", "signature": "def android_abi(conanfile, context=\"host\"):", "type": "function" } ], "file": "conan/tools/android/utils.py" } ]
[ "conans/test/unittests/tools/android/test_android_tools.py::test_tools_android_abi" ]
[]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> add `conan.tools.android.android_abi()` Changelog: Feature: Add `conan.tools.android.android_abi()` function to return the Android standard ABI name based on Conan. Docs: https://github.com/conan-io/docs/pull/2975 closes https://github.com/conan-io/conan/issues/12814 - [x] Refer to the issue that supports this Pull Request. - [x] If the issue has missing info, explain the purpose/use case/pain/need that covers this Pull Request. - [x] I've read the [Contributing guide](https://github.com/conan-io/conan/blob/develop/.github/CONTRIBUTING.md). - [x] I've followed the PEP8 style guides for Python code. - [ ] I've opened another PR in the Conan docs repo to the ``develop`` branch, documenting this one. <sup>**Note:** By default this PR will skip the slower tests and will use a limited set of python versions. Check [here](https://github.com/conan-io/conan/blob/develop/.github/PR_INCREASE_TESTING.md) how to increase the testing level by writing some tags in the current PR body text.</sup> ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in conan/tools/android/utils.py] (definition of android_abi:) def android_abi(conanfile, context="host"): """Returns Android-NDK ABI :param conanfile: ConanFile instance :param context: either "host", "build" or "target" :return: Android-NDK ABI""" [end of new definitions in conan/tools/android/utils.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
4a5b19a75db9225316c8cb022a2dfb9705a2af34
Textualize__textual-1517
1,517
Textualize/textual
null
779b10a0e8b8581fab512eb684a06eb90381705d
2023-01-07T14:10:40Z
diff --git a/src/textual/app.py b/src/textual/app.py index b207bbd025..89da6aaf60 100644 --- a/src/textual/app.py +++ b/src/textual/app.py @@ -1,6 +1,8 @@ from __future__ import annotations import asyncio +from concurrent.futures import Future +from functools import partial import inspect import io import os @@ -18,6 +20,7 @@ from typing import ( TYPE_CHECKING, Any, + Awaitable, Callable, Generic, Iterable, @@ -206,6 +209,8 @@ def stop(self) -> None: CSSPathType = Union[str, PurePath, List[Union[str, PurePath]], None] +CallThreadReturnType = TypeVar("CallThreadReturnType") + @rich.repr.auto class App(Generic[ReturnType], DOMNode): @@ -353,6 +358,8 @@ def __init__( else: self.devtools = DevtoolsClient() + self._loop: asyncio.AbstractEventLoop | None = None + self._thread_id: int = 0 self._return_value: ReturnType | None = None self._exit = False @@ -604,6 +611,51 @@ def _log( except Exception as error: self._handle_exception(error) + def call_from_thread( + self, + callback: Callable[..., CallThreadReturnType | Awaitable[CallThreadReturnType]], + *args, + **kwargs, + ) -> CallThreadReturnType: + """Run a callback from another thread. + + Like asyncio apps in general, Textual apps are not thread-safe. If you call methods + or set attributes on Textual objects from a thread, you may get unpredictable results. + + This method will ensure that your code is ran within the correct context. + + Args: + callback (Callable): A callable to run. + *args: Arguments to the callback. + **kwargs: Keyword arguments for the callback. + + Raises: + RuntimeError: If the app isn't running or if this method is called from the same + thread where the app is running. + """ + + if self._loop is None: + raise RuntimeError("App is not running") + + if self._thread_id == threading.get_ident(): + raise RuntimeError( + "The `call_from_thread` method must run in a different thread from the app" + ) + + callback_with_args = partial(callback, *args, **kwargs) + + async def run_callback() -> CallThreadReturnType: + """Run the callback, set the result or error on the future.""" + self._set_active() + return await invoke(callback_with_args) + + # Post the message to the main loop + future: Future[CallThreadReturnType] = asyncio.run_coroutine_threadsafe( + run_callback(), loop=self._loop + ) + result = future.result() + return result + def action_toggle_dark(self) -> None: """Action to toggle dark mode.""" self.dark = not self.dark @@ -874,11 +926,17 @@ def run( async def run_app() -> None: """Run the app.""" - await self.run_async( - headless=headless, - size=size, - auto_pilot=auto_pilot, - ) + self._loop = asyncio.get_running_loop() + self._thread_id = threading.get_ident() + try: + await self.run_async( + headless=headless, + size=size, + auto_pilot=auto_pilot, + ) + finally: + self._loop = None + self._thread_id = 0 if _ASYNCIO_GET_EVENT_LOOP_IS_DEPRECATED: # N.B. This doesn't work with Python<3.10, as we end up with 2 event loops:
diff --git a/tests/test_concurrency.py b/tests/test_concurrency.py new file mode 100644 index 0000000000..c73418f2f2 --- /dev/null +++ b/tests/test_concurrency.py @@ -0,0 +1,53 @@ +import pytest + +from threading import Thread +from textual.app import App, ComposeResult +from textual.widgets import TextLog + + +def test_call_from_thread_app_not_running(): + app = App() + + # Should fail if app is not running + with pytest.raises(RuntimeError): + app.call_from_thread(print) + + +def test_call_from_thread(): + """Test the call_from_thread method.""" + + class BackgroundThread(Thread): + """A background thread which will modify app in some way.""" + + def __init__(self, app: App) -> None: + self.app = app + super().__init__() + + def run(self) -> None: + def write_stuff(text: str) -> None: + """Write stuff to a widget.""" + self.app.query_one(TextLog).write(text) + + self.app.call_from_thread(write_stuff, "Hello") + # Exit the app with a code we can assert + self.app.call_from_thread(self.app.exit, 123) + + class ThreadTestApp(App): + """Trivial app with a single widget.""" + + def compose(self) -> ComposeResult: + yield TextLog() + + def on_ready(self) -> None: + """Launch a thread which will modify the app.""" + try: + self.call_from_thread(print) + except RuntimeError as error: + # Calling this from the same thread as the app is an error + self._runtime_error = error + BackgroundThread(self).start() + + app = ThreadTestApp() + result = app.run(headless=True, size=(80, 24)) + assert isinstance(app._runtime_error, RuntimeError) + assert result == 123
[ { "components": [ { "doc": "Run a callback from another thread.\n\nLike asyncio apps in general, Textual apps are not thread-safe. If you call methods\nor set attributes on Textual objects from a thread, you may get unpredictable results.\n\nThis method will ensure that your code is ran within the correct context.\n\nArgs:\n callback (Callable): A callable to run.\n *args: Arguments to the callback.\n **kwargs: Keyword arguments for the callback.\n\nRaises:\n RuntimeError: If the app isn't running or if this method is called from the same\n thread where the app is running.", "lines": [ 614, 657 ], "name": "App.call_from_thread", "signature": "def call_from_thread( self, callback: Callable[..., CallThreadReturnType | Awaitable[CallThreadReturnType]], *args, **kwargs, ) -> CallThreadReturnType:", "type": "function" } ], "file": "src/textual/app.py" } ]
[ "tests/test_concurrency.py::test_call_from_thread_app_not_running", "tests/test_concurrency.py::test_call_from_thread" ]
[]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> Call from thread method This is a step towards having an answer to devs who want to integrate a third-party API with Textual. The `call_from_thread` takes a callback that will be called in the app's loop from a thread. It will block until the callback returns. If integrating with a threaded API (many are under the hood), this will generally give the most predictable behaviour. There are downsides: you call it from the same thread as the app. Otherwise it would deadlock. I'll leave this method undocumented for now. We will at least have an answer for the next version, and we can work on greater syntactical sugar in the meantime. ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in src/textual/app.py] (definition of App.call_from_thread:) def call_from_thread( self, callback: Callable[..., CallThreadReturnType | Awaitable[CallThreadReturnType]], *args, **kwargs, ) -> CallThreadReturnType: """Run a callback from another thread. Like asyncio apps in general, Textual apps are not thread-safe. If you call methods or set attributes on Textual objects from a thread, you may get unpredictable results. This method will ensure that your code is ran within the correct context. Args: callback (Callable): A callable to run. *args: Arguments to the callback. **kwargs: Keyword arguments for the callback. Raises: RuntimeError: If the app isn't running or if this method is called from the same thread where the app is running.""" [end of new definitions in src/textual/app.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
86e93536b991014e0ea4bf993068202b446bb698
tobymao__sqlglot-874
874
tobymao/sqlglot
null
f5f3f84c7343151c5f48da60e8c15df41aadb33a
2023-01-02T17:23:08Z
diff --git a/sqlglot/dialects/postgres.py b/sqlglot/dialects/postgres.py index 15f627bfdb..a092cadb2a 100644 --- a/sqlglot/dialects/postgres.py +++ b/sqlglot/dialects/postgres.py @@ -15,6 +15,15 @@ from sqlglot.tokens import TokenType from sqlglot.transforms import delegate, preprocess +DATE_DIFF_FACTOR = { + "MICROSECOND": " * 1000000", + "MILLISECOND": " * 1000", + "SECOND": "", + "MINUTE": " / 60", + "HOUR": " / 3600", + "DAY": " / 86400", +} + def _date_add_sql(kind): def func(self, expression): @@ -35,6 +44,32 @@ def func(self, expression): return func +def _date_diff_sql(self, expression): + unit = expression.text("unit").upper() + factor = DATE_DIFF_FACTOR.get(unit) + + end = f"CAST({expression.this} AS TIMESTAMP)" + start = f"CAST({expression.expression} AS TIMESTAMP)" + + if factor is not None: + return f"CAST(EXTRACT(epoch FROM {end} - {start}){factor} AS BIGINT)" + + age = f"AGE({end}, {start})" + + if unit == "WEEK": + extract = f"EXTRACT(year FROM {age}) * 48 + EXTRACT(month FROM {age}) * 4 + EXTRACT(day FROM {age}) / 7" + elif unit == "MONTH": + extract = f"EXTRACT(year FROM {age}) * 12 + EXTRACT(month FROM {age})" + elif unit == "QUARTER": + extract = f"EXTRACT(year FROM {age}) * 4 + EXTRACT(month FROM {age}) / 3" + elif unit == "YEAR": + extract = f"EXTRACT(year FROM {age})" + else: + self.unsupported(f"Unsupported DATEDIFF unit {unit}") + + return f"CAST({extract} AS BIGINT)" + + def _substring_sql(self, expression): this = self.sql(expression, "this") start = self.sql(expression, "start") @@ -275,6 +310,7 @@ class Generator(generator.Generator): exp.CurrentTimestamp: lambda *_: "CURRENT_TIMESTAMP", exp.DateAdd: _date_add_sql("+"), exp.DateSub: _date_add_sql("-"), + exp.DateDiff: _date_diff_sql, exp.RegexpLike: lambda self, e: self.binary(e, "~"), exp.RegexpILike: lambda self, e: self.binary(e, "~*"), exp.StrPosition: str_position_sql,
diff --git a/tests/dialects/test_databricks.py b/tests/dialects/test_databricks.py index 2168f55de3..7560d616fa 100644 --- a/tests/dialects/test_databricks.py +++ b/tests/dialects/test_databricks.py @@ -12,6 +12,76 @@ def test_datediff(self): "databricks": "SELECT DATEDIFF(year, 'start', 'end')", }, ) + self.validate_all( + "SELECT DATEDIFF(microsecond, 'start', 'end')", + write={ + "databricks": "SELECT DATEDIFF(microsecond, 'start', 'end')", + "postgres": "SELECT CAST(EXTRACT(epoch FROM CAST('end' AS TIMESTAMP) - CAST('start' AS TIMESTAMP)) * 1000000 AS BIGINT)", + }, + ) + self.validate_all( + "SELECT DATEDIFF(millisecond, 'start', 'end')", + write={ + "databricks": "SELECT DATEDIFF(millisecond, 'start', 'end')", + "postgres": "SELECT CAST(EXTRACT(epoch FROM CAST('end' AS TIMESTAMP) - CAST('start' AS TIMESTAMP)) * 1000 AS BIGINT)", + }, + ) + self.validate_all( + "SELECT DATEDIFF(second, 'start', 'end')", + write={ + "databricks": "SELECT DATEDIFF(second, 'start', 'end')", + "postgres": "SELECT CAST(EXTRACT(epoch FROM CAST('end' AS TIMESTAMP) - CAST('start' AS TIMESTAMP)) AS BIGINT)", + }, + ) + self.validate_all( + "SELECT DATEDIFF(minute, 'start', 'end')", + write={ + "databricks": "SELECT DATEDIFF(minute, 'start', 'end')", + "postgres": "SELECT CAST(EXTRACT(epoch FROM CAST('end' AS TIMESTAMP) - CAST('start' AS TIMESTAMP)) / 60 AS BIGINT)", + }, + ) + self.validate_all( + "SELECT DATEDIFF(hour, 'start', 'end')", + write={ + "databricks": "SELECT DATEDIFF(hour, 'start', 'end')", + "postgres": "SELECT CAST(EXTRACT(epoch FROM CAST('end' AS TIMESTAMP) - CAST('start' AS TIMESTAMP)) / 3600 AS BIGINT)", + }, + ) + self.validate_all( + "SELECT DATEDIFF(day, 'start', 'end')", + write={ + "databricks": "SELECT DATEDIFF(day, 'start', 'end')", + "postgres": "SELECT CAST(EXTRACT(epoch FROM CAST('end' AS TIMESTAMP) - CAST('start' AS TIMESTAMP)) / 86400 AS BIGINT)", + }, + ) + self.validate_all( + "SELECT DATEDIFF(week, 'start', 'end')", + write={ + "databricks": "SELECT DATEDIFF(week, 'start', 'end')", + "postgres": "SELECT CAST(EXTRACT(year FROM AGE(CAST('end' AS TIMESTAMP), CAST('start' AS TIMESTAMP))) * 48 + EXTRACT(month FROM AGE(CAST('end' AS TIMESTAMP), CAST('start' AS TIMESTAMP))) * 4 + EXTRACT(day FROM AGE(CAST('end' AS TIMESTAMP), CAST('start' AS TIMESTAMP))) / 7 AS BIGINT)", + }, + ) + self.validate_all( + "SELECT DATEDIFF(month, 'start', 'end')", + write={ + "databricks": "SELECT DATEDIFF(month, 'start', 'end')", + "postgres": "SELECT CAST(EXTRACT(year FROM AGE(CAST('end' AS TIMESTAMP), CAST('start' AS TIMESTAMP))) * 12 + EXTRACT(month FROM AGE(CAST('end' AS TIMESTAMP), CAST('start' AS TIMESTAMP))) AS BIGINT)", + }, + ) + self.validate_all( + "SELECT DATEDIFF(quarter, 'start', 'end')", + write={ + "databricks": "SELECT DATEDIFF(quarter, 'start', 'end')", + "postgres": "SELECT CAST(EXTRACT(year FROM AGE(CAST('end' AS TIMESTAMP), CAST('start' AS TIMESTAMP))) * 4 + EXTRACT(month FROM AGE(CAST('end' AS TIMESTAMP), CAST('start' AS TIMESTAMP))) / 3 AS BIGINT)", + }, + ) + self.validate_all( + "SELECT DATEDIFF(year, 'start', 'end')", + write={ + "databricks": "SELECT DATEDIFF(year, 'start', 'end')", + "postgres": "SELECT CAST(EXTRACT(year FROM AGE(CAST('end' AS TIMESTAMP), CAST('start' AS TIMESTAMP))) AS BIGINT)", + }, + ) def test_add_date(self): self.validate_all(
[ { "components": [ { "doc": "", "lines": [ 47, 70 ], "name": "_date_diff_sql", "signature": "def _date_diff_sql(self, expression):", "type": "function" } ], "file": "sqlglot/dialects/postgres.py" } ]
[ "tests/dialects/test_databricks.py::TestDatabricks::test_datediff" ]
[ "tests/dialects/test_databricks.py::TestDatabricks::test_add_date" ]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> Transpile DATEDIFF to postgres This is a WIP -- thought I'd start a PR early to get some feedback and iterate faster. The units "week", "month", "quarter" and "year" are currently missing from the implementation, but I'll add them soon. I'm trying to figure out how to reduce code duplication as much as possible for them. Regarding my current approach, I'm unsure whether hardcoding the mult / div operators as strings is the way to go. An alternative could be to return a tuple that contains the factor and a flag that determines whether to multiply or to divide, although it's not necessary cleaner. cc: @tobymao ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in sqlglot/dialects/postgres.py] (definition of _date_diff_sql:) def _date_diff_sql(self, expression): [end of new definitions in sqlglot/dialects/postgres.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
ceb42fabad60312699e4b15936aeebac00e22e4d
sympy__sympy-24437
24,437
sympy/sympy
1.12
9b9786518d3475751e66e11d3e3592091e3160b3
2022-12-29T22:56:10Z
diff --git a/sympy/utilities/iterables.py b/sympy/utilities/iterables.py index 144713d4fe47..a0eb4cece751 100644 --- a/sympy/utilities/iterables.py +++ b/sympy/utilities/iterables.py @@ -3,7 +3,6 @@ chain, combinations, combinations_with_replacement, cycle, islice, permutations, product ) - # For backwards compatibility from itertools import product as cartes # noqa: F401 from operator import gt @@ -2706,6 +2705,130 @@ def runs(seq, op=gt): return cycles +def sequence_partitions(l, n, /): + r"""Returns the partition of sequence $l$ into $n$ bins + + Explanation + =========== + + Given the sequence $l_1 \cdots l_m \in V^+$ where + $V^+$ is the Kleene plus of $V$ + + The set of $n$ partitions of $l$ is defined as: + + .. math:: + \{(s_1, \cdots, s_n) | s_1 \in V^+, \cdots, s_n \in V^+, + s_1 \cdots s_n = l_1 \cdots l_m\} + + Parameters + ========== + + l : Sequence[T] + A nonempty sequence of any Python objects + + n : int + A positive integer + + Yields + ====== + + out : list[Sequence[T]] + A list of sequences with concatenation equals $l$. + This should conform with the type of $l$. + + Examples + ======== + + >>> from sympy.utilities.iterables import sequence_partitions + >>> for out in sequence_partitions([1, 2, 3, 4], 2): + ... print(out) + [[1], [2, 3, 4]] + [[1, 2], [3, 4]] + [[1, 2, 3], [4]] + + Notes + ===== + + This is modified version of EnricoGiampieri's partition generator + from https://stackoverflow.com/questions/13131491/ + + See Also + ======== + + sequence_partitions_empty + """ + # Asserting l is nonempty is done only for sanity check + if n == 1 and l: + yield [l] + return + for i in range(1, len(l)): + for part in sequence_partitions(l[i:], n - 1): + yield [l[:i]] + part + + +def sequence_partitions_empty(l, n, /): + r"""Returns the partition of sequence $l$ into $n$ bins with + empty sequence + + Explanation + =========== + + Given the sequence $l_1 \cdots l_m \in V^*$ where + $V^*$ is the Kleene star of $V$ + + The set of $n$ partitions of $l$ is defined as: + + .. math:: + \{(s_1, \cdots, s_n) | s_1 \in V^*, \cdots, s_n \in V^*, + s_1 \cdots s_n = l_1 \cdots l_m\} + + There are more combinations than :func:`sequence_partitions` because + empty sequence can fill everywhere, so we try to provide different + utility for this. + + Parameters + ========== + + l : Sequence[T] + A sequence of any Python objects (can be possibly empty) + + n : int + A positive integer + + Yields + ====== + + out : list[Sequence[T]] + A list of sequences with concatenation equals $l$. + This should conform with the type of $l$. + + Examples + ======== + + >>> from sympy.utilities.iterables import sequence_partitions_empty + >>> for out in sequence_partitions_empty([1, 2, 3, 4], 2): + ... print(out) + [[], [1, 2, 3, 4]] + [[1], [2, 3, 4]] + [[1, 2], [3, 4]] + [[1, 2, 3], [4]] + [[1, 2, 3, 4], []] + + See Also + ======== + + sequence_partitions + """ + if n < 1: + return + if n == 1: + yield [l] + return + for i in range(0, len(l) + 1): + for part in sequence_partitions_empty(l[i:], n - 1): + yield [l[:i]] + part + + def kbins(l, k, ordered=None): """ Return sequence ``l`` partitioned into ``k`` bins. @@ -2787,24 +2910,12 @@ def kbins(l, k, ordered=None): partitions, multiset_partitions """ - def partition(lista, bins): - # EnricoGiampieri's partition generator from - # https://stackoverflow.com/questions/13131491/ - # partition-n-items-into-k-bins-in-python-lazily - if len(lista) == 1 or bins == 1: - yield [lista] - elif len(lista) > 1 and bins > 1: - for i in range(1, len(lista)): - for part in partition(lista[i:], bins - 1): - if len([lista[:i]] + part) == bins: - yield [lista[:i]] + part - if ordered is None: - yield from partition(l, k) + yield from sequence_partitions(l, k) elif ordered == 11: for pl in multiset_permutations(l): pl = list(pl) - yield from partition(pl, k) + yield from sequence_partitions(pl, k) elif ordered == 00: yield from multiset_partitions(l, k) elif ordered == 10:
diff --git a/sympy/utilities/tests/test_iterables.py b/sympy/utilities/tests/test_iterables.py index 77c6e7b1ee80..8e527a447e75 100644 --- a/sympy/utilities/tests/test_iterables.py +++ b/sympy/utilities/tests/test_iterables.py @@ -19,7 +19,8 @@ prefixes, reshape, rotate_left, rotate_right, runs, sift, strongly_connected_components, subsets, take, topological_sort, unflatten, uniq, variations, ordered_partitions, rotations, is_palindromic, iterable, - NotIterable, multiset_derangements) + NotIterable, multiset_derangements, + sequence_partitions, sequence_partitions_empty) from sympy.utilities.enumerative import ( factoring_visitor, multiset_partitions_taocp ) @@ -885,3 +886,51 @@ class Test6(Test5): _iterable = False assert iterable(Test6()) is False + + +def test_sequence_partitions(): + assert list(sequence_partitions([1], 1)) == [[[1]]] + assert list(sequence_partitions([1, 2], 1)) == [[[1, 2]]] + assert list(sequence_partitions([1, 2], 2)) == [[[1], [2]]] + assert list(sequence_partitions([1, 2, 3], 1)) == [[[1, 2, 3]]] + assert list(sequence_partitions([1, 2, 3], 2)) == \ + [[[1], [2, 3]], [[1, 2], [3]]] + assert list(sequence_partitions([1, 2, 3], 3)) == [[[1], [2], [3]]] + + # Exceptional cases + assert list(sequence_partitions([], 0)) == [] + assert list(sequence_partitions([], 1)) == [] + assert list(sequence_partitions([1, 2], 0)) == [] + assert list(sequence_partitions([1, 2], 3)) == [] + + +def test_sequence_partitions_empty(): + assert list(sequence_partitions_empty([], 1)) == [[[]]] + assert list(sequence_partitions_empty([], 2)) == [[[], []]] + assert list(sequence_partitions_empty([], 3)) == [[[], [], []]] + assert list(sequence_partitions_empty([1], 1)) == [[[1]]] + assert list(sequence_partitions_empty([1], 2)) == [[[], [1]], [[1], []]] + assert list(sequence_partitions_empty([1], 3)) == \ + [[[], [], [1]], [[], [1], []], [[1], [], []]] + assert list(sequence_partitions_empty([1, 2], 1)) == [[[1, 2]]] + assert list(sequence_partitions_empty([1, 2], 2)) == \ + [[[], [1, 2]], [[1], [2]], [[1, 2], []]] + assert list(sequence_partitions_empty([1, 2], 3)) == [ + [[], [], [1, 2]], [[], [1], [2]], [[], [1, 2], []], + [[1], [], [2]], [[1], [2], []], [[1, 2], [], []] + ] + assert list(sequence_partitions_empty([1, 2, 3], 1)) == [[[1, 2, 3]]] + assert list(sequence_partitions_empty([1, 2, 3], 2)) == \ + [[[], [1, 2, 3]], [[1], [2, 3]], [[1, 2], [3]], [[1, 2, 3], []]] + assert list(sequence_partitions_empty([1, 2, 3], 3)) == [ + [[], [], [1, 2, 3]], [[], [1], [2, 3]], + [[], [1, 2], [3]], [[], [1, 2, 3], []], + [[1], [], [2, 3]], [[1], [2], [3]], + [[1], [2, 3], []], [[1, 2], [], [3]], + [[1, 2], [3], []], [[1, 2, 3], [], []] + ] + + # Exceptional cases + assert list(sequence_partitions([], 0)) == [] + assert list(sequence_partitions([1], 0)) == [] + assert list(sequence_partitions([1, 2], 0)) == []
[ { "components": [ { "doc": "Returns the partition of sequence $l$ into $n$ bins\n\nExplanation\n===========\n\nGiven the sequence $l_1 \\cdots l_m \\in V^+$ where\n$V^+$ is the Kleene plus of $V$\n\nThe set of $n$ partitions of $l$ is defined as:\n\n.. math::\n \\{(s_1, \\cdots, s_n) | s_1 \\in V^+, \\cdots, s_n \\in V^+,\n s_1 \\cdots s_n = l_1 \\cdots l_m\\}\n\nParameters\n==========\n\nl : Sequence[T]\n A nonempty sequence of any Python objects\n\nn : int\n A positive integer\n\nYields\n======\n\nout : list[Sequence[T]]\n A list of sequences with concatenation equals $l$.\n This should conform with the type of $l$.\n\nExamples\n========\n\n>>> from sympy.utilities.iterables import sequence_partitions\n>>> for out in sequence_partitions([1, 2, 3, 4], 2):\n... print(out)\n[[1], [2, 3, 4]]\n[[1, 2], [3, 4]]\n[[1, 2, 3], [4]]\n\nNotes\n=====\n\nThis is modified version of EnricoGiampieri's partition generator\nfrom https://stackoverflow.com/questions/13131491/\n\nSee Also\n========\n\nsequence_partitions_empty", "lines": [ 2708, 2766 ], "name": "sequence_partitions", "signature": "def sequence_partitions(l, n, /):", "type": "function" }, { "doc": "Returns the partition of sequence $l$ into $n$ bins with\nempty sequence\n\nExplanation\n===========\n\nGiven the sequence $l_1 \\cdots l_m \\in V^*$ where\n$V^*$ is the Kleene star of $V$\n\nThe set of $n$ partitions of $l$ is defined as:\n\n.. math::\n \\{(s_1, \\cdots, s_n) | s_1 \\in V^*, \\cdots, s_n \\in V^*,\n s_1 \\cdots s_n = l_1 \\cdots l_m\\}\n\nThere are more combinations than :func:`sequence_partitions` because\nempty sequence can fill everywhere, so we try to provide different\nutility for this.\n\nParameters\n==========\n\nl : Sequence[T]\n A sequence of any Python objects (can be possibly empty)\n\nn : int\n A positive integer\n\nYields\n======\n\nout : list[Sequence[T]]\n A list of sequences with concatenation equals $l$.\n This should conform with the type of $l$.\n\nExamples\n========\n\n>>> from sympy.utilities.iterables import sequence_partitions_empty\n>>> for out in sequence_partitions_empty([1, 2, 3, 4], 2):\n... print(out)\n[[], [1, 2, 3, 4]]\n[[1], [2, 3, 4]]\n[[1, 2], [3, 4]]\n[[1, 2, 3], [4]]\n[[1, 2, 3, 4], []]\n\nSee Also\n========\n\nsequence_partitions", "lines": [ 2769, 2829 ], "name": "sequence_partitions_empty", "signature": "def sequence_partitions_empty(l, n, /):", "type": "function" } ], "file": "sympy/utilities/iterables.py" } ]
[ "test_deprecated_iterables", "test_is_palindromic", "test_flatten", "test_iproduct", "test_group", "test_subsets", "test_variations", "test_cartes", "test_filter_symbols", "test_numbered_symbols", "test_sift", "test_take", "test_dict_merge", "test_prefixes", "test_postfixes", "test_topological_sort", "test_strongly_connected_components", "test_connected_components", "test_rotate", "test_multiset_partitions", "test_multiset_combinations", "test_multiset_permutations", "test_partitions", "test_binary_partitions", "test_bell_perm", "test_involutions", "test_derangements", "test_necklaces", "test_bracelets", "test_generate_oriented_forest", "test_unflatten", "test_common_prefix_suffix", "test_minlex", "test_ordered", "test_runs", "test_reshape", "test_uniq", "test_kbins", "test_has_dups", "test__partition", "test_ordered_partitions", "test_rotations", "test_ibin", "test_iterable", "test_sequence_partitions" ]
[]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> Decompose partition utility from `kbins` <!-- Your title above should be a short description of what was changed. Do not include the issue number in the title. --> #### References to other Issues or PRs <!-- If this pull request fixes an issue, write "Fixes #NNNN" in that exact format, e.g. "Fixes #1234" (see https://tinyurl.com/auto-closing for more information). Also, please write a comment on that issue linking back to this pull request once it is open. --> #### Brief description of what is fixed or changed There are lots of utilities under name 'partition', but I find none of them are useful for some purpose, so I try to implement this and hope that this effort is not duplicated. I also implemented `sequence_partitions_empty` because it is needed for parsing, unification, pattern matching with empty sequences. I've also removed some redundant length check. This can make things little bit faster, but there could more faster algorithm to use, but at least it is not the responsibility for now #### Other comments #### Release Notes <!-- Write the release notes for this release below between the BEGIN and END statements. The basic format is a bulleted list with the name of the subpackage and the release note for this PR. For example: * solvers * Added a new solver for logarithmic equations. * functions * Fixed a bug with log of integers. or if no release note(s) should be included use: NO ENTRY See https://github.com/sympy/sympy/wiki/Writing-Release-Notes for more information on how to write release notes. The bot will check your release notes automatically to see if they are formatted correctly. --> <!-- BEGIN RELEASE NOTES --> - utilities - Added `sequence_partitions`, `sequence_partitions_empty` for generic partitioning of sequence into bins, with the option to partition into empty sequence respectively. <!-- END RELEASE NOTES --> ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in sympy/utilities/iterables.py] (definition of sequence_partitions:) def sequence_partitions(l, n, /): """Returns the partition of sequence $l$ into $n$ bins Explanation =========== Given the sequence $l_1 \cdots l_m \in V^+$ where $V^+$ is the Kleene plus of $V$ The set of $n$ partitions of $l$ is defined as: .. math:: \{(s_1, \cdots, s_n) | s_1 \in V^+, \cdots, s_n \in V^+, s_1 \cdots s_n = l_1 \cdots l_m\} Parameters ========== l : Sequence[T] A nonempty sequence of any Python objects n : int A positive integer Yields ====== out : list[Sequence[T]] A list of sequences with concatenation equals $l$. This should conform with the type of $l$. Examples ======== >>> from sympy.utilities.iterables import sequence_partitions >>> for out in sequence_partitions([1, 2, 3, 4], 2): ... print(out) [[1], [2, 3, 4]] [[1, 2], [3, 4]] [[1, 2, 3], [4]] Notes ===== This is modified version of EnricoGiampieri's partition generator from https://stackoverflow.com/questions/13131491/ See Also ======== sequence_partitions_empty""" (definition of sequence_partitions_empty:) def sequence_partitions_empty(l, n, /): """Returns the partition of sequence $l$ into $n$ bins with empty sequence Explanation =========== Given the sequence $l_1 \cdots l_m \in V^*$ where $V^*$ is the Kleene star of $V$ The set of $n$ partitions of $l$ is defined as: .. math:: \{(s_1, \cdots, s_n) | s_1 \in V^*, \cdots, s_n \in V^*, s_1 \cdots s_n = l_1 \cdots l_m\} There are more combinations than :func:`sequence_partitions` because empty sequence can fill everywhere, so we try to provide different utility for this. Parameters ========== l : Sequence[T] A sequence of any Python objects (can be possibly empty) n : int A positive integer Yields ====== out : list[Sequence[T]] A list of sequences with concatenation equals $l$. This should conform with the type of $l$. Examples ======== >>> from sympy.utilities.iterables import sequence_partitions_empty >>> for out in sequence_partitions_empty([1, 2, 3, 4], 2): ... print(out) [[], [1, 2, 3, 4]] [[1], [2, 3, 4]] [[1, 2], [3, 4]] [[1, 2, 3], [4]] [[1, 2, 3, 4], []] See Also ======== sequence_partitions""" [end of new definitions in sympy/utilities/iterables.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
22520ed5f4a9b2b6c4b6b314b4748878f1b4b662
tobymao__sqlglot-858
858
tobymao/sqlglot
null
6e4c0ef48ab0db1a336d634273dab35de17c80bc
2022-12-28T22:32:11Z
diff --git a/sqlglot/expressions.py b/sqlglot/expressions.py index 701abb0ff4..888c4fc48d 100644 --- a/sqlglot/expressions.py +++ b/sqlglot/expressions.py @@ -1337,7 +1337,7 @@ def with_( "group": False, "having": False, "qualify": False, - "window": False, + "windows": False, "distribute": False, "sort": False, "cluster": False, @@ -1910,6 +1910,18 @@ def having(self, *expressions, append=True, dialect=None, copy=True, **opts) -> **opts, ) + def window(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: + return _apply_list_builder( + *expressions, + instance=self, + arg="windows", + append=append, + into=Window, + dialect=dialect, + copy=copy, + **opts, + ) + def distinct(self, distinct=True, copy=True) -> Select: """ Set the OFFSET expression. diff --git a/sqlglot/parser.py b/sqlglot/parser.py index f2251b4296..a985d84beb 100644 --- a/sqlglot/parser.py +++ b/sqlglot/parser.py @@ -402,6 +402,7 @@ class Parser(metaclass=_Parser): exp.Ordered: lambda self: self._parse_ordered(), exp.Having: lambda self: self._parse_having(), exp.With: lambda self: self._parse_with(), + exp.Window: lambda self: self._parse_named_window(), "JOIN_TYPE": lambda self: self._parse_join_side_and_kind(), } @@ -550,8 +551,7 @@ class Parser(metaclass=_Parser): "group": lambda self: self._parse_group(), "having": lambda self: self._parse_having(), "qualify": lambda self: self._parse_qualify(), - "windows": lambda self: self._match(TokenType.WINDOW) - and self._parse_csv(lambda: self._parse_window(self._parse_id_var(), alias=True)), + "windows": lambda self: self._parse_window_clause(), "distribute": lambda self: self._parse_sort(TokenType.DISTRIBUTE_BY, exp.Distribute), "sort": lambda self: self._parse_sort(TokenType.SORT_BY, exp.Sort), "cluster": lambda self: self._parse_sort(TokenType.CLUSTER_BY, exp.Cluster), @@ -2440,6 +2440,12 @@ def _parse_trim(self): collation=collation, ) + def _parse_window_clause(self): + return self._match(TokenType.WINDOW) and self._parse_csv(lambda: self._parse_named_window()) + + def _parse_named_window(self): + return self._parse_window(self._parse_id_var(), alias=True) + def _parse_window(self, this, alias=False): if self._match(TokenType.FILTER): where = self._parse_wrapped(self._parse_where)
diff --git a/tests/test_build.py b/tests/test_build.py index b014a3ab0c..a1a268ded6 100644 --- a/tests/test_build.py +++ b/tests/test_build.py @@ -481,6 +481,19 @@ def test_build(self): ), (lambda: exp.delete("y", where="x > 1"), "DELETE FROM y WHERE x > 1"), (lambda: exp.delete("y", where=exp.and_("x > 1")), "DELETE FROM y WHERE x > 1"), + ( + lambda: select("AVG(a) OVER b") + .from_("table") + .window("b AS (PARTITION BY c ORDER BY d)"), + "SELECT AVG(a) OVER b FROM table WINDOW b AS (PARTITION BY c ORDER BY d)", + ), + ( + lambda: select("AVG(a) OVER b", "MIN(c) OVER d") + .from_("table") + .window("b AS (PARTITION BY e ORDER BY f)") + .window("d AS (PARTITION BY g ORDER BY h)"), + "SELECT AVG(a) OVER b, MIN(c) OVER d FROM table WINDOW b AS (PARTITION BY e ORDER BY f), d AS (PARTITION BY g ORDER BY h)", + ), ]: with self.subTest(sql): self.assertEqual(expression().sql(dialect[0] if dialect else None), sql)
[ { "components": [ { "doc": "", "lines": [ 1913, 1922 ], "name": "Select.window", "signature": "def window(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:", "type": "function" } ], "file": "sqlglot/expressions.py" }, { "components": [ { "doc": "", "lines": [ 2443, 2444 ], "name": "Parser._parse_window_clause", "signature": "def _parse_window_clause(self):", "type": "function" }, { "doc": "", "lines": [ 2446, 2447 ], "name": "Parser._parse_named_window", "signature": "def _parse_named_window(self):", "type": "function" } ], "file": "sqlglot/parser.py" } ]
[ "tests/test_build.py::TestBuild::test_build" ]
[]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> Add a window clause builder to Select. A few comments about this PR: * The argument to Select used everywhere else in the code was `windows`, so I updated `QUERY_MODIFIERS` to reflect that. * I had `window(...)` follow the same pattern as other builders of lists of expressions. * I needed a parse function that would return one named `Window` expression. * So I split out `_parse_named_window(...)` for that purpose -- and it's the registered parser for Window expressions. Which might be confusing -- given that window expressions can take a lot of forms. In the future it might make sense to have `NamedWindow` as a separate expression, or `WindowClause` or something of the sort. Not sure if you want to do that now, or if this is sufficient. ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in sqlglot/expressions.py] (definition of Select.window:) def window(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: [end of new definitions in sqlglot/expressions.py] [start of new definitions in sqlglot/parser.py] (definition of Parser._parse_window_clause:) def _parse_window_clause(self): (definition of Parser._parse_named_window:) def _parse_named_window(self): [end of new definitions in sqlglot/parser.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
ceb42fabad60312699e4b15936aeebac00e22e4d
django__django-16369
16,369
django/django
4.2
ab7a85ac297464df82d8363455609979ca3603db
2022-12-07T15:09:14Z
diff --git a/django/contrib/sitemaps/__init__.py b/django/contrib/sitemaps/__init__.py index 3d276b60d490..df57f1cd5c70 100644 --- a/django/contrib/sitemaps/__init__.py +++ b/django/contrib/sitemaps/__init__.py @@ -92,6 +92,10 @@ def _get(self, name, item, default=None): return attr(item) return attr + def get_languages_for_item(self, item): + """Languages for which this item is displayed.""" + return self._languages() + def _languages(self): if self.languages is not None: return self.languages @@ -103,8 +107,8 @@ def _items(self): # This is necessary to paginate with all languages already considered. items = [ (item, lang_code) - for lang_code in self._languages() for item in self.items() + for lang_code in self.get_languages_for_item(item) ] return items return self.items() @@ -201,7 +205,8 @@ def _urls(self, page, protocol, domain): } if self.i18n and self.alternates: - for lang_code in self._languages(): + item_languages = self.get_languages_for_item(item[0]) + for lang_code in item_languages: loc = f"{protocol}://{domain}{self._location(item, lang_code)}" url_info["alternates"].append( { @@ -209,7 +214,7 @@ def _urls(self, page, protocol, domain): "lang_code": lang_code, } ) - if self.x_default: + if self.x_default and settings.LANGUAGE_CODE in item_languages: lang_code = settings.LANGUAGE_CODE loc = f"{protocol}://{domain}{self._location(item, lang_code)}" loc = loc.replace(f"/{lang_code}/", "/", 1) diff --git a/docs/ref/contrib/sitemaps.txt b/docs/ref/contrib/sitemaps.txt index d3225405a38d..7dc3dced5183 100644 --- a/docs/ref/contrib/sitemaps.txt +++ b/docs/ref/contrib/sitemaps.txt @@ -311,6 +311,15 @@ Note: The latest ``lastmod`` returned by calling the method with all items returned by :meth:`Sitemap.items`. + .. method:: Sitemap.get_languages_for_item(item, lang_code) + + .. versionadded:: 4.2 + + **Optional.** A method that returns the sequence of language codes for + which the item is displayed. By default + :meth:`~Sitemap.get_languages_for_item` returns + :attr:`~Sitemap.languages`. + Shortcuts ========= diff --git a/docs/releases/4.2.txt b/docs/releases/4.2.txt index 682fce2a5362..7e93df0702ce 100644 --- a/docs/releases/4.2.txt +++ b/docs/releases/4.2.txt @@ -145,7 +145,8 @@ Minor features :mod:`django.contrib.sitemaps` ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -* ... +* The new :meth:`.Sitemap.get_languages_for_item` method allows customizing the + list of languages for which the item is displayed. :mod:`django.contrib.sites` ~~~~~~~~~~~~~~~~~~~~~~~~~~~
diff --git a/tests/sitemaps_tests/test_http.py b/tests/sitemaps_tests/test_http.py index 8c16f66896bd..12e387757be7 100644 --- a/tests/sitemaps_tests/test_http.py +++ b/tests/sitemaps_tests/test_http.py @@ -10,7 +10,7 @@ from django.utils.formats import localize from .base import SitemapTestsBase -from .models import TestModel +from .models import I18nTestModel, TestModel class HTTPSitemapTests(SitemapTestsBase): @@ -440,6 +440,72 @@ def test_alternate_i18n_sitemap_xdefault(self): ) self.assertXMLEqual(response.content.decode(), expected_content) + @override_settings(LANGUAGES=(("en", "English"), ("pt", "Portuguese"))) + def test_language_for_item_i18n_sitemap(self): + """ + A i18n sitemap index in which item can be chosen to be displayed for a + lang or not. + """ + only_pt = I18nTestModel.objects.create(name="Only for PT") + response = self.client.get("/item-by-lang/i18n.xml") + url, pk, only_pt_pk = self.base_url, self.i18n_model.pk, only_pt.pk + expected_urls = ( + f"<url><loc>{url}/en/i18n/testmodel/{pk}/</loc>" + f"<changefreq>never</changefreq><priority>0.5</priority></url>" + f"<url><loc>{url}/pt/i18n/testmodel/{pk}/</loc>" + f"<changefreq>never</changefreq><priority>0.5</priority></url>" + f"<url><loc>{url}/pt/i18n/testmodel/{only_pt_pk}/</loc>" + f"<changefreq>never</changefreq><priority>0.5</priority></url>" + ) + expected_content = ( + f'<?xml version="1.0" encoding="UTF-8"?>\n' + f'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" ' + f'xmlns:xhtml="http://www.w3.org/1999/xhtml">\n' + f"{expected_urls}\n" + f"</urlset>" + ) + self.assertXMLEqual(response.content.decode(), expected_content) + + @override_settings(LANGUAGES=(("en", "English"), ("pt", "Portuguese"))) + def test_alternate_language_for_item_i18n_sitemap(self): + """ + A i18n sitemap index in which item can be chosen to be displayed for a + lang or not. + """ + only_pt = I18nTestModel.objects.create(name="Only for PT") + response = self.client.get("/item-by-lang-alternates/i18n.xml") + url, pk, only_pt_pk = self.base_url, self.i18n_model.pk, only_pt.pk + expected_urls = ( + f"<url><loc>{url}/en/i18n/testmodel/{pk}/</loc>" + f"<changefreq>never</changefreq><priority>0.5</priority>" + f'<xhtml:link rel="alternate" ' + f'hreflang="en" href="{url}/en/i18n/testmodel/{pk}/"/>' + f'<xhtml:link rel="alternate" ' + f'hreflang="pt" href="{url}/pt/i18n/testmodel/{pk}/"/>' + f'<xhtml:link rel="alternate" ' + f'hreflang="x-default" href="{url}/i18n/testmodel/{pk}/"/></url>' + f"<url><loc>{url}/pt/i18n/testmodel/{pk}/</loc>" + f"<changefreq>never</changefreq><priority>0.5</priority>" + f'<xhtml:link rel="alternate" ' + f'hreflang="en" href="{url}/en/i18n/testmodel/{pk}/"/>' + f'<xhtml:link rel="alternate" ' + f'hreflang="pt" href="{url}/pt/i18n/testmodel/{pk}/"/>' + f'<xhtml:link rel="alternate" ' + f'hreflang="x-default" href="{url}/i18n/testmodel/{pk}/"/></url>' + f"<url><loc>{url}/pt/i18n/testmodel/{only_pt_pk}/</loc>" + f"<changefreq>never</changefreq><priority>0.5</priority>" + f'<xhtml:link rel="alternate" ' + f'hreflang="pt" href="{url}/pt/i18n/testmodel/{only_pt_pk}/"/></url>' + ) + expected_content = ( + f'<?xml version="1.0" encoding="UTF-8"?>\n' + f'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" ' + f'xmlns:xhtml="http://www.w3.org/1999/xhtml">\n' + f"{expected_urls}\n" + f"</urlset>" + ) + self.assertXMLEqual(response.content.decode(), expected_content) + def test_sitemap_without_entries(self): response = self.client.get("/sitemap-without-entries/sitemap.xml") expected_content = ( diff --git a/tests/sitemaps_tests/urls/http.py b/tests/sitemaps_tests/urls/http.py index 75dd4834c0a5..2b512cfd6918 100644 --- a/tests/sitemaps_tests/urls/http.py +++ b/tests/sitemaps_tests/urls/http.py @@ -48,6 +48,22 @@ class XDefaultI18nSitemap(AlternatesI18nSitemap): x_default = True +class ItemByLangSitemap(SimpleI18nSitemap): + def get_languages_for_item(self, item): + if item.name == "Only for PT": + return ["pt"] + return super().get_languages_for_item(item) + + +class ItemByLangAlternatesSitemap(AlternatesI18nSitemap): + x_default = True + + def get_languages_for_item(self, item): + if item.name == "Only for PT": + return ["pt"] + return super().get_languages_for_item(item) + + class EmptySitemap(Sitemap): changefreq = "never" priority = 0.5 @@ -168,6 +184,14 @@ def testmodelview(request, id): "i18n-xdefault": XDefaultI18nSitemap, } +item_by_lang_i18n_sitemaps = { + "i18n-item-by-lang": ItemByLangSitemap, +} + +item_by_lang_alternates_i18n_sitemaps = { + "i18n-item-by-lang-alternates": ItemByLangAlternatesSitemap, +} + simple_sitemaps_not_callable = { "simple": SimpleSitemap(), } @@ -358,6 +382,18 @@ def testmodelview(request, id): {"sitemaps": sitemaps_lastmod_ascending}, name="django.contrib.sitemaps.views.sitemap", ), + path( + "item-by-lang/i18n.xml", + views.sitemap, + {"sitemaps": item_by_lang_i18n_sitemaps}, + name="django.contrib.sitemaps.views.sitemap", + ), + path( + "item-by-lang-alternates/i18n.xml", + views.sitemap, + {"sitemaps": item_by_lang_alternates_i18n_sitemaps}, + name="django.contrib.sitemaps.views.sitemap", + ), path( "lastmod-sitemaps/descending.xml", views.sitemap,
diff --git a/docs/ref/contrib/sitemaps.txt b/docs/ref/contrib/sitemaps.txt index d3225405a38d..7dc3dced5183 100644 --- a/docs/ref/contrib/sitemaps.txt +++ b/docs/ref/contrib/sitemaps.txt @@ -311,6 +311,15 @@ Note: The latest ``lastmod`` returned by calling the method with all items returned by :meth:`Sitemap.items`. + .. method:: Sitemap.get_languages_for_item(item, lang_code) + + .. versionadded:: 4.2 + + **Optional.** A method that returns the sequence of language codes for + which the item is displayed. By default + :meth:`~Sitemap.get_languages_for_item` returns + :attr:`~Sitemap.languages`. + Shortcuts ========= diff --git a/docs/releases/4.2.txt b/docs/releases/4.2.txt index 682fce2a5362..7e93df0702ce 100644 --- a/docs/releases/4.2.txt +++ b/docs/releases/4.2.txt @@ -145,7 +145,8 @@ Minor features :mod:`django.contrib.sitemaps` ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -* ... +* The new :meth:`.Sitemap.get_languages_for_item` method allows customizing the + list of languages for which the item is displayed. :mod:`django.contrib.sites` ~~~~~~~~~~~~~~~~~~~~~~~~~~~
[ { "components": [ { "doc": "Languages for which this item is displayed.", "lines": [ 95, 97 ], "name": "Sitemap.get_languages_for_item", "signature": "def get_languages_for_item(self, item):", "type": "function" } ], "file": "django/contrib/sitemaps/__init__.py" } ]
[ "A i18n sitemap index in which item can be chosen to be displayed for a" ]
[ "A simple sitemap index can be rendered with a custom template", "test_simple_sitemap_custom_index_warning (sitemaps_tests.test_http.DeprecatedTests)", "A i18n sitemap with alternate/hreflang links can be rendered.", "A i18n sitemap index with limited languages can be rendered.", "A i18n sitemap index with x-default can be rendered.", "A cached sitemap index can be rendered (#2713).", "All items in the sitemap have `lastmod`. The `Last-Modified` header", "test_callable_sitemod_no_items (sitemaps_tests.test_http.HTTPSitemapTests)", "Not all items have `lastmod`. Therefore the `Last-Modified` header", "test_empty_page (sitemaps_tests.test_http.HTTPSitemapTests)", "test_empty_sitemap (sitemaps_tests.test_http.HTTPSitemapTests)", "The priority value should not be localized.", "test_no_section (sitemaps_tests.test_http.HTTPSitemapTests)", "test_page_not_int (sitemaps_tests.test_http.HTTPSitemapTests)", "A sitemap may have multiple pages.", "test_requestsite_sitemap (sitemaps_tests.test_http.HTTPSitemapTests)", "A simple sitemap can be rendered with a custom template", "A simple i18n sitemap index can be rendered, without logging variable", "A simple sitemap can be rendered", "A simple sitemap index can be rendered", "A simple sitemap section can be rendered", "sitemapindex.lastmod is included when Sitemap.lastmod is", "sitemapindex.lastmod is omitted when Sitemap.lastmod is", "Check we get ImproperlyConfigured if we don't pass a site object to", "Check we get ImproperlyConfigured when we don't pass a site object to", "Check to make sure that the raw item is included with each", "Last-Modified header is set correctly", "The Last-Modified header should be support dates (without time).", "Last-Modified header is missing when sitemap has no lastmod", "Last-Modified header is omitted when lastmod not on all items", "The Last-Modified header should be converted from timezone aware dates", "lastmod datestamp shows timezones if Sitemap.get_latest_lastmod", "A sitemap may not be callable.", "test_sitemap_without_entries (sitemaps_tests.test_http.HTTPSitemapTests)", "The Last-Modified header is set to the most recent sitemap lastmod.", "The Last-Modified header is omitted when lastmod isn't found in all", "test_x_robots_sitemap (sitemaps_tests.test_http.HTTPSitemapTests)" ]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> Fixed #33662 -- Allowed Sitemap to customize languages for each item. [ticket #33662 : Choose which items are displayed per language in Sitemap ](https://code.djangoproject.com/ticket/33662) ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in django/contrib/sitemaps/__init__.py] (definition of Sitemap.get_languages_for_item:) def get_languages_for_item(self, item): """Languages for which this item is displayed.""" [end of new definitions in django/contrib/sitemaps/__init__.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
Here is the discussion in the issues of the pull request. <issues> Choose which items are displayed per language in Sitemap Description The current implementation of Sitemap is : if we use i18n, then we display a cartesian product between some items and some languages. There is no way to use the provided i18n automation if we want to display some items depending on the language (for instance non-translated blog articles). I precise in my case, urls are translated, so given a language the url may not exist or raise an error. ---------- OK, sounds reasonable to at least look at. Would you care to take on a patch? In either case could you perhaps expand the description to include a minimal reproduce setup so that someone picking it up had a few breadcrumbs to follow? Thanks! I would like to tackle this new feature, it sounds interesting. As Carlton Gibson said, could you expand please the description, so I can fully understand the idea of the new feature?. For instance, on which scenario the URLs get translated? (Not sure, but this maybe sounds more like an error than a future). It does sound as a new feature, being able to display some items depending on the language, by this do you mean like for example, only translate a menu or only translate what is inside a <div> or something similar? Please expand your idea. -------------------- </issues>
016bead6a23989adec5c7ee6948db7ce2fc5e89b
pyvista__pyvista-3662
3,662
pyvista/pyvista
0.38
f5dbce80bc44ff3def8c5eb15db054706fc5f38d
2022-11-30T22:23:05Z
diff --git a/pyvista/plotting/camera.py b/pyvista/plotting/camera.py index 915893c4d2d..d7f237ff98f 100644 --- a/pyvista/plotting/camera.py +++ b/pyvista/plotting/camera.py @@ -1,5 +1,11 @@ """Module containing pyvista implementation of vtkCamera.""" +from __future__ import annotations + +from pathlib import Path +from typing import Union from weakref import proxy +import xml.dom.minidom as md +from xml.etree import ElementTree import numpy as np @@ -88,6 +94,128 @@ def __del__(self): self.RemoveAllObservers() self.parent = None + @classmethod + def from_paraview_pvcc(cls, filename: Union[str, Path]) -> Camera: + """Load a Paraview camera file (.pvcc extension). + + Returns a pyvista.Camera object for which attributes has been read + from the filename argument. + + Parameters + ---------- + filename : str or pathlib.Path + Path to Paraview camera file (.pvcc). + + Examples + -------- + >>> import pyvista as pv + >>> pl = pv.Plotter() + >>> pl.camera = pv.Camera.from_paraview_pvcc("camera.pvcc") # doctest:+SKIP + >>> pl.camera.position + (1.0, 1.0, 1.0) + """ + to_find = { + "CameraPosition": ("position", float), + "CameraFocalPoint": ("focal_point", float), + "CameraViewAngle": ("view_angle", float), + "CameraViewUp": ("up", float), + "CameraParallelProjection": ("parallel_projection", int), + "CameraParallelScale": ("parallel_scale", float), + } + camera = cls() + + tree = ElementTree.parse(filename) + root = tree.getroot()[0] + for element in root: + attrib = element.attrib + attrib_name = attrib["name"] + + if attrib_name in to_find: + name, typ = to_find[attrib_name] + nelems = int(attrib["number_of_elements"]) + + # Set the camera attributes + if nelems == 3: + values = [typ(e.attrib["value"]) for e in element] + setattr(camera, name, values) + elif nelems == 1: + + # Special case for bool since bool("0") returns True. + # So first convert to int from `to_find` and then apply bool + if "name" in element[-1].attrib and element[-1].attrib["name"] == "bool": + val = bool(typ(element[0].attrib["value"])) + else: + val = typ(element[0].attrib["value"]) + setattr(camera, name, val) + + return camera + + def to_paraview_pvcc(self, filename: Union[str, Path]): + """Write the camera parameters to a Paraview camera file (.pvcc extension). + + Parameters + ---------- + filename : str or pathlib.Path + Path to Paraview camera file (.pvcc). + + Examples + -------- + >>> import pyvista as pv + >>> pl = pv.Plotter() + >>> pl.camera.to_paraview_pvcc("camera.pvcc") + """ + root = ElementTree.Element("PVCameraConfiguration") + root.attrib["description"] = "ParaView camera configuration" + root.attrib["version"] = "1.0" + + dico = dict(group="views", type="RenderView", id="0", servers="21") + proxy = ElementTree.SubElement(root, "Proxy", dico) + + # Add tuples + to_find = { + "CameraPosition": "position", + "CameraFocalPoint": "focal_point", + "CameraViewUp": "up", + } + for name, attr in to_find.items(): + e = ElementTree.SubElement( + proxy, "Property", dict(name=name, id=f"0.{name}", number_of_elements="3") + ) + + for i in range(3): + tmp = ElementTree.Element("Element") + tmp.attrib["index"] = str(i) + tmp.attrib["value"] = str(getattr(self, attr)[i]) + e.append(tmp) + + # Add single values + to_find = { + "CameraViewAngle": "view_angle", + "CameraParallelScale": "parallel_scale", + "CameraParallelProjection": "parallel_projection", + } + + for name, attr in to_find.items(): + e = ElementTree.SubElement( + proxy, "Property", dict(name=name, id=f"0.{name}", number_of_elements="1") + ) + tmp = ElementTree.Element("Element") + tmp.attrib["index"] = "0" + + val = getattr(self, attr) + if type(val) is not bool: + tmp.attrib["value"] = str(val) + e.append(tmp) + else: + tmp.attrib["value"] = "1" if val else "0" + e.append(tmp) + e.append(ElementTree.Element("Domain", dict(name="bool", id=f"0.{name}.bool"))) + + xmlstr = ElementTree.tostring(root).decode() + newxml = md.parseString(xmlstr) + with open(filename, 'w') as outfile: + outfile.write(newxml.toprettyxml(indent='\t', newl='\n')) + @property def position(self): """Return or set the position of the camera in world coordinates.
diff --git a/tests/test_camera.py b/tests/test_camera.py index 5259c0d9a77..6690f47db63 100644 --- a/tests/test_camera.py +++ b/tests/test_camera.py @@ -1,3 +1,5 @@ +import io + import numpy as np import pytest @@ -22,11 +24,81 @@ def camera(): return pyvista.Camera() +@pytest.fixture() +def paraview_pvcc(): + """Fixture returning a paraview camera file with values of the position""" + + tmp = """ + <PVCameraConfiguration description="ParaView camera configuration" version="1.0"> + <Proxy group="views" type="RenderView" id="6395" servers="21"> + <Property name="CameraPosition" id="6395.CameraPosition" number_of_elements="3"> + <Element index="0" value="10.519087611966333"/> + <Element index="1" value="40.74973775632195"/> + <Element index="2" value="-20.24019652397463"/> + </Property> + <Property name="CameraFocalPoint" id="6395.CameraFocalPoint" number_of_elements="3"> + <Element index="0" value="15.335762892470676"/> + <Element index="1" value="-26.960151717473682"/> + <Element index="2" value="17.860905595181094"/> + </Property> + <Property name="CameraViewUp" id="6395.CameraViewUp" number_of_elements="3"> + <Element index="0" value="0.2191945908188539"/> + <Element index="1" value="-0.4665856879512876"/> + <Element index="2" value="-0.8568847805596613"/> + </Property> + <Property name="CenterOfRotation" id="6395.CenterOfRotation" number_of_elements="3"> + <Element index="0" value="15.039424359798431"/> + <Element index="1" value="-7.047080755233765"/> + <Element index="2" value="6.712674975395203"/> + </Property> + <Property name="RotationFactor" id="6395.RotationFactor" number_of_elements="1"> + <Element index="0" value="1"/> + </Property> + <Property name="CameraViewAngle" id="6395.CameraViewAngle" number_of_elements="1"> + <Element index="0" value="30"/> + </Property> + <Property name="CameraParallelScale" id="6395.CameraParallelScale" number_of_elements="1"> + <Element index="0" value="20.147235678333413"/> + </Property> + <Property name="CameraParallelProjection" id="6395.CameraParallelProjection" number_of_elements="1"> + <Element index="0" value="0"/> + <Domain name="bool" id="6395.CameraParallelProjection.bool"/> + </Property> + </Proxy> + </PVCameraConfiguration>""" + position = [10.519087611966333, 40.74973775632195, -20.24019652397463] + focal = [15.335762892470676, -26.960151717473682, 17.860905595181094] + view_up = [0.2191945908188539, -0.4665856879512876, -0.8568847805596613] + view_angle = 30 + parallel_scale = 20.147235678333413 + projection = False + + return io.StringIO(tmp), position, focal, view_up, view_angle, parallel_scale, projection + + def test_invalid_init(): with pytest.raises(TypeError): pyvista.Camera(1) +def test_camera_fom_paraview_pvcc(paraview_pvcc): + camera = pyvista.Camera.from_paraview_pvcc(paraview_pvcc[0]) + assert camera.position == pytest.approx(paraview_pvcc[1]) + assert camera.focal_point == pytest.approx(paraview_pvcc[2]) + assert camera.up == pytest.approx(paraview_pvcc[3]) + assert camera.view_angle == paraview_pvcc[4] + assert camera.parallel_scale == paraview_pvcc[-2] + assert camera.parallel_projection == paraview_pvcc[-1] + + +def test_camera_to_paraview_pvcc(camera, tmp_path): + fname = tmp_path / "test.pvcc" + camera.to_paraview_pvcc(fname) + assert fname.exists() + ocamera = pyvista.Camera.from_paraview_pvcc(fname) + assert ocamera == camera + + def test_camera_position(camera): position = np.random.random(3) camera.position = position
[ { "components": [ { "doc": "Load a Paraview camera file (.pvcc extension).\n\nReturns a pyvista.Camera object for which attributes has been read\nfrom the filename argument.\n\nParameters\n----------\nfilename : str or pathlib.Path\n Path to Paraview camera file (.pvcc).\n\nExamples\n--------\n>>> import pyvista as pv\n>>> pl = pv.Plotter()\n>>> pl.camera = pv.Camera.from_paraview_pvcc(\"camera.pvcc\") # doctest:+SKIP\n>>> pl.camera.position\n(1.0, 1.0, 1.0)", "lines": [ 98, 151 ], "name": "Camera.from_paraview_pvcc", "signature": "def from_paraview_pvcc(cls, filename: Union[str, Path]) -> Camera:", "type": "function" }, { "doc": "Write the camera parameters to a Paraview camera file (.pvcc extension).\n\nParameters\n----------\nfilename : str or pathlib.Path\n Path to Paraview camera file (.pvcc).\n\nExamples\n--------\n>>> import pyvista as pv\n>>> pl = pv.Plotter()\n>>> pl.camera.to_paraview_pvcc(\"camera.pvcc\")", "lines": [ 153, 217 ], "name": "Camera.to_paraview_pvcc", "signature": "def to_paraview_pvcc(self, filename: Union[str, Path]):", "type": "function" } ], "file": "pyvista/plotting/camera.py" } ]
[ "tests/test_camera.py::test_camera_fom_paraview_pvcc", "tests/test_camera.py::test_camera_to_paraview_pvcc" ]
[ "tests/test_camera.py::test_invalid_init", "tests/test_camera.py::test_camera_position", "tests/test_camera.py::test_focal_point", "tests/test_camera.py::test_model_transform_matrix", "tests/test_camera.py::test_distance", "tests/test_camera.py::test_thickness", "tests/test_camera.py::test_parallel_scale", "tests/test_camera.py::test_zoom", "tests/test_camera.py::test_up", "tests/test_camera.py::test_enable_parallel_projection", "tests/test_camera.py::test_disable_parallel_projection", "tests/test_camera.py::test_clipping_range", "tests/test_camera.py::test_reset_clipping_range", "tests/test_camera.py::test_view_angle", "tests/test_camera.py::test_direction", "tests/test_camera.py::test_view_frustum", "tests/test_camera.py::test_roll", "tests/test_camera.py::test_elevation", "tests/test_camera.py::test_azimuth", "tests/test_camera.py::test_eq", "tests/test_camera.py::test_copy" ]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> Add classmethod to read pvcc paraview ### Overview This PR implements a _classmethod_ to **pyvista.Camera** that reads a Paraview camera file (.pvcc). It looks like: ```python camera = pyvista.Camera.from_paraview_pvcc("file.pvcc") ``` See attached pvcc file as example (outputted with Paraview 5.10). ```<?xml version="1.0"?> <PVCameraConfiguration description="ParaView camera configuration" version="1.0"> <Proxy group="views" type="RenderView" id="6395" servers="21"> <Property name="CameraPosition" id="6395.CameraPosition" number_of_elements="3"> <Element index="0" value="10.519087611966333"/> <Element index="1" value="40.74973775632195"/> <Element index="2" value="-20.24019652397463"/> </Property> <Property name="CameraFocalPoint" id="6395.CameraFocalPoint" number_of_elements="3"> <Element index="0" value="15.335762892470676"/> <Element index="1" value="-26.960151717473682"/> <Element index="2" value="17.860905595181094"/> </Property> <Property name="CameraViewUp" id="6395.CameraViewUp" number_of_elements="3"> <Element index="0" value="0.2191945908188539"/> <Element index="1" value="-0.4665856879512876"/> <Element index="2" value="-0.8568847805596613"/> </Property> <Property name="CenterOfRotation" id="6395.CenterOfRotation" number_of_elements="3"> <Element index="0" value="15.039424359798431"/> <Element index="1" value="-7.047080755233765"/> <Element index="2" value="6.712674975395203"/> </Property> <Property name="RotationFactor" id="6395.RotationFactor" number_of_elements="1"> <Element index="0" value="1"/> </Property> <Property name="CameraViewAngle" id="6395.CameraViewAngle" number_of_elements="1"> <Element index="0" value="30"/> </Property> <Property name="CameraParallelScale" id="6395.CameraParallelScale" number_of_elements="1"> <Element index="0" value="20.147235678333413"/> </Property> <Property name="CameraParallelProjection" id="6395.CameraParallelProjection" number_of_elements="1"> <Element index="0" value="0"/> <Domain name="bool" id="6395.CameraParallelProjection.bool"/> </Property> </Proxy> </PVCameraConfiguration> ``` ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in pyvista/plotting/camera.py] (definition of Camera.from_paraview_pvcc:) def from_paraview_pvcc(cls, filename: Union[str, Path]) -> Camera: """Load a Paraview camera file (.pvcc extension). Returns a pyvista.Camera object for which attributes has been read from the filename argument. Parameters ---------- filename : str or pathlib.Path Path to Paraview camera file (.pvcc). Examples -------- >>> import pyvista as pv >>> pl = pv.Plotter() >>> pl.camera = pv.Camera.from_paraview_pvcc("camera.pvcc") # doctest:+SKIP >>> pl.camera.position (1.0, 1.0, 1.0)""" (definition of Camera.to_paraview_pvcc:) def to_paraview_pvcc(self, filename: Union[str, Path]): """Write the camera parameters to a Paraview camera file (.pvcc extension). Parameters ---------- filename : str or pathlib.Path Path to Paraview camera file (.pvcc). Examples -------- >>> import pyvista as pv >>> pl = pv.Plotter() >>> pl.camera.to_paraview_pvcc("camera.pvcc")""" [end of new definitions in pyvista/plotting/camera.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
e7f7ada0477439ebd725d56ca080ee85ca50d640
pvlib__pvlib-python-1585
1,585
pvlib/pvlib-python
0.8
e6e5b043f5f59af1c5fde0f25cc1793d79caa78b
2022-11-02T19:51:38Z
diff --git a/docs/sphinx/source/reference/pv_modeling.rst b/docs/sphinx/source/reference/pv_modeling.rst index 4e57130711..797681ce23 100644 --- a/docs/sphinx/source/reference/pv_modeling.rst +++ b/docs/sphinx/source/reference/pv_modeling.rst @@ -186,6 +186,7 @@ Utilities for working with IV curve data :toctree: generated/ ivtools.utils.rectify_iv_curve + ivtools.utils.astm_e1036 Other ----- diff --git a/docs/sphinx/source/whatsnew/v0.9.4.rst b/docs/sphinx/source/whatsnew/v0.9.4.rst index ecb659ccc9..cebb864758 100644 --- a/docs/sphinx/source/whatsnew/v0.9.4.rst +++ b/docs/sphinx/source/whatsnew/v0.9.4.rst @@ -45,6 +45,8 @@ Enhancements in a simplified way, using the Faiman model as an example. :py:func:`~pvlib.temperature.faiman_rad` (:issue:`1594`, :pull:`1595`) +* Add a function :py:func:`pvlib.ivtools.utils.astm_e1036` to perform ASTM E1036 extraction of IV + curve parameters (:pull:`1585`) Bug fixes ~~~~~~~~~ @@ -78,6 +80,7 @@ Contributors * Christian Orner (:ghuser:`chrisorner`) * Saurabh Aneja (:ghuser:`spaneja`) * Marcus Boumans (:ghuser:`bowie2211`) +* Michael Deceglie (:ghuser:`mdeceglie`) * Yu Xie (:ghuser:`xieyupku`) * Anton Driesse (:ghuser:`adriesse`) * Cliff Hansen (:ghuser:`cwhanse`) diff --git a/pvlib/ivtools/utils.py b/pvlib/ivtools/utils.py index 17eefa31a0..554af24ecc 100644 --- a/pvlib/ivtools/utils.py +++ b/pvlib/ivtools/utils.py @@ -6,6 +6,7 @@ import numpy as np import pandas as pd +from numpy.polynomial.polynomial import Polynomial as Poly # A small number used to decide when a slope is equivalent to zero @@ -423,3 +424,123 @@ def _schumaker_qspline(x, y): yhat = tmp2[:, 4] kflag = tmp2[:, 5] return t, c, yhat, kflag + + +def astm_e1036(v, i, imax_limits=(0.75, 1.15), vmax_limits=(0.75, 1.15), + voc_points=3, isc_points=3, mp_fit_order=4): + ''' + Extract photovoltaic IV parameters according to ASTM E1036. Assumes that + the power producing portion of the curve is in the first quadrant. + + Parameters + ---------- + v : array-like + Voltage points + i : array-like + Current points + imax_limits : tuple, default (0.75, 1.15) + Two-element tuple (low, high) specifying the fraction of estimated + Imp within which to fit a polynomial for max power calculation + vmax_limits : tuple, default (0.75, 1.15) + Two-element tuple (low, high) specifying the fraction of estimated + Vmp within which to fit a polynomial for max power calculation + voc_points : int, default 3 + The number of points near open circuit to use for linear fit + and Voc calculation + isc_points : int, default 3 + The number of points near short circuit to use for linear fit and + Isc calculation + mp_fit_order : int, default 4 + The order of the polynomial fit of power vs. voltage near maximum + power + + + Returns + ------- + dict + Results. The IV parameters are given by the keys 'voc', 'isc', + 'vmp', 'imp', 'pmp', and 'ff'. The key 'mp_fit' gives the numpy + Polynomial object for the fit of power vs voltage near maximum + power. + + References + ---------- + .. [1] Standard Test Methods for Electrical Performance of Nonconcentrator + Terrestrial Photovoltaic Modules and Arrays Using Reference Cells, + ASTM E1036-15(2019), :doi:`10.1520/E1036-15R19` + ''' + + # Adapted from https://github.com/NREL/iv_params + # Copyright (c) 2022, Alliance for Sustainable Energy, LLC + # All rights reserved. + + df = pd.DataFrame() + df['v'] = v + df['i'] = i + df['p'] = df['v'] * df['i'] + + # determine if we can use voc and isc estimates + i_min_ind = df['i'].abs().idxmin() + v_min_ind = df['v'].abs().idxmin() + voc_est = df['v'][i_min_ind] + isc_est = df['i'][v_min_ind] + + # accept the estimates if they are close enough + # if not, perform a linear fit + if abs(df['i'][i_min_ind]) <= isc_est * 0.001: + voc = voc_est + else: + df['i_abs'] = df['i'].abs() + voc_df = df.nsmallest(voc_points, 'i_abs') + voc_fit = Poly.fit(voc_df['i'], voc_df['v'], 1) + voc = voc_fit(0) + + if abs(df['v'][v_min_ind]) <= voc_est * 0.005: + isc = isc_est + else: + df['v_abs'] = df['v'].abs() + isc_df = df.nsmallest(isc_points, 'v_abs') + isc_fit = Poly.fit(isc_df['v'], isc_df['i'], 1) + isc = isc_fit(0) + + # estimate max power point + max_index = df['p'].idxmax() + mp_est = df.loc[max_index] + + # filter around max power + mask = ( + (df['i'] >= imax_limits[0] * mp_est['i']) & + (df['i'] <= imax_limits[1] * mp_est['i']) & + (df['v'] >= vmax_limits[0] * mp_est['v']) & + (df['v'] <= vmax_limits[1] * mp_est['v']) + ) + filtered = df[mask] + + # fit polynomial and find max + mp_fit = Poly.fit(filtered['v'], filtered['p'], mp_fit_order) + # Note that this root finding procedure differs from + # the suggestion in the standard + roots = mp_fit.deriv().roots() + # only consider real roots + roots = roots.real[abs(roots.imag) < 1e-5] + # only consider roots in the relevant part of the domain + roots = roots[(roots < filtered['v'].max()) & + (roots > filtered['v'].min())] + vmp = roots[np.argmax(mp_fit(roots))] + pmp = mp_fit(vmp) + # Imp isn't mentioned for update in the + # standard, but this seems to be in the intended spirit + imp = pmp / vmp + + ff = pmp / (voc * isc) + + result = {} + result['voc'] = voc + result['isc'] = isc + result['vmp'] = vmp + result['imp'] = imp + result['pmp'] = pmp + result['ff'] = ff + result['mp_fit'] = mp_fit + + return result
diff --git a/pvlib/tests/ivtools/test_utils.py b/pvlib/tests/ivtools/test_utils.py index 8f7826bdc2..d8a35e554d 100644 --- a/pvlib/tests/ivtools/test_utils.py +++ b/pvlib/tests/ivtools/test_utils.py @@ -1,7 +1,7 @@ import numpy as np import pandas as pd import pytest -from pvlib.ivtools.utils import _numdiff, rectify_iv_curve +from pvlib.ivtools.utils import _numdiff, rectify_iv_curve, astm_e1036 from pvlib.ivtools.utils import _schumaker_qspline from ..conftest import DATA_DIR @@ -76,3 +76,98 @@ def test__schmumaker_qspline(x, y, expected): np.testing.assert_allclose(t, expected[1], atol=0.0001) np.testing.assert_allclose(yhat, expected[2], atol=0.0001) np.testing.assert_allclose(kflag, expected[3], atol=0.0001) + + +@pytest.fixture +def i_array(): + i = np.array([8.09403993, 8.09382549, 8.09361103, 8.09339656, 8.09318205, + 8.09296748, 8.09275275, 8.09253771, 8.09232204, 8.09210506, + 8.09188538, 8.09166014, 8.09142342, 8.09116305, 8.09085392, + 8.09044425, 8.08982734, 8.08878333, 8.08685945, 8.08312463, + 8.07566926, 8.06059856, 8.03005836, 7.96856869, 7.8469714, + 7.61489584, 7.19789314, 6.51138396, 5.49373476, 4.13267172, + 2.46021487, 0.52838624, -1.61055289]) + return i + + +@pytest.fixture +def v_array(): + v = np.array([-0.005, 0.015, 0.035, 0.055, 0.075, 0.095, 0.115, 0.135, + 0.155, 0.175, 0.195, 0.215, 0.235, 0.255, 0.275, 0.295, + 0.315, 0.335, 0.355, 0.375, 0.395, 0.415, 0.435, 0.455, + 0.475, 0.495, 0.515, 0.535, 0.555, 0.575, 0.595, 0.615, + 0.635]) + return v + + +# astm_e1036 tests +def test_astm_e1036(v_array, i_array): + result = astm_e1036(v_array, i_array) + expected = {'voc': 0.6195097477985162, + 'isc': 8.093986320386227, + 'vmp': 0.494283417170082, + 'imp': 7.626088301548568, + 'pmp': 3.7694489853302127, + 'ff': 0.7517393078504361} + fit = result.pop('mp_fit') + expected_fit = np.array( + [3.6260726, 0.49124176, -0.24644747, -0.26442383, -0.1223237]) + assert fit.coef == pytest.approx(expected_fit) + assert result == pytest.approx(expected) + + +def test_astm_e1036_fit_order(v_array, i_array): + result = astm_e1036(v_array, i_array, mp_fit_order=3) + fit = result.pop('mp_fit') + expected_fit = np.array( + [3.64081697, 0.49124176, -0.3720477, -0.26442383]) + assert fit.coef == pytest.approx(expected_fit) + + +def test_astm_e1036_est_isc_voc(v_array, i_array): + ''' + Test the case in which Isc and Voc estimates are + valid without a linear fit + ''' + v = v_array + i = i_array + v = np.append(v, [0.001, 0.6201]) + i = np.append(i, [8.09397560e+00, 7.10653445e-04]) + result = astm_e1036(v, i) + expected = {'voc': 0.6201, + 'isc': 8.093975598317805, + 'vmp': 0.494283417170082, + 'imp': 7.626088301548568, + 'pmp': 3.7694489853302127, + 'ff': 0.751024747526615} + result.pop('mp_fit') + assert result == pytest.approx(expected) + + +def test_astm_e1036_mpfit_limits(v_array, i_array): + result = astm_e1036(v_array, + i_array, + imax_limits=(0.85, 1.1), + vmax_limits=(0.85, 1.1)) + expected = {'voc': 0.6195097477985162, + 'isc': 8.093986320386227, + 'vmp': 0.49464214190725303, + 'imp': 7.620032530519718, + 'pmp': 3.769189212299219, + 'ff': 0.7516875014460312} + result.pop('mp_fit') + assert result == pytest.approx(expected) + + +def test_astm_e1036_fit_points(v_array, i_array): + i = i_array + i[3] = 8.1 # ensure an interesting change happens + result = astm_e1036(v_array, i, voc_points=4, isc_points=4) + expected = {'voc': 0.619337073271274, + 'isc': 8.093160893325297, + 'vmp': 0.494283417170082, + 'imp': 7.626088301548568, + 'pmp': 3.7694489853302127, + 'ff': 0.7520255886236707} + result.pop('mp_fit') + assert result == pytest.approx(expected)
diff --git a/docs/sphinx/source/reference/pv_modeling.rst b/docs/sphinx/source/reference/pv_modeling.rst index 4e57130711..797681ce23 100644 --- a/docs/sphinx/source/reference/pv_modeling.rst +++ b/docs/sphinx/source/reference/pv_modeling.rst @@ -186,6 +186,7 @@ Utilities for working with IV curve data :toctree: generated/ ivtools.utils.rectify_iv_curve + ivtools.utils.astm_e1036 Other ----- diff --git a/docs/sphinx/source/whatsnew/v0.9.4.rst b/docs/sphinx/source/whatsnew/v0.9.4.rst index ecb659ccc9..cebb864758 100644 --- a/docs/sphinx/source/whatsnew/v0.9.4.rst +++ b/docs/sphinx/source/whatsnew/v0.9.4.rst @@ -45,6 +45,8 @@ Enhancements in a simplified way, using the Faiman model as an example. :py:func:`~pvlib.temperature.faiman_rad` (:issue:`1594`, :pull:`1595`) +* Add a function :py:func:`pvlib.ivtools.utils.astm_e1036` to perform ASTM E1036 extraction of IV + curve parameters (:pull:`1585`) Bug fixes ~~~~~~~~~ @@ -78,6 +80,7 @@ Contributors * Christian Orner (:ghuser:`chrisorner`) * Saurabh Aneja (:ghuser:`spaneja`) * Marcus Boumans (:ghuser:`bowie2211`) +* Michael Deceglie (:ghuser:`mdeceglie`) * Yu Xie (:ghuser:`xieyupku`) * Anton Driesse (:ghuser:`adriesse`) * Cliff Hansen (:ghuser:`cwhanse`)
[ { "components": [ { "doc": "Extract photovoltaic IV parameters according to ASTM E1036. Assumes that\nthe power producing portion of the curve is in the first quadrant.\n\nParameters\n----------\nv : array-like\n Voltage points\ni : array-like\n Current points\nimax_limits : tuple, default (0.75, 1.15)\n Two-element tuple (low, high) specifying the fraction of estimated\n Imp within which to fit a polynomial for max power calculation\nvmax_limits : tuple, default (0.75, 1.15)\n Two-element tuple (low, high) specifying the fraction of estimated\n Vmp within which to fit a polynomial for max power calculation\nvoc_points : int, default 3\n The number of points near open circuit to use for linear fit\n and Voc calculation\nisc_points : int, default 3\n The number of points near short circuit to use for linear fit and\n Isc calculation\nmp_fit_order : int, default 4\n The order of the polynomial fit of power vs. voltage near maximum\n power\n\n\nReturns\n-------\ndict\n Results. The IV parameters are given by the keys 'voc', 'isc',\n 'vmp', 'imp', 'pmp', and 'ff'. The key 'mp_fit' gives the numpy\n Polynomial object for the fit of power vs voltage near maximum\n power.\n\nReferences\n----------\n.. [1] Standard Test Methods for Electrical Performance of Nonconcentrator\n Terrestrial Photovoltaic Modules and Arrays Using Reference Cells,\n ASTM E1036-15(2019), :doi:`10.1520/E1036-15R19`", "lines": [ 429, 546 ], "name": "astm_e1036", "signature": "def astm_e1036(v, i, imax_limits=(0.75, 1.15), vmax_limits=(0.75, 1.15), voc_points=3, isc_points=3, mp_fit_order=4):", "type": "function" } ], "file": "pvlib/ivtools/utils.py" } ]
[ "pvlib/tests/ivtools/test_utils.py::test__numdiff", "pvlib/tests/ivtools/test_utils.py::test_rectify_iv_curve", "pvlib/tests/ivtools/test_utils.py::test__schmumaker_qspline[x0-y0-expected0]", "pvlib/tests/ivtools/test_utils.py::test__schmumaker_qspline[x1-y1-expected1]", "pvlib/tests/ivtools/test_utils.py::test__schmumaker_qspline[x2-y2-expected2]", "pvlib/tests/ivtools/test_utils.py::test_astm_e1036", "pvlib/tests/ivtools/test_utils.py::test_astm_e1036_fit_order", "pvlib/tests/ivtools/test_utils.py::test_astm_e1036_est_isc_voc", "pvlib/tests/ivtools/test_utils.py::test_astm_e1036_mpfit_limits", "pvlib/tests/ivtools/test_utils.py::test_astm_e1036_fit_points" ]
[]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> add ASTM E1036 parameter extraction - [x] I am familiar with the [contributing guidelines](https://pvlib-python.readthedocs.io/en/latest/contributing.html) - [x] Tests added - [x] Updates entries in [`docs/sphinx/source/reference`](https://github.com/pvlib/pvlib-python/blob/master/docs/sphinx/source/reference) for API changes. - [x] Adds description and name entries in the appropriate "what's new" file in [`docs/sphinx/source/whatsnew`](https://github.com/pvlib/pvlib-python/tree/master/docs/sphinx/source/whatsnew) for all changes. Includes link to the GitHub Issue with `` :issue:`num` `` or this Pull Request with `` :pull:`num` ``. Includes contributor name and/or GitHub username (link with `` :ghuser:`user` ``). - [x] New code is fully documented. Includes [numpydoc](https://numpydoc.readthedocs.io/en/latest/format.html) compliant docstrings, examples, and comments where necessary. - [x] Pull request is nearly complete and ready for detailed review. - [x] Maintainer: Appropriate GitHub Labels (including `remote-data`) and Milestone are assigned to the Pull Request and linked Issue. <!-- Brief description of the problem and proposed solution (if not already fully described in the issue linked to above): --> This PR adds the ASTM E1036 methods for extracting performance parameters from IV curves. The code has been adapted from https://github.com/NREL/iv_params ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in pvlib/ivtools/utils.py] (definition of astm_e1036:) def astm_e1036(v, i, imax_limits=(0.75, 1.15), vmax_limits=(0.75, 1.15), voc_points=3, isc_points=3, mp_fit_order=4): """Extract photovoltaic IV parameters according to ASTM E1036. Assumes that the power producing portion of the curve is in the first quadrant. Parameters ---------- v : array-like Voltage points i : array-like Current points imax_limits : tuple, default (0.75, 1.15) Two-element tuple (low, high) specifying the fraction of estimated Imp within which to fit a polynomial for max power calculation vmax_limits : tuple, default (0.75, 1.15) Two-element tuple (low, high) specifying the fraction of estimated Vmp within which to fit a polynomial for max power calculation voc_points : int, default 3 The number of points near open circuit to use for linear fit and Voc calculation isc_points : int, default 3 The number of points near short circuit to use for linear fit and Isc calculation mp_fit_order : int, default 4 The order of the polynomial fit of power vs. voltage near maximum power Returns ------- dict Results. The IV parameters are given by the keys 'voc', 'isc', 'vmp', 'imp', 'pmp', and 'ff'. The key 'mp_fit' gives the numpy Polynomial object for the fit of power vs voltage near maximum power. References ---------- .. [1] Standard Test Methods for Electrical Performance of Nonconcentrator Terrestrial Photovoltaic Modules and Arrays Using Reference Cells, ASTM E1036-15(2019), :doi:`10.1520/E1036-15R19`""" [end of new definitions in pvlib/ivtools/utils.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
311781d2380997044da0e484dc90aa146a74ca44
aws__sagemaker-python-sdk-3432
3,432
aws/sagemaker-python-sdk
null
1a39422883c7c7b04865e58fda201bcb93075669
2022-10-21T15:46:55Z
diff --git a/src/sagemaker/fw_utils.py b/src/sagemaker/fw_utils.py index dacd0a229c..af48a111bc 100644 --- a/src/sagemaker/fw_utils.py +++ b/src/sagemaker/fw_utils.py @@ -134,10 +134,13 @@ "1.12.0", ] + TORCH_DISTRIBUTED_SUPPORTED_FRAMEWORK_VERSIONS = ["1.11", "1.11.0"] + TRAINIUM_SUPPORTED_DISTRIBUTION_STRATEGIES = ["torch_distributed"] + SMDISTRIBUTED_SUPPORTED_STRATEGIES = ["dataparallel", "modelparallel"] @@ -160,6 +163,12 @@ def validate_source_dir(script, directory): return True +GRAVITON_ALLOWED_TARGET_INSTANCE_FAMILY = ["c6g", "t4g", "r6g", "m6g"] + + +GRAVITON_ALLOWED_FRAMEWORKS = set(["tensorflow", "pytorch"]) + + def validate_source_code_input_against_pipeline_variables( entry_point: Optional[Union[str, PipelineVariable]] = None, source_dir: Optional[Union[str, PipelineVariable]] = None, diff --git a/src/sagemaker/image_uri_config/pytorch.json b/src/sagemaker/image_uri_config/pytorch.json index a88f7f1c50..74127a1fda 100644 --- a/src/sagemaker/image_uri_config/pytorch.json +++ b/src/sagemaker/image_uri_config/pytorch.json @@ -654,6 +654,51 @@ } } }, + "inference_graviton": { + "processors": [ + "cpu" + ], + "version_aliases": { + "1.12": "1.12.1" + }, + "versions": { + "1.12.1": { + "py_versions": [ + "py38" + ], + "registries": { + "af-south-1": "626614931356", + "ap-east-1": "871362719292", + "ap-northeast-1": "763104351884", + "ap-northeast-2": "763104351884", + "ap-northeast-3": "364406365360", + "ap-south-1": "763104351884", + "ap-southeast-1": "763104351884", + "ap-southeast-2": "763104351884", + "ap-southeast-3": "907027046896", + "ca-central-1": "763104351884", + "cn-north-1": "727897471807", + "cn-northwest-1": "727897471807", + "eu-central-1": "763104351884", + "eu-north-1": "763104351884", + "eu-west-1": "763104351884", + "eu-west-2": "763104351884", + "eu-west-3": "763104351884", + "eu-south-1": "692866216735", + "me-south-1": "217643126080", + "sa-east-1": "763104351884", + "us-east-1": "763104351884", + "us-east-2": "763104351884", + "us-gov-west-1": "442386744353", + "us-iso-east-1": "886529160074", + "us-west-1": "763104351884", + "us-west-2": "763104351884" + }, + "repository": "pytorch-inference-graviton", + "container_version": {"cpu": "ubuntu20.04"} + } + } + }, "training": { "processors": [ "cpu", diff --git a/src/sagemaker/image_uri_config/tensorflow.json b/src/sagemaker/image_uri_config/tensorflow.json index 6a2318ddbe..0f5a390c8d 100644 --- a/src/sagemaker/image_uri_config/tensorflow.json +++ b/src/sagemaker/image_uri_config/tensorflow.json @@ -1471,6 +1471,51 @@ } } }, + "inference_graviton": { + "processors": [ + "cpu" + ], + "version_aliases": { + "2.9": "2.9.1" + }, + "versions": { + "2.9.1": { + "py_versions": [ + "py38" + ], + "registries": { + "af-south-1": "626614931356", + "ap-east-1": "871362719292", + "ap-northeast-1": "763104351884", + "ap-northeast-2": "763104351884", + "ap-northeast-3": "364406365360", + "ap-south-1": "763104351884", + "ap-southeast-1": "763104351884", + "ap-southeast-2": "763104351884", + "ap-southeast-3": "907027046896", + "ca-central-1": "763104351884", + "cn-north-1": "727897471807", + "cn-northwest-1": "727897471807", + "eu-central-1": "763104351884", + "eu-north-1": "763104351884", + "eu-west-1": "763104351884", + "eu-west-2": "763104351884", + "eu-west-3": "763104351884", + "eu-south-1": "692866216735", + "me-south-1": "217643126080", + "sa-east-1": "763104351884", + "us-east-1": "763104351884", + "us-east-2": "763104351884", + "us-gov-west-1": "442386744353", + "us-iso-east-1": "886529160074", + "us-west-1": "763104351884", + "us-west-2": "763104351884" + }, + "repository": "tensorflow-inference-graviton", + "container_version": {"cpu": "ubuntu20.04"} + } + } + }, "training": { "processors": [ "cpu", diff --git a/src/sagemaker/image_uris.py b/src/sagemaker/image_uris.py index 01ed5f1d99..f1c0d69af2 100644 --- a/src/sagemaker/image_uris.py +++ b/src/sagemaker/image_uris.py @@ -25,6 +25,7 @@ from sagemaker.jumpstart import artifacts from sagemaker.workflow import is_pipeline_variable from sagemaker.workflow.utilities import override_pipeline_parameter_var +from sagemaker.fw_utils import GRAVITON_ALLOWED_TARGET_INSTANCE_FAMILY, GRAVITON_ALLOWED_FRAMEWORKS logger = logging.getLogger(__name__) @@ -151,6 +152,7 @@ def retrieve( inference_tool = _get_inference_tool(inference_tool, instance_type) if inference_tool == "neuron": _framework = f"{framework}-{inference_tool}" + image_scope = _get_image_scope_for_instance_type(_framework, instance_type, image_scope) config = _config_for_framework_and_scope(_framework, image_scope, accelerator_type) original_version = version @@ -216,6 +218,9 @@ def retrieve( else: tag_prefix = version_config.get("tag_prefix", version) + if repo == f"{framework}-inference-graviton": + container_version = f"{container_version}-sagemaker" + tag = _format_tag(tag_prefix, processor, py_version, container_version, inference_tool) if instance_type is not None and _should_auto_select_container_version( @@ -287,6 +292,15 @@ def config_for_framework(framework): return json.load(f) +def _get_image_scope_for_instance_type(framework, instance_type, image_scope): + """Extract the image scope from instance type.""" + if framework in GRAVITON_ALLOWED_FRAMEWORKS and isinstance(instance_type, str): + match = re.match(r"^ml[\._]([a-z\d]+)\.?\w*$", instance_type) + if match and match[1] in GRAVITON_ALLOWED_TARGET_INSTANCE_FAMILY: + return "inference_graviton" + return image_scope + + def _get_inference_tool(inference_tool, instance_type): """Extract the inference tool name from instance type.""" if not inference_tool and instance_type:
diff --git a/tests/conftest.py b/tests/conftest.py index 17a5c1db9c..a54cbfea15 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -308,6 +308,16 @@ def huggingface_pytorch_latest_inference_py_version(huggingface_inference_pytorc ) +@pytest.fixture(scope="module") +def graviton_tensorflow_version(): + return "2.9.1" + + +@pytest.fixture(scope="module") +def graviton_pytorch_version(): + return "1.12.1" + + @pytest.fixture(scope="module") def huggingface_tensorflow_latest_training_py_version(): return "py38" diff --git a/tests/unit/sagemaker/image_uris/expected_uris.py b/tests/unit/sagemaker/image_uris/expected_uris.py index 9bcdbc6e81..a49ff57936 100644 --- a/tests/unit/sagemaker/image_uris/expected_uris.py +++ b/tests/unit/sagemaker/image_uris/expected_uris.py @@ -38,3 +38,18 @@ def algo_uri(algo, account, region, version=1): def monitor_uri(account, region=REGION): domain = ALTERNATE_DOMAINS.get(region, DOMAIN) return MONITOR_URI_FORMAT.format(account, region, domain) + + +def graviton_framework_uri( + repo, + fw_version, + account, + py_version="py38", + processor="cpu", + region=REGION, + container_version="ubuntu20.04-sagemaker", +): + domain = ALTERNATE_DOMAINS.get(region, DOMAIN) + tag = "-".join(x for x in (fw_version, processor, py_version, container_version) if x) + + return IMAGE_URI_FORMAT.format(account, region, domain, repo, tag) diff --git a/tests/unit/sagemaker/image_uris/test_graviton.py b/tests/unit/sagemaker/image_uris/test_graviton.py new file mode 100644 index 0000000000..450073e558 --- /dev/null +++ b/tests/unit/sagemaker/image_uris/test_graviton.py @@ -0,0 +1,83 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). You +# may not use this file except in compliance with the License. A copy of +# the License is located at +# +# http://aws.amazon.com/apache2.0/ +# +# or in the "license" file accompanying this file. This file is +# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF +# ANY KIND, either express or implied. See the License for the specific +# language governing permissions and limitations under the License. +from __future__ import absolute_import + +from sagemaker import image_uris +from tests.unit.sagemaker.image_uris import expected_uris + +GRAVITON_ALGOS = ("tensorflow", "pytotch") +GRAVITON_INSTANCE_TYPES = [ + "ml.c6g.4xlarge", + "ml.t4g.2xlarge", + "ml.r6g.2xlarge", + "ml.m6g.4xlarge", +] + +ACCOUNTS = { + "af-south-1": "626614931356", + "ap-east-1": "871362719292", + "ap-northeast-1": "763104351884", + "ap-northeast-2": "763104351884", + "ap-northeast-3": "364406365360", + "ap-south-1": "763104351884", + "ap-southeast-1": "763104351884", + "ap-southeast-2": "763104351884", + "ap-southeast-3": "907027046896", + "ca-central-1": "763104351884", + "cn-north-1": "727897471807", + "cn-northwest-1": "727897471807", + "eu-central-1": "763104351884", + "eu-north-1": "763104351884", + "eu-west-1": "763104351884", + "eu-west-2": "763104351884", + "eu-west-3": "763104351884", + "eu-south-1": "692866216735", + "me-south-1": "217643126080", + "sa-east-1": "763104351884", + "us-east-1": "763104351884", + "us-east-2": "763104351884", + "us-gov-west-1": "442386744353", + "us-iso-east-1": "886529160074", + "us-west-1": "763104351884", + "us-west-2": "763104351884", +} + +GRAVITON_REGIONS = ACCOUNTS.keys() + + +def _test_graviton_framework_uris(framework, version): + for region in GRAVITON_REGIONS: + for instance_type in GRAVITON_INSTANCE_TYPES: + uri = image_uris.retrieve( + framework, region, instance_type=instance_type, version=version + ) + expected = _expected_graviton_framework_uri(framework, version, region=region) + assert expected == uri + + +def test_graviton_tensorflow(graviton_tensorflow_version): + _test_graviton_framework_uris("tensorflow", graviton_tensorflow_version) + + +def test_graviton_pytorch(graviton_pytorch_version): + _test_graviton_framework_uris("pytorch", graviton_pytorch_version) + + +def _expected_graviton_framework_uri(framework, version, region): + return expected_uris.graviton_framework_uri( + "{}-inference-graviton".format(framework), + fw_version=version, + py_version="py38", + account=ACCOUNTS[region], + region=region, + )
diff --git a/src/sagemaker/image_uri_config/pytorch.json b/src/sagemaker/image_uri_config/pytorch.json index a88f7f1c50..74127a1fda 100644 --- a/src/sagemaker/image_uri_config/pytorch.json +++ b/src/sagemaker/image_uri_config/pytorch.json @@ -654,6 +654,51 @@ } } }, + "inference_graviton": { + "processors": [ + "cpu" + ], + "version_aliases": { + "1.12": "1.12.1" + }, + "versions": { + "1.12.1": { + "py_versions": [ + "py38" + ], + "registries": { + "af-south-1": "626614931356", + "ap-east-1": "871362719292", + "ap-northeast-1": "763104351884", + "ap-northeast-2": "763104351884", + "ap-northeast-3": "364406365360", + "ap-south-1": "763104351884", + "ap-southeast-1": "763104351884", + "ap-southeast-2": "763104351884", + "ap-southeast-3": "907027046896", + "ca-central-1": "763104351884", + "cn-north-1": "727897471807", + "cn-northwest-1": "727897471807", + "eu-central-1": "763104351884", + "eu-north-1": "763104351884", + "eu-west-1": "763104351884", + "eu-west-2": "763104351884", + "eu-west-3": "763104351884", + "eu-south-1": "692866216735", + "me-south-1": "217643126080", + "sa-east-1": "763104351884", + "us-east-1": "763104351884", + "us-east-2": "763104351884", + "us-gov-west-1": "442386744353", + "us-iso-east-1": "886529160074", + "us-west-1": "763104351884", + "us-west-2": "763104351884" + }, + "repository": "pytorch-inference-graviton", + "container_version": {"cpu": "ubuntu20.04"} + } + } + }, "training": { "processors": [ "cpu", diff --git a/src/sagemaker/image_uri_config/tensorflow.json b/src/sagemaker/image_uri_config/tensorflow.json index 6a2318ddbe..0f5a390c8d 100644 --- a/src/sagemaker/image_uri_config/tensorflow.json +++ b/src/sagemaker/image_uri_config/tensorflow.json @@ -1471,6 +1471,51 @@ } } }, + "inference_graviton": { + "processors": [ + "cpu" + ], + "version_aliases": { + "2.9": "2.9.1" + }, + "versions": { + "2.9.1": { + "py_versions": [ + "py38" + ], + "registries": { + "af-south-1": "626614931356", + "ap-east-1": "871362719292", + "ap-northeast-1": "763104351884", + "ap-northeast-2": "763104351884", + "ap-northeast-3": "364406365360", + "ap-south-1": "763104351884", + "ap-southeast-1": "763104351884", + "ap-southeast-2": "763104351884", + "ap-southeast-3": "907027046896", + "ca-central-1": "763104351884", + "cn-north-1": "727897471807", + "cn-northwest-1": "727897471807", + "eu-central-1": "763104351884", + "eu-north-1": "763104351884", + "eu-west-1": "763104351884", + "eu-west-2": "763104351884", + "eu-west-3": "763104351884", + "eu-south-1": "692866216735", + "me-south-1": "217643126080", + "sa-east-1": "763104351884", + "us-east-1": "763104351884", + "us-east-2": "763104351884", + "us-gov-west-1": "442386744353", + "us-iso-east-1": "886529160074", + "us-west-1": "763104351884", + "us-west-2": "763104351884" + }, + "repository": "tensorflow-inference-graviton", + "container_version": {"cpu": "ubuntu20.04"} + } + } + }, "training": { "processors": [ "cpu",
[ { "components": [ { "doc": "Extract the image scope from instance type.", "lines": [ 295, 301 ], "name": "_get_image_scope_for_instance_type", "signature": "def _get_image_scope_for_instance_type(framework, instance_type, image_scope):", "type": "function" } ], "file": "src/sagemaker/image_uris.py" } ]
[ "tests/unit/sagemaker/image_uris/test_graviton.py::test_graviton_tensorflow", "tests/unit/sagemaker/image_uris/test_graviton.py::test_graviton_pytorch" ]
[]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> feature: Graviton support for PyTorch and Tensorflow frameworks *Issue #, if available:* *Description of changes:* Added the necessary changes to incorporate the [Graviton instances](https://github.com/aws/deep-learning-containers/releases/tag/v1.0-pt-graviton-sagemaker-1.12.1-inf-cpu-py38) into the `PyTorch` and `Tensorflow` frameworks. *Testing done:* Locally tested the feature to extract image string with the following code, where the output should match with expected DLC image URI's for PyTorch (`763104351884.dkr.ecr.us-west-2.amazonaws.com/pytorch-inference-graviton:1.12.1-cpu-py38-ubuntu20.04-sagemaker`) and Tensorflow (`763104351884.dkr.ecr.us-west-2.amazonaws.com/tensorflow-inference-graviton:2.9.1-cpu-py38-ubuntu20.04-sagemaker`). ```bash >>> sagemaker.image_uris.retrieve("pytorch","us-west-2", instance_type="ml.c6g.4xlarge") '763104351884.dkr.ecr.us-west-2.amazonaws.com/pytorch-inference-graviton:1.12.1-cpu-py38-ubuntu20.04-sagemaker' >>> sagemaker.image_uris.retrieve("tensorflow","us-west-2", instance_type="ml.t4g.2xlarge") '763104351884.dkr.ecr.us-west-2.amazonaws.com/tensorflow-inference-graviton:2.9.1-cpu-py38-ubuntu20.04-sagemaker' ``` ## Merge Checklist _Put an `x` in the boxes that apply. You can also fill these out after creating the PR. If you're unsure about any of them, don't hesitate to ask. We're here to help! This is simply a reminder of what we are going to look for before merging your pull request._ #### General - [x] I have read the [CONTRIBUTING](https://github.com/aws/sagemaker-python-sdk/blob/master/CONTRIBUTING.md) doc - [x] I certify that the changes I am introducing will be backward compatible, and I have discussed concerns about this, if any, with the Python SDK team - [x] I used the commit message format described in [CONTRIBUTING](https://github.com/aws/sagemaker-python-sdk/blob/master/CONTRIBUTING.md#committing-your-change) - [ ] I have passed the region in to all S3 and STS clients that I've initialized as part of this change. - [ ] I have updated any necessary documentation, including [READMEs](https://github.com/aws/sagemaker-python-sdk/blob/master/README.rst) and [API docs](https://github.com/aws/sagemaker-python-sdk/tree/master/doc) (if appropriate) #### Tests - [x] I have added tests that prove my fix is effective or that my feature works (if appropriate) - [x] I have added unit and/or integration tests as appropriate to ensure backward compatibility of the changes - [ ] I have checked that my tests are not configured for a specific region or account (if appropriate) - [ ] I have used [`unique_name_from_base`](https://github.com/aws/sagemaker-python-sdk/blob/master/src/sagemaker/utils.py#L77) to create resource names in integ tests (if appropriate) By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license. ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in src/sagemaker/image_uris.py] (definition of _get_image_scope_for_instance_type:) def _get_image_scope_for_instance_type(framework, instance_type, image_scope): """Extract the image scope from instance type.""" [end of new definitions in src/sagemaker/image_uris.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
03738861995e0c3fda73958d251e83465aba3c04
aws__sagemaker-python-sdk-3423
3,423
aws/sagemaker-python-sdk
null
8dc17fb89fafd3609e14cb1539ae2911be510f2e
2022-10-18T21:48:25Z
diff --git a/doc/frameworks/pytorch/using_pytorch.rst b/doc/frameworks/pytorch/using_pytorch.rst index 725f34aa5a..f56085f756 100644 --- a/doc/frameworks/pytorch/using_pytorch.rst +++ b/doc/frameworks/pytorch/using_pytorch.rst @@ -293,6 +293,121 @@ using two ``ml.p4d.24xlarge`` instances: pt_estimator.fit("s3://bucket/path/to/training/data") +.. _distributed-pytorch-training-on-trainium: + +Distributed Training with PyTorch Neuron on Trn1 instances +========================================================== + +SageMaker Training supports Amazon EC2 Trn1 instances powered by +`AWS Trainium <https://aws.amazon.com/machine-learning/trainium/>`_ device, +the second generation purpose-built machine learning accelerator from AWS. +Each Trn1 instance consists of up to 16 Trainium devices, and each +Trainium device consists of two `NeuronCores +<https://awsdocs-neuron.readthedocs-hosted.com/en/latest/general/arch/neuron-hardware/trn1-arch.html#trainium-architecture>`_ +in the *AWS Neuron Documentation*. + +You can run distributed training job on Trn1 instances. +SageMaker supports the ``xla`` package through ``torchrun``. +With this, you do not need to manually pass ``RANK``, +``WORLD_SIZE``, ``MASTER_ADDR``, and ``MASTER_PORT``. +You can launch the training job using the +:class:`sagemaker.pytorch.estimator.PyTorch` estimator class +with the ``torch_distributed`` option as the distribution strategy. + +.. note:: + + This ``torch_distributed`` support is available + in the AWS Deep Learning Containers for PyTorch Neuron starting v1.11.0. + To find a complete list of supported versions of PyTorch Neuron, see + `Neuron Containers <https://github.com/aws/deep-learning-containers/blob/master/available_images.md#neuron-containers>`_ + in the *AWS Deep Learning Containers GitHub repository*. + +.. note:: + + SageMaker Debugger is currently not supported with Trn1 instances. + +Adapt Your Training Script to Initialize with the XLA backend +------------------------------------------------------------- + +To initialize distributed training in your script, call +`torch.distributed.init_process_group +<https://pytorch.org/docs/master/distributed.html#torch.distributed.init_process_group>`_ +with the ``xla`` backend as shown below. + +.. code:: python + + import torch.distributed as dist + + dist.init_process_group('xla') + +SageMaker takes care of ``'MASTER_ADDR'`` and ``'MASTER_PORT'`` for you via ``torchrun`` + +For detailed documentation about modifying your training script for Trainium, see `Multi-worker data-parallel MLP training using torchrun <https://awsdocs-neuron.readthedocs-hosted.com/en/latest/frameworks/torch/torch-neuronx/tutorials/training/mlp.html?highlight=torchrun#multi-worker-data-parallel-mlp-training-using-torchrun>`_ in the *AWS Neuron Documentation*. + +**Currently Supported backends:** + +- ``xla`` for Trainium (Trn1) instances + +For up-to-date information on supported backends for Trn1 instances, see `AWS Neuron Documentation <https://awsdocs-neuron.readthedocs-hosted.com/en/latest/index.html>`_. + +Launching a Distributed Training Job on Trainium +------------------------------------------------ + +You can run multi-node distributed PyTorch training jobs on Trn1 instances using the +:class:`sagemaker.pytorch.estimator.PyTorch` estimator class. +With ``instance_count=1``, the estimator submits a +single-node training job to SageMaker; with ``instance_count`` greater +than one, a multi-node training job is launched. + +With the ``torch_distributed`` option, the SageMaker PyTorch estimator runs a SageMaker +training container for PyTorch Neuron, sets up the environment, and launches +the training job using the ``torchrun`` command on each worker with the given information. + +**Examples** + +The following examples show how to run a PyTorch training using ``torch_distributed`` in SageMaker +on one ``ml.trn1.2xlarge`` instance and two ``ml.trn1.32xlarge`` instances: + +.. code:: python + + from sagemaker.pytorch import PyTorch + + pt_estimator = PyTorch( + entry_point="train_torch_distributed.py", + role="SageMakerRole", + framework_version="1.11.0", + py_version="py38", + instance_count=1, + instance_type="ml.trn1.2xlarge", + distribution={ + "torch_distributed": { + "enabled": True + } + } + ) + + pt_estimator.fit("s3://bucket/path/to/training/data") + +.. code:: python + + from sagemaker.pytorch import PyTorch + + pt_estimator = PyTorch( + entry_point="train_torch_distributed.py", + role="SageMakerRole", + framework_version="1.11.0", + py_version="py38", + instance_count=2, + instance_type="ml.trn1.32xlarge", + distribution={ + "torch_distributed": { + "enabled": True + } + } + ) + + pt_estimator.fit("s3://bucket/path/to/training/data") + ********************* Deploy PyTorch Models ********************* diff --git a/src/sagemaker/image_uri_config/pytorch-neuron.json b/src/sagemaker/image_uri_config/pytorch-neuron.json new file mode 100644 index 0000000000..b116a8a36b --- /dev/null +++ b/src/sagemaker/image_uri_config/pytorch-neuron.json @@ -0,0 +1,41 @@ +{ + "training": { + "processors": ["trn"], + "version_aliases": {"1.11": "1.11.0"}, + "versions": { + "1.11.0": { + "py_versions": ["py38"], + "repository": "pytorch-training-neuron", + "registries": { + "af-south-1": "626614931356", + "ap-east-1": "871362719292", + "ap-northeast-1": "763104351884", + "ap-northeast-2": "763104351884", + "ap-northeast-3": "364406365360", + "ap-south-1": "763104351884", + "ap-southeast-1": "763104351884", + "ap-southeast-2": "763104351884", + "ca-central-1": "763104351884", + "cn-north-1": "727897471807", + "cn-northwest-1": "727897471807", + "eu-central-1": "763104351884", + "eu-north-1": "763104351884", + "eu-west-1": "763104351884", + "eu-west-2": "763104351884", + "eu-west-3": "763104351884", + "eu-south-1": "692866216735", + "me-south-1": "217643126080", + "sa-east-1": "763104351884", + "us-east-1": "763104351884", + "us-east-2": "763104351884", + "us-gov-west-1": "442386744353", + "us-iso-east-1": "886529160074", + "us-west-1": "763104351884", + "us-west-2": "763104351884" + }, + "container_version": {"trn": "ubuntu20.04"}, + "sdk_versions": ["sdk2.4.0"] + } + } + } + } \ No newline at end of file diff --git a/src/sagemaker/image_uris.py b/src/sagemaker/image_uris.py index fa00fe873c..b961ee0c4e 100644 --- a/src/sagemaker/image_uris.py +++ b/src/sagemaker/image_uris.py @@ -33,6 +33,7 @@ HUGGING_FACE_FRAMEWORK = "huggingface" XGBOOST_FRAMEWORK = "xgboost" SKLEARN_FRAMEWORK = "sklearn" +TRAINIUM_ALLOWED_FRAMEWORKS = "pytorch" @override_pipeline_parameter_var @@ -150,11 +151,12 @@ def retrieve( ) else: _framework = framework - if framework == HUGGING_FACE_FRAMEWORK: + if framework == HUGGING_FACE_FRAMEWORK or framework in TRAINIUM_ALLOWED_FRAMEWORKS: inference_tool = _get_inference_tool(inference_tool, instance_type) if inference_tool == "neuron": _framework = f"{framework}-{inference_tool}" final_image_scope = _get_final_image_scope(framework, instance_type, image_scope) + _validate_for_suppported_frameworks_and_instance_type(framework, instance_type) config = _config_for_framework_and_scope(_framework, final_image_scope, accelerator_type) original_version = version @@ -186,6 +188,12 @@ def retrieve( if version_config.get("container_version"): container_version = version_config["container_version"][processor] + # Append sdk version in case of trainium instances + if repo in ["pytorch-training-neuron"]: + if not sdk_version: + sdk_version = _get_latest_versions(version_config["sdk_versions"]) + container_version = sdk_version + "-" + container_version + if framework == HUGGING_FACE_FRAMEWORK: pt_or_tf_version = ( re.compile("^(pytorch|tensorflow)(.*)$").match(base_framework_version).group(2) @@ -344,6 +352,16 @@ def _config_for_framework_and_scope(framework, image_scope, accelerator_type=Non return config if "scope" in config else config[image_scope] +def _validate_for_suppported_frameworks_and_instance_type(framework, instace_type): + """Validate if framework is supported for the instance_type""" + if ( + instace_type is not None + and "trn" in instace_type + and framework not in TRAINIUM_ALLOWED_FRAMEWORKS + ): + _validate_framework(framework, TRAINIUM_ALLOWED_FRAMEWORKS, "framework") + + def config_for_framework(framework): """Loads the JSON config for the given framework.""" fname = os.path.join(os.path.dirname(__file__), "image_uri_config", "{}.json".format(framework)) @@ -371,7 +389,7 @@ def _get_inference_tool(inference_tool, instance_type): """Extract the inference tool name from instance type.""" if not inference_tool: instance_type_family = _get_instance_type_family(instance_type) - if instance_type_family.startswith("inf"): + if instance_type_family.startswith("inf") or instance_type_family.startswith("trn"): return "neuron" return inference_tool @@ -460,6 +478,8 @@ def _processor(instance_type, available_processors, serverless_inference_config= processor = family elif family.startswith("inf"): processor = "inf" + elif family.startswith("trn"): + processor = "trn" elif family[0] in ("g", "p"): processor = "gpu" else: @@ -523,6 +543,15 @@ def _validate_arg(arg, available_options, arg_name): ) +def _validate_framework(framework, allowed_frameworks, arg_name): + """Checks if the framework is in the allowed frameworks, and raises a ``ValueError`` if not.""" + if framework not in allowed_frameworks: + raise ValueError( + f"Unsupported {arg_name}: {framework}. " + f"Supported {arg_name}(s) for trainium instances: {allowed_frameworks}." + ) + + def _format_tag(tag_prefix, processor, py_version, container_version, inference_tool=None): """Creates a tag for the image URI.""" if inference_tool:
diff --git a/tests/conftest.py b/tests/conftest.py index 249f25cfcb..e92d98112b 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -358,6 +358,11 @@ def huggingface_neuron_latest_inference_py_version(): return "py37" +@pytest.fixture(scope="module") +def pytorch_neuron_version(): + return "1.11" + + @pytest.fixture(scope="module") def pytorch_eia_py_version(): return "py3" diff --git a/tests/unit/sagemaker/image_uris/expected_uris.py b/tests/unit/sagemaker/image_uris/expected_uris.py index a49ff57936..0574536754 100644 --- a/tests/unit/sagemaker/image_uris/expected_uris.py +++ b/tests/unit/sagemaker/image_uris/expected_uris.py @@ -30,6 +30,24 @@ def framework_uri(repo, fw_version, account, py_version=None, processor="cpu", r return IMAGE_URI_FORMAT.format(account, region, domain, repo, tag) +def neuron_framework_uri( + repo, + fw_version, + account, + py_version=None, + inference_tool="neuron", + region=REGION, + sdk_version="sdk2.4.0", + container_version="ubuntu20.04", +): + domain = ALTERNATE_DOMAINS.get(region, DOMAIN) + tag = "-".join( + x for x in (fw_version, inference_tool, py_version, sdk_version, container_version) if x + ) + + return IMAGE_URI_FORMAT.format(account, region, domain, repo, tag) + + def algo_uri(algo, account, region, version=1): domain = ALTERNATE_DOMAINS.get(region, DOMAIN) return IMAGE_URI_FORMAT.format(account, region, domain, algo, version) diff --git a/tests/unit/sagemaker/image_uris/test_trainium.py b/tests/unit/sagemaker/image_uris/test_trainium.py new file mode 100644 index 0000000000..d2b7d4a949 --- /dev/null +++ b/tests/unit/sagemaker/image_uris/test_trainium.py @@ -0,0 +1,74 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). You +# may not use this file except in compliance with the License. A copy of +# the License is located at +# +# http://aws.amazon.com/apache2.0/ +# +# or in the "license" file accompanying this file. This file is +# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF +# ANY KIND, either express or implied. See the License for the specific +# language governing permissions and limitations under the License. +from __future__ import absolute_import + +from sagemaker import image_uris +from tests.unit.sagemaker.image_uris import expected_uris + +ACCOUNTS = { + "af-south-1": "626614931356", + "ap-east-1": "871362719292", + "ap-northeast-1": "763104351884", + "ap-northeast-2": "763104351884", + "ap-northeast-3": "364406365360", + "ap-south-1": "763104351884", + "ap-southeast-1": "763104351884", + "ap-southeast-2": "763104351884", + "ca-central-1": "763104351884", + "cn-north-1": "727897471807", + "cn-northwest-1": "727897471807", + "eu-central-1": "763104351884", + "eu-north-1": "763104351884", + "eu-west-1": "763104351884", + "eu-west-2": "763104351884", + "eu-west-3": "763104351884", + "eu-south-1": "692866216735", + "me-south-1": "217643126080", + "sa-east-1": "763104351884", + "us-east-1": "763104351884", + "us-east-2": "763104351884", + "us-gov-west-1": "442386744353", + "us-iso-east-1": "886529160074", + "us-west-1": "763104351884", + "us-west-2": "763104351884", +} + +TRAINIUM_REGIONS = ACCOUNTS.keys() + + +def _expected_trainium_framework_uri( + framework, version, region="us-west-2", inference_tool="neuron" +): + return expected_uris.neuron_framework_uri( + "{}-neuron".format(framework), + fw_version=version, + py_version="py38", + account=ACCOUNTS[region], + region=region, + inference_tool=inference_tool, + ) + + +def _test_trainium_framework_uris(framework, version): + for region in TRAINIUM_REGIONS: + uri = image_uris.retrieve( + framework, region, instance_type="ml.trn1.xlarge", version=version + ) + expected = _expected_trainium_framework_uri( + "{}-training".format(framework), version, region=region, inference_tool="neuron" + ) + assert expected == uri + + +def test_trainium_pytorch(pytorch_neuron_version): + _test_trainium_framework_uris("pytorch", pytorch_neuron_version)
diff --git a/doc/frameworks/pytorch/using_pytorch.rst b/doc/frameworks/pytorch/using_pytorch.rst index 725f34aa5a..f56085f756 100644 --- a/doc/frameworks/pytorch/using_pytorch.rst +++ b/doc/frameworks/pytorch/using_pytorch.rst @@ -293,6 +293,121 @@ using two ``ml.p4d.24xlarge`` instances: pt_estimator.fit("s3://bucket/path/to/training/data") +.. _distributed-pytorch-training-on-trainium: + +Distributed Training with PyTorch Neuron on Trn1 instances +========================================================== + +SageMaker Training supports Amazon EC2 Trn1 instances powered by +`AWS Trainium <https://aws.amazon.com/machine-learning/trainium/>`_ device, +the second generation purpose-built machine learning accelerator from AWS. +Each Trn1 instance consists of up to 16 Trainium devices, and each +Trainium device consists of two `NeuronCores +<https://awsdocs-neuron.readthedocs-hosted.com/en/latest/general/arch/neuron-hardware/trn1-arch.html#trainium-architecture>`_ +in the *AWS Neuron Documentation*. + +You can run distributed training job on Trn1 instances. +SageMaker supports the ``xla`` package through ``torchrun``. +With this, you do not need to manually pass ``RANK``, +``WORLD_SIZE``, ``MASTER_ADDR``, and ``MASTER_PORT``. +You can launch the training job using the +:class:`sagemaker.pytorch.estimator.PyTorch` estimator class +with the ``torch_distributed`` option as the distribution strategy. + +.. note:: + + This ``torch_distributed`` support is available + in the AWS Deep Learning Containers for PyTorch Neuron starting v1.11.0. + To find a complete list of supported versions of PyTorch Neuron, see + `Neuron Containers <https://github.com/aws/deep-learning-containers/blob/master/available_images.md#neuron-containers>`_ + in the *AWS Deep Learning Containers GitHub repository*. + +.. note:: + + SageMaker Debugger is currently not supported with Trn1 instances. + +Adapt Your Training Script to Initialize with the XLA backend +------------------------------------------------------------- + +To initialize distributed training in your script, call +`torch.distributed.init_process_group +<https://pytorch.org/docs/master/distributed.html#torch.distributed.init_process_group>`_ +with the ``xla`` backend as shown below. + +.. code:: python + + import torch.distributed as dist + + dist.init_process_group('xla') + +SageMaker takes care of ``'MASTER_ADDR'`` and ``'MASTER_PORT'`` for you via ``torchrun`` + +For detailed documentation about modifying your training script for Trainium, see `Multi-worker data-parallel MLP training using torchrun <https://awsdocs-neuron.readthedocs-hosted.com/en/latest/frameworks/torch/torch-neuronx/tutorials/training/mlp.html?highlight=torchrun#multi-worker-data-parallel-mlp-training-using-torchrun>`_ in the *AWS Neuron Documentation*. + +**Currently Supported backends:** + +- ``xla`` for Trainium (Trn1) instances + +For up-to-date information on supported backends for Trn1 instances, see `AWS Neuron Documentation <https://awsdocs-neuron.readthedocs-hosted.com/en/latest/index.html>`_. + +Launching a Distributed Training Job on Trainium +------------------------------------------------ + +You can run multi-node distributed PyTorch training jobs on Trn1 instances using the +:class:`sagemaker.pytorch.estimator.PyTorch` estimator class. +With ``instance_count=1``, the estimator submits a +single-node training job to SageMaker; with ``instance_count`` greater +than one, a multi-node training job is launched. + +With the ``torch_distributed`` option, the SageMaker PyTorch estimator runs a SageMaker +training container for PyTorch Neuron, sets up the environment, and launches +the training job using the ``torchrun`` command on each worker with the given information. + +**Examples** + +The following examples show how to run a PyTorch training using ``torch_distributed`` in SageMaker +on one ``ml.trn1.2xlarge`` instance and two ``ml.trn1.32xlarge`` instances: + +.. code:: python + + from sagemaker.pytorch import PyTorch + + pt_estimator = PyTorch( + entry_point="train_torch_distributed.py", + role="SageMakerRole", + framework_version="1.11.0", + py_version="py38", + instance_count=1, + instance_type="ml.trn1.2xlarge", + distribution={ + "torch_distributed": { + "enabled": True + } + } + ) + + pt_estimator.fit("s3://bucket/path/to/training/data") + +.. code:: python + + from sagemaker.pytorch import PyTorch + + pt_estimator = PyTorch( + entry_point="train_torch_distributed.py", + role="SageMakerRole", + framework_version="1.11.0", + py_version="py38", + instance_count=2, + instance_type="ml.trn1.32xlarge", + distribution={ + "torch_distributed": { + "enabled": True + } + } + ) + + pt_estimator.fit("s3://bucket/path/to/training/data") + ********************* Deploy PyTorch Models ********************* diff --git a/src/sagemaker/image_uri_config/pytorch-neuron.json b/src/sagemaker/image_uri_config/pytorch-neuron.json new file mode 100644 index 0000000000..b116a8a36b --- /dev/null +++ b/src/sagemaker/image_uri_config/pytorch-neuron.json @@ -0,0 +1,41 @@ +{ + "training": { + "processors": ["trn"], + "version_aliases": {"1.11": "1.11.0"}, + "versions": { + "1.11.0": { + "py_versions": ["py38"], + "repository": "pytorch-training-neuron", + "registries": { + "af-south-1": "626614931356", + "ap-east-1": "871362719292", + "ap-northeast-1": "763104351884", + "ap-northeast-2": "763104351884", + "ap-northeast-3": "364406365360", + "ap-south-1": "763104351884", + "ap-southeast-1": "763104351884", + "ap-southeast-2": "763104351884", + "ca-central-1": "763104351884", + "cn-north-1": "727897471807", + "cn-northwest-1": "727897471807", + "eu-central-1": "763104351884", + "eu-north-1": "763104351884", + "eu-west-1": "763104351884", + "eu-west-2": "763104351884", + "eu-west-3": "763104351884", + "eu-south-1": "692866216735", + "me-south-1": "217643126080", + "sa-east-1": "763104351884", + "us-east-1": "763104351884", + "us-east-2": "763104351884", + "us-gov-west-1": "442386744353", + "us-iso-east-1": "886529160074", + "us-west-1": "763104351884", + "us-west-2": "763104351884" + }, + "container_version": {"trn": "ubuntu20.04"}, + "sdk_versions": ["sdk2.4.0"] + } + } + } + } \ No newline at end of file
[ { "components": [ { "doc": "Validate if framework is supported for the instance_type", "lines": [ 355, 362 ], "name": "_validate_for_suppported_frameworks_and_instance_type", "signature": "def _validate_for_suppported_frameworks_and_instance_type(framework, instace_type):", "type": "function" }, { "doc": "Checks if the framework is in the allowed frameworks, and raises a ``ValueError`` if not.", "lines": [ 546, 551 ], "name": "_validate_framework", "signature": "def _validate_framework(framework, allowed_frameworks, arg_name):", "type": "function" } ], "file": "src/sagemaker/image_uris.py" } ]
[ "tests/unit/sagemaker/image_uris/test_trainium.py::test_trainium_pytorch" ]
[]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> feature: Trainium Neuron support for PyTorch *Issue #, if available:* *Description of changes:* Added the necessary changes to incorporate the `v1.0-pt-1.11.0-tr-neuron-sdk2.3.0-py38` image into the `PyTorch` framework. *Testing done:* Locally tested the feature to extract image string with the following code, where the output matched with the [released DLC image](https://github.com/aws/deep-learning-containers/releases/tag/v1.0-pt-1.11.0-tr-neuron-sdk2.3.0-py38) ```bash import sagemaker, boto3 sagemaker.image_uris.retrieve(framework="pytorch", region=boto3.Session().region_name, instance_type="ml.trn1.xlarge") '763104351884.dkr.ecr.us-west-2.amazonaws.com/pytorch-training-neuron:1.11.0-neuron-py38-sdk2.3.0-ubuntu20.04' ``` ## Merge Checklist _Put an `x` in the boxes that apply. You can also fill these out after creating the PR. If you're unsure about any of them, don't hesitate to ask. We're here to help! This is simply a reminder of what we are going to look for before merging your pull request._ #### General - [x] I have read the [CONTRIBUTING](https://github.com/aws/sagemaker-python-sdk/blob/master/CONTRIBUTING.md) doc - [x] I certify that the changes I am introducing will be backward compatible, and I have discussed concerns about this, if any, with the Python SDK team - [x] I used the commit message format described in [CONTRIBUTING](https://github.com/aws/sagemaker-python-sdk/blob/master/CONTRIBUTING.md#committing-your-change) - [ ] I have passed the region in to all S3 and STS clients that I've initialized as part of this change. - [ ] I have updated any necessary documentation, including [READMEs](https://github.com/aws/sagemaker-python-sdk/blob/master/README.rst) and [API docs](https://github.com/aws/sagemaker-python-sdk/tree/master/doc) (if appropriate) #### Tests - [x] I have added tests that prove my fix is effective or that my feature works (if appropriate) - [x] I have added unit and/or integration tests as appropriate to ensure backward compatibility of the changes - [x] I have checked that my tests are not configured for a specific region or account (if appropriate) - [ ] I have used [`unique_name_from_base`](https://github.com/aws/sagemaker-python-sdk/blob/master/src/sagemaker/utils.py#L77) to create resource names in integ tests (if appropriate) By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license. ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in src/sagemaker/image_uris.py] (definition of _validate_for_suppported_frameworks_and_instance_type:) def _validate_for_suppported_frameworks_and_instance_type(framework, instace_type): """Validate if framework is supported for the instance_type""" (definition of _validate_framework:) def _validate_framework(framework, allowed_frameworks, arg_name): """Checks if the framework is in the allowed frameworks, and raises a ``ValueError`` if not.""" [end of new definitions in src/sagemaker/image_uris.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
03738861995e0c3fda73958d251e83465aba3c04
open-mmlab__mmengine-609
609
open-mmlab/mmengine
null
bc37c838d424b3d9ce5cbd4859540cdc03204026
2022-10-14T07:40:30Z
diff --git a/docs/en/api/utils.rst b/docs/en/api/utils.rst index 92466352a5..681e15d2c0 100644 --- a/docs/en/api/utils.rst +++ b/docs/en/api/utils.rst @@ -109,6 +109,7 @@ Miscellaneous to_ntuple check_prerequisites deprecated_api_warning + deprecated_function has_method is_method_overridden import_modules_from_strings diff --git a/docs/zh_cn/api/utils.rst b/docs/zh_cn/api/utils.rst index 92466352a5..681e15d2c0 100644 --- a/docs/zh_cn/api/utils.rst +++ b/docs/zh_cn/api/utils.rst @@ -109,6 +109,7 @@ Miscellaneous to_ntuple check_prerequisites deprecated_api_warning + deprecated_function has_method is_method_overridden import_modules_from_strings diff --git a/mmengine/utils/misc.py b/mmengine/utils/misc.py index cdb24d8c52..d7fa1fb39b 100644 --- a/mmengine/utils/misc.py +++ b/mmengine/utils/misc.py @@ -2,7 +2,10 @@ import collections.abc import functools import itertools +import logging +import re import subprocess +import textwrap import warnings from collections import abc from importlib import import_module @@ -387,3 +390,72 @@ def has_method(obj: object, method: str) -> bool: bool: True if the object has the method else False. """ return hasattr(obj, method) and callable(getattr(obj, method)) + + +def deprecated_function(since: str, removed_in: str, + instructions: str) -> Callable: + """Marks functions as deprecated. + + Throw a warning when a deprecated function is called, and add a note in the + docstring. Modified from https://github.com/pytorch/pytorch/blob/master/torch/onnx/_deprecation.py + + Args: + since (str): The version when the function was first deprecated. + removed_in (str): The version when the function will be removed. + instructions (str): The action users should take. + + Returns: + Callable: A new function, which will be deprecated soon. + """ # noqa: E501 + from mmengine import print_log + + def decorator(function): + + @functools.wraps(function) + def wrapper(*args, **kwargs): + print_log( + f"'{function.__module__}.{function.__name__}' " + f'is deprecated in version {since} and will be ' + f'removed in version {removed_in}. Please {instructions}.', + logger='current', + level=logging.WARNING, + ) + return function(*args, **kwargs) + + indent = ' ' + # Add a deprecation note to the docstring. + docstring = function.__doc__ or '' + # Add a note to the docstring. + deprecation_note = textwrap.dedent(f"""\ + .. deprecated:: {since} + Deprecated and will be removed in version {removed_in}. + Please {instructions}. + """) + # Split docstring at first occurrence of newline + pattern = '\n\n' + summary_and_body = re.split(pattern, docstring, 1) + + if len(summary_and_body) > 1: + summary, body = summary_and_body + body = textwrap.indent(textwrap.dedent(body), indent) + summary = '\n'.join( + [textwrap.dedent(string) for string in summary.split('\n')]) + summary = textwrap.indent(summary, prefix=indent) + # Dedent the body. We cannot do this with the presence of the + # summary because the body contains leading whitespaces when the + # summary does not. + new_docstring_parts = [ + deprecation_note, '\n\n', summary, '\n\n', body + ] + else: + summary = summary_and_body[0] + summary = '\n'.join( + [textwrap.dedent(string) for string in summary.split('\n')]) + summary = textwrap.indent(summary, prefix=indent) + new_docstring_parts = [deprecation_note, '\n\n', summary] + + wrapper.__doc__ = ''.join(new_docstring_parts) + + return wrapper + + return decorator
diff --git a/tests/test_utils/test_misc.py b/tests/test_utils/test_misc.py new file mode 100644 index 0000000000..95d7a006bd --- /dev/null +++ b/tests/test_utils/test_misc.py @@ -0,0 +1,285 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import pytest + +from mmengine import MMLogger +# yapf: disable +from mmengine.utils.misc import (concat_list, deprecated_api_warning, + deprecated_function, has_method, + import_modules_from_strings, is_list_of, + is_method_overridden, is_seq_of, is_tuple_of, + iter_cast, list_cast, requires_executable, + requires_package, slice_list, to_1tuple, + to_2tuple, to_3tuple, to_4tuple, to_ntuple, + tuple_cast) + +# yapf: enable + + +def test_to_ntuple(): + single_number = 2 + assert to_1tuple(single_number) == (single_number, ) + assert to_2tuple(single_number) == (single_number, single_number) + assert to_3tuple(single_number) == (single_number, single_number, + single_number) + assert to_4tuple(single_number) == (single_number, single_number, + single_number, single_number) + assert to_ntuple(5)(single_number) == (single_number, single_number, + single_number, single_number, + single_number) + assert to_ntuple(6)(single_number) == (single_number, single_number, + single_number, single_number, + single_number, single_number) + + +def test_iter_cast(): + assert list_cast([1, 2, 3], int) == [1, 2, 3] + assert list_cast(['1.1', 2, '3'], float) == [1.1, 2.0, 3.0] + assert list_cast([1, 2, 3], str) == ['1', '2', '3'] + assert tuple_cast((1, 2, 3), str) == ('1', '2', '3') + assert next(iter_cast([1, 2, 3], str)) == '1' + with pytest.raises(TypeError): + iter_cast([1, 2, 3], '') + with pytest.raises(TypeError): + iter_cast(1, str) + + +def test_is_seq_of(): + assert is_seq_of([1.0, 2.0, 3.0], float) + assert is_seq_of([(1, ), (2, ), (3, )], tuple) + assert is_seq_of((1.0, 2.0, 3.0), float) + assert is_list_of([1.0, 2.0, 3.0], float) + assert not is_seq_of((1.0, 2.0, 3.0), float, seq_type=list) + assert not is_tuple_of([1.0, 2.0, 3.0], float) + assert not is_seq_of([1.0, 2, 3], int) + assert not is_seq_of((1.0, 2, 3), int) + + +def test_slice_list(): + in_list = [1, 2, 3, 4, 5, 6] + assert slice_list(in_list, [1, 2, 3]) == [[1], [2, 3], [4, 5, 6]] + assert slice_list(in_list, [len(in_list)]) == [in_list] + with pytest.raises(TypeError): + slice_list(in_list, 2.0) + with pytest.raises(ValueError): + slice_list(in_list, [1, 2]) + + +def test_concat_list(): + assert concat_list([[1, 2]]) == [1, 2] + assert concat_list([[1, 2], [3, 4, 5], [6]]) == [1, 2, 3, 4, 5, 6] + + +def test_requires_package(capsys): + + @requires_package('nnn') + def func_a(): + pass + + @requires_package(['numpy', 'n1', 'n2']) + def func_b(): + pass + + @requires_package('numpy') + def func_c(): + return 1 + + with pytest.raises(RuntimeError): + func_a() + out, _ = capsys.readouterr() + assert out == ('Prerequisites "nnn" are required in method "func_a" but ' + 'not found, please install them first.\n') + + with pytest.raises(RuntimeError): + func_b() + out, _ = capsys.readouterr() + assert out == ( + 'Prerequisites "n1, n2" are required in method "func_b" but not found,' + ' please install them first.\n') + + assert func_c() == 1 + + +def test_requires_executable(capsys): + + @requires_executable('nnn') + def func_a(): + pass + + @requires_executable(['ls', 'n1', 'n2']) + def func_b(): + pass + + @requires_executable('mv') + def func_c(): + return 1 + + with pytest.raises(RuntimeError): + func_a() + out, _ = capsys.readouterr() + assert out == ('Prerequisites "nnn" are required in method "func_a" but ' + 'not found, please install them first.\n') + + with pytest.raises(RuntimeError): + func_b() + out, _ = capsys.readouterr() + assert out == ( + 'Prerequisites "n1, n2" are required in method "func_b" but not found,' + ' please install them first.\n') + + assert func_c() == 1 + + +def test_import_modules_from_strings(): + # multiple imports + import os.path as osp_ + import sys as sys_ + osp, sys = import_modules_from_strings(['os.path', 'sys']) + assert osp == osp_ + assert sys == sys_ + + # single imports + osp = import_modules_from_strings('os.path') + assert osp == osp_ + # No imports + assert import_modules_from_strings(None) is None + assert import_modules_from_strings([]) is None + assert import_modules_from_strings('') is None + # Unsupported types + with pytest.raises(TypeError): + import_modules_from_strings(1) + with pytest.raises(TypeError): + import_modules_from_strings([1]) + # Failed imports + with pytest.raises(ImportError): + import_modules_from_strings('_not_implemented_module') + with pytest.warns(UserWarning): + imported = import_modules_from_strings( + '_not_implemented_module', allow_failed_imports=True) + assert imported is None + with pytest.warns(UserWarning): + imported = import_modules_from_strings(['os.path', '_not_implemented'], + allow_failed_imports=True) + assert imported[0] == osp + assert imported[1] is None + + +def test_is_method_overridden(): + + class Base: + + def foo1(): + pass + + def foo2(): + pass + + class Sub(Base): + + def foo1(): + pass + + # test passing sub class directly + assert is_method_overridden('foo1', Base, Sub) + assert not is_method_overridden('foo2', Base, Sub) + + # test passing instance of sub class + sub_instance = Sub() + assert is_method_overridden('foo1', Base, sub_instance) + assert not is_method_overridden('foo2', Base, sub_instance) + + # base_class should be a class, not instance + base_instance = Base() + with pytest.raises(AssertionError): + is_method_overridden('foo1', base_instance, sub_instance) + + +def test_has_method(): + + class Foo: + + def __init__(self, name): + self.name = name + + def print_name(self): + print(self.name) + + foo = Foo('foo') + assert not has_method(foo, 'name') + assert has_method(foo, 'print_name') + + +def test_deprecated_api_warning(): + + @deprecated_api_warning(name_dict=dict(old_key='new_key')) + def dummy_func(new_key=1): + return new_key + + # replace `old_key` to `new_key` + assert dummy_func(old_key=2) == 2 + + # The expected behavior is to replace the + # deprecated key `old_key` to `new_key`, + # but got them in the arguments at the same time + with pytest.raises(AssertionError): + dummy_func(old_key=1, new_key=2) + + +def test_deprecated_function(): + + @deprecated_function('0.2.0', '0.3.0', 'toy instruction') + def deprecated_demo(arg1: int, arg2: int) -> tuple: + """This is a long summary. This is a long summary. This is a long + summary. This is a long summary. + + Args: + arg1 (int): Long description with a line break. Long description + with a line break. + arg2 (int): short description. + + Returns: + Long description without a line break. Long description without + a line break. + """ + + return arg1, arg2 + + MMLogger.get_instance('test_deprecated_function') + deprecated_demo(1, 2) + # out, _ = capsys.readouterr() + # assert "'test_misc.deprecated_demo' is deprecated" in out + assert (1, 2) == deprecated_demo(1, 2) + + expected_docstring = \ + """.. deprecated:: 0.2.0 + Deprecated and will be removed in version 0.3.0. + Please toy instruction. + + + This is a long summary. This is a long summary. This is a long + summary. This is a long summary. + + Args: + arg1 (int): Long description with a line break. Long description + with a line break. + arg2 (int): short description. + + Returns: + Long description without a line break. Long description without + a line break. + """ # noqa: E122 + assert expected_docstring.strip(' ') == deprecated_demo.__doc__ + MMLogger._instance_dict.clear() + + # Test with short summary without args. + @deprecated_function('0.2.0', '0.3.0', 'toy instruction') + def deprecated_demo1(): + """Short summary.""" + + expected_docstring = \ + """.. deprecated:: 0.2.0 + Deprecated and will be removed in version 0.3.0. + Please toy instruction. + + + Short summary.""" # noqa: E122 + assert expected_docstring.strip(' ') == deprecated_demo1.__doc__
diff --git a/docs/en/api/utils.rst b/docs/en/api/utils.rst index 92466352a5..681e15d2c0 100644 --- a/docs/en/api/utils.rst +++ b/docs/en/api/utils.rst @@ -109,6 +109,7 @@ Miscellaneous to_ntuple check_prerequisites deprecated_api_warning + deprecated_function has_method is_method_overridden import_modules_from_strings diff --git a/docs/zh_cn/api/utils.rst b/docs/zh_cn/api/utils.rst index 92466352a5..681e15d2c0 100644 --- a/docs/zh_cn/api/utils.rst +++ b/docs/zh_cn/api/utils.rst @@ -109,6 +109,7 @@ Miscellaneous to_ntuple check_prerequisites deprecated_api_warning + deprecated_function has_method is_method_overridden import_modules_from_strings
[ { "components": [ { "doc": "Marks functions as deprecated.\n\nThrow a warning when a deprecated function is called, and add a note in the\ndocstring. Modified from https://github.com/pytorch/pytorch/blob/master/torch/onnx/_deprecation.py\n\nArgs:\n since (str): The version when the function was first deprecated.\n removed_in (str): The version when the function will be removed.\n instructions (str): The action users should take.\n\nReturns:\n Callable: A new function, which will be deprecated soon.", "lines": [ 395, 461 ], "name": "deprecated_function", "signature": "def deprecated_function(since: str, removed_in: str, instructions: str) -> Callable:", "type": "function" }, { "doc": "", "lines": [ 412, 459 ], "name": "deprecated_function.decorator", "signature": "def decorator(function): @functools.wraps(function)", "type": "function" }, { "doc": "", "lines": [ 415, 423 ], "name": "deprecated_function.decorator.wrapper", "signature": "def wrapper(*args, **kwargs):", "type": "function" } ], "file": "mmengine/utils/misc.py" } ]
[ "tests/test_utils/test_misc.py::test_to_ntuple", "tests/test_utils/test_misc.py::test_iter_cast", "tests/test_utils/test_misc.py::test_is_seq_of", "tests/test_utils/test_misc.py::test_slice_list", "tests/test_utils/test_misc.py::test_concat_list", "tests/test_utils/test_misc.py::test_requires_package", "tests/test_utils/test_misc.py::test_requires_executable", "tests/test_utils/test_misc.py::test_import_modules_from_strings", "tests/test_utils/test_misc.py::test_is_method_overridden", "tests/test_utils/test_misc.py::test_has_method", "tests/test_utils/test_misc.py::test_deprecated_api_warning", "tests/test_utils/test_misc.py::test_deprecated_function" ]
[]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> [Enhancement] Add a function to mark the deprecated function. Thanks for your contribution and we appreciate it a lot. The following instructions would make your pull request more healthy and more easily get feedback. If you do not understand some items, don't worry, just make the pull request and seek help from maintainers. ## Motivation Add a function to mark the deprecated function (copied from https://github.com/pytorch/pytorch/blob/master/torch/onnx/_deprecation.py). ## Modification Please briefly describe what modification is made in this PR. ## BC-breaking (Optional) Does the modification introduce changes that break the backward-compatibility of the downstream repos? If so, please describe how it breaks the compatibility and how the downstream projects should modify their code to keep compatibility with this PR. ## Use cases (Optional) If this PR introduces a new feature, it is better to list some use cases here, and update the documentation. ## Checklist 1. Pre-commit or other linting tools are used to fix the potential lint issues. 2. The modification is covered by complete unit tests. If not, please add more unit test to ensure the correctness. 3. If the modification has potential influence on downstream projects, this PR should be tested with downstream projects, like MMDet or MMCls. 4. The documentation has been modified accordingly, like docstring or example tutorials. ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in mmengine/utils/misc.py] (definition of deprecated_function:) def deprecated_function(since: str, removed_in: str, instructions: str) -> Callable: """Marks functions as deprecated. Throw a warning when a deprecated function is called, and add a note in the docstring. Modified from https://github.com/pytorch/pytorch/blob/master/torch/onnx/_deprecation.py Args: since (str): The version when the function was first deprecated. removed_in (str): The version when the function will be removed. instructions (str): The action users should take. Returns: Callable: A new function, which will be deprecated soon.""" (definition of deprecated_function.decorator:) def decorator(function): @functools.wraps(function) (definition of deprecated_function.decorator.wrapper:) def wrapper(*args, **kwargs): [end of new definitions in mmengine/utils/misc.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
53474ef1ba0b166508c231fa525b55b580adf20f
sqlfluff__sqlfluff-3937
3,937
sqlfluff/sqlfluff
1.3
f691f033ac90e760bb70f0f9d02c89a859565d6d
2022-10-08T18:54:38Z
diff --git a/.gitignore b/.gitignore index 95882a5bcdc..9bc74ff9001 100644 --- a/.gitignore +++ b/.gitignore @@ -39,6 +39,9 @@ test-reports # Ignore dbt outputs from testing /target +# Ignore any timing outputs +/*.csv + # Ignore conda environment.yml contributors might be using and direnv config environment.yml .envrc diff --git a/src/sqlfluff/cli/commands.py b/src/sqlfluff/cli/commands.py index 64ea38cd1e4..b2dfc29d98f 100644 --- a/src/sqlfluff/cli/commands.py +++ b/src/sqlfluff/cli/commands.py @@ -514,6 +514,16 @@ def dump_file_payload(filename: Optional[str], payload: str): cls=DeprecatedOption, deprecated=["--disable_progress_bar"], ) +@click.option( + "--persist-timing", + default=None, + help=( + "A filename to persist the timing information for a linting run to " + "in csv format for external analysis. NOTE: This feature should be " + "treated as beta, and the format of the csv file may change in " + "future releases without warning." + ), +) @click.argument("paths", nargs=-1, type=click.Path(allow_dash=True)) def lint( paths: Tuple[str], @@ -528,6 +538,7 @@ def lint( disable_progress_bar: Optional[bool] = False, extra_config_path: Optional[str] = None, ignore_local_config: bool = False, + persist_timing: Optional[str] = None, **kwargs, ) -> None: """Lint SQL files via passing a list of files or using stdin. @@ -642,6 +653,9 @@ def lint( if file_output: dump_file_payload(write_output, cast(str, file_output)) + if persist_timing: + result.persist_timing_records(persist_timing) + output_stream.close() if bench: click.echo("==== overall timings ====") diff --git a/src/sqlfluff/core/linter/linting_result.py b/src/sqlfluff/core/linter/linting_result.py index b5860df2b35..5270768ee15 100644 --- a/src/sqlfluff/core/linter/linting_result.py +++ b/src/sqlfluff/core/linter/linting_result.py @@ -1,5 +1,6 @@ """Defines the linter class.""" +import csv import time from typing import ( Any, @@ -146,6 +147,50 @@ def timing_summary(self) -> Dict[str, Dict[str, float]]: timing.add(file.time_dict) return timing.summary() + def persist_timing_records(self, filename): + """Persist the timing records as a csv to external analysis.""" + meta_fields = [ + "path", + "source_chars", + "templated_chars", + "segments", + "raw_segments", + ] + timing_fields = ["templating", "lexing", "parsing", "linting"] + with open(filename, "w", newline="") as f: + writer = csv.DictWriter(f, fieldnames=meta_fields + timing_fields) + + writer.writeheader() + + for dir in self.paths: + for file in dir.files: + writer.writerow( + { + "path": file.path, + "source_chars": ( + len(file.templated_file.source_str) + if file.templated_file + else "" + ), + "templated_chars": ( + len(file.templated_file.templated_str) + if file.templated_file + else "" + ), + "segments": ( + file.tree.count_segments(raw_only=False) + if file.tree + else "" + ), + "raw_segments": ( + file.tree.count_segments(raw_only=True) + if file.tree + else "" + ), + **file.time_dict, + } + ) + def as_records(self) -> List[dict]: """Return the result as a list of dictionaries. diff --git a/src/sqlfluff/core/parser/segments/base.py b/src/sqlfluff/core/parser/segments/base.py index 91e320900fd..0a60c5c0277 100644 --- a/src/sqlfluff/core/parser/segments/base.py +++ b/src/sqlfluff/core/parser/segments/base.py @@ -864,6 +864,16 @@ def get_type(self): """Returns the type of this segment as a string.""" return self.type + def count_segments(self, raw_only=False): + """Returns the number of segments in this segment.""" + if self.segments: + self_count = 0 if raw_only else 1 + return self_count + sum( + seg.count_segments(raw_only=raw_only) for seg in self.segments + ) + else: + return 1 + def is_type(self, *seg_type): """Is this segment (or its parent) of the given type.""" return self.class_is_type(*seg_type)
diff --git a/test/cli/commands_test.py b/test/cli/commands_test.py index b9630eaa11e..ba0effb615a 100644 --- a/test/cli/commands_test.py +++ b/test/cli/commands_test.py @@ -441,6 +441,8 @@ def test__cli__command_lint_stdin(command): "test/fixtures/cli/extra_config_tsql.sql", ], ), + # Check timing outputs doesn't raise exceptions + (lint, ["test/fixtures/cli/passing_a.sql", "--persist-timing", "test.csv"]), ], ) def test__cli__command_lint_parse(command): diff --git a/test/core/parser/segments_base_test.py b/test/core/parser/segments_base_test.py index d763521b6c7..03e1e9662d4 100644 --- a/test/core/parser/segments_base_test.py +++ b/test/core/parser/segments_base_test.py @@ -64,6 +64,13 @@ def test__parser__base_segments_direct_descendant_type_set(raw_seg_list): assert test_seg.direct_descendant_type_set == {"base", "dummy_aux"} +def test__parser__base_segments_count_segments(raw_seg_list): + """Test the .count_segments() method.""" + test_seg = DummySegment([DummyAuxSegment(raw_seg_list)]) + assert test_seg.count_segments() == 4 + assert test_seg.count_segments(raw_only=True) == 2 + + def test__parser__base_segments_path_to(raw_seg_list): """Test the .path_to() method.""" test_seg_a = DummyAuxSegment(raw_seg_list)
diff --git a/.gitignore b/.gitignore index 95882a5bcdc..9bc74ff9001 100644 --- a/.gitignore +++ b/.gitignore @@ -39,6 +39,9 @@ test-reports # Ignore dbt outputs from testing /target +# Ignore any timing outputs +/*.csv + # Ignore conda environment.yml contributors might be using and direnv config environment.yml .envrc
[ { "components": [ { "doc": "Persist the timing records as a csv to external analysis.", "lines": [ 150, 190 ], "name": "LintingResult.persist_timing_records", "signature": "def persist_timing_records(self, filename):", "type": "function" } ], "file": "src/sqlfluff/core/linter/linting_result.py" }, { "components": [ { "doc": "Returns the number of segments in this segment.", "lines": [ 867, 875 ], "name": "BaseSegment.count_segments", "signature": "def count_segments(self, raw_only=False):", "type": "function" } ], "file": "src/sqlfluff/core/parser/segments/base.py" } ]
[ "test/cli/commands_test.py::test__cli__command_lint_parse[command24]", "test/core/parser/segments_base_test.py::test__parser__base_segments_count_segments" ]
[ "test/cli/commands_test.py::test__cli__command_directed", "test/cli/commands_test.py::test__cli__command_dialect", "test/cli/commands_test.py::test__cli__command_no_dialect", "test/cli/commands_test.py::test__cli__command_parse_error_dialect_explicit_warning", "test/cli/commands_test.py::test__cli__command_parse_error_dialect_implicit_warning", "test/cli/commands_test.py::test__cli__command_dialect_legacy", "test/cli/commands_test.py::test__cli__command_extra_config_fail", "test/cli/commands_test.py::test__cli__command_lint_stdin[command0]", "test/cli/commands_test.py::test__cli__command_lint_stdin[command1]", "test/cli/commands_test.py::test__cli__command_lint_stdin[command2]", "test/cli/commands_test.py::test__cli__command_lint_stdin[command3]", "test/cli/commands_test.py::test__cli__command_lint_parse[command0]", "test/cli/commands_test.py::test__cli__command_lint_parse[command1]", "test/cli/commands_test.py::test__cli__command_lint_parse[command2]", "test/cli/commands_test.py::test__cli__command_lint_parse[command3]", "test/cli/commands_test.py::test__cli__command_lint_parse[command4]", "test/cli/commands_test.py::test__cli__command_lint_parse[command5]", "test/cli/commands_test.py::test__cli__command_lint_parse[command6]", "test/cli/commands_test.py::test__cli__command_lint_parse[command7]", "test/cli/commands_test.py::test__cli__command_lint_parse[command8]", "test/cli/commands_test.py::test__cli__command_lint_parse[command9]", "test/cli/commands_test.py::test__cli__command_lint_parse[command10]", "test/cli/commands_test.py::test__cli__command_lint_parse[command11]", "test/cli/commands_test.py::test__cli__command_lint_parse[command12]", "test/cli/commands_test.py::test__cli__command_lint_parse[command13]", "test/cli/commands_test.py::test__cli__command_lint_parse[command14]", "test/cli/commands_test.py::test__cli__command_lint_parse[command15]", "test/cli/commands_test.py::test__cli__command_lint_parse[command16]", "test/cli/commands_test.py::test__cli__command_lint_parse[command17]", "test/cli/commands_test.py::test__cli__command_lint_parse[command18]", "test/cli/commands_test.py::test__cli__command_lint_parse[command19]", "test/cli/commands_test.py::test__cli__command_lint_parse[command20]", "test/cli/commands_test.py::test__cli__command_lint_parse[command21]", "test/cli/commands_test.py::test__cli__command_lint_parse[command22]", "test/cli/commands_test.py::test__cli__command_lint_parse[command23]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command0-1]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command1-1]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command2-1]", "test/cli/commands_test.py::test__cli__command_lint_parse_with_retcode[command3-1]", "test/cli/commands_test.py::test__cli__command_lint_warning_explicit_file_ignored", "test/cli/commands_test.py::test__cli__command_lint_skip_ignore_files", "test/cli/commands_test.py::test__cli__command_lint_ignore_local_config", "test/cli/commands_test.py::test__cli__command_versioning", "test/cli/commands_test.py::test__cli__command_version", "test/cli/commands_test.py::test__cli__command_rules", "test/cli/commands_test.py::test__cli__command_dialects", "test/cli/commands_test.py::test__cli__command__fix[L001-test/fixtures/linter/indentation_errors.sql]", "test/cli/commands_test.py::test__cli__command__fix[L008-test/fixtures/linter/whitespace_errors.sql]", "test/cli/commands_test.py::test__cli__command__fix[L008-test/fixtures/linter/indentation_errors.sql]", "test/cli/commands_test.py::test__cli__command__fix[L003-test/fixtures/linter/indentation_error_hard.sql]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[1_lint_error_1_unsuppressed_parse_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[1_lint_error_1_unsuppressed_templating_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[1_lint_error_1_suppressed_parse_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[0_lint_errors_1_unsuppressed_parse_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[0_lint_errors_1_suppressed_parse_error]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[1_lint_error_1_unsuppressed_parse_error_FIX_EVEN_UNPARSABLE]", "test/cli/commands_test.py::test__cli__fix_error_handling_behavior[2_files_with_lint_errors_1_unsuppressed_parse_error]", "test/cli/commands_test.py::test_cli_fix_even_unparsable[command-line-False]", "test/cli/commands_test.py::test_cli_fix_even_unparsable[command-line-True]", "test/cli/commands_test.py::test_cli_fix_even_unparsable[config-file-False]", "test/cli/commands_test.py::test_cli_fix_even_unparsable[config-file-True]", "test/cli/commands_test.py::test__cli__fix_loop_limit_behavior[--", "test/cli/commands_test.py::test__cli__command_fix_stdin[select", "test/cli/commands_test.py::test__cli__command_fix_stdin[", "test/cli/commands_test.py::test__cli__command_fix_stdin[SELECT", "test/cli/commands_test.py::test__cli__command_fix_stdin_logging_to_stderr", "test/cli/commands_test.py::test__cli__command_fix_stdin_safety", "test/cli/commands_test.py::test__cli__command_fix_stdin_error_exit_code[create", "test/cli/commands_test.py::test__cli__command_fix_stdin_error_exit_code[select", "test/cli/commands_test.py::test__cli__command__fix_no_force[L001-test/fixtures/linter/indentation_errors.sql-y-0-0]", "test/cli/commands_test.py::test__cli__command__fix_no_force[L001-test/fixtures/linter/indentation_errors.sql-n-1-1]", "test/cli/commands_test.py::test__cli__command_parse_serialize_from_stdin[None-yaml]", "test/cli/commands_test.py::test__cli__command_parse_serialize_from_stdin[None-json]", "test/cli/commands_test.py::test__cli__command_parse_serialize_from_stdin[outfile-yaml]", "test/cli/commands_test.py::test__cli__command_parse_serialize_from_stdin[outfile-json]", "test/cli/commands_test.py::test__cli__command_lint_serialize_from_stdin[select", "test/cli/commands_test.py::test__cli__command_lint_serialize_from_stdin[SElect", "test/cli/commands_test.py::test__cli__command_fail_nice_not_found[command0]", "test/cli/commands_test.py::test__cli__command_fail_nice_not_found[command1]", "test/cli/commands_test.py::test__cli__command_lint_nocolor", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-human]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-yaml]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-json]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-github-annotation]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[None-github-annotation-native]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-human]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-yaml]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-json]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-github-annotation]", "test/cli/commands_test.py::test__cli__command_lint_serialize_multiple_files[outfile-github-annotation-native]", "test/cli/commands_test.py::test__cli__command_lint_serialize_github_annotation", "test/cli/commands_test.py::test__cli__command_lint_serialize_github_annotation_native", "test/cli/commands_test.py::test__cli__command_lint_serialize_annotation_level_error_failure_equivalent[github-annotation]", "test/cli/commands_test.py::test__cli__command_lint_serialize_annotation_level_error_failure_equivalent[github-annotation-native]", "test/cli/commands_test.py::test___main___help", "test/cli/commands_test.py::test_encoding[utf-8-ascii]", "test/cli/commands_test.py::test_encoding[utf-8-sig-UTF-8-SIG]", "test/cli/commands_test.py::test_encoding[utf-32-UTF-32]", "test/cli/commands_test.py::test_cli_encoding[utf-8-command-line-False]", "test/cli/commands_test.py::test_cli_encoding[utf-8-SIG-command-line-True]", "test/cli/commands_test.py::test_cli_encoding[utf-8-config-file-False]", "test/cli/commands_test.py::test_cli_encoding[utf-8-SIG-config-file-True]", "test/cli/commands_test.py::test_cli_no_disable_noqa_flag", "test/cli/commands_test.py::test_cli_disable_noqa_flag", "test/cli/commands_test.py::test_cli_get_default_config", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_disabled_progress_bar", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_disabled_progress_bar_deprecated_option", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_enabled_progress_bar", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_enabled_progress_bar_multiple_paths", "test/cli/commands_test.py::TestProgressBars::test_cli_lint_enabled_progress_bar_multiple_files", "test/cli/commands_test.py::test__cli__fix_multiple_errors_no_show_errors", "test/cli/commands_test.py::test__cli__fix_multiple_errors_show_errors", "test/cli/commands_test.py::test__cli__multiple_files__fix_multiple_errors_show_errors", "test/core/parser/segments_base_test.py::test__parser__base_segments_type", "test/core/parser/segments_base_test.py::test__parser__base_segments_class_types", "test/core/parser/segments_base_test.py::test__parser__base_segments_descendant_type_set", "test/core/parser/segments_base_test.py::test__parser__base_segments_direct_descendant_type_set", "test/core/parser/segments_base_test.py::test__parser__base_segments_path_to", "test/core/parser/segments_base_test.py::test__parser__base_segments_stubs", "test/core/parser/segments_base_test.py::test__parser__base_segments_raw", "test/core/parser/segments_base_test.py::test__parser__base_segments_base", "test/core/parser/segments_base_test.py::test__parser__base_segments_raw_compare", "test/core/parser/segments_base_test.py::test__parser__base_segments_base_compare", "test/core/parser/segments_base_test.py::test__parser__base_segments_file", "test/core/parser/segments_base_test.py::test__parser__raw_get_raw_segments", "test/core/parser/segments_base_test.py::test__parser__raw_segments_with_ancestors" ]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> Enable dumping of performance information to csv. To enable a bit more introspection on performance information - this enables dumping performance information to an external csv file. I'd like to do some analysis on the results from our large project a little before going much further with this as a feature - but eventually I'd love to validate each releases performance via some indices. This might make @WittierDinosaur very happy (I hope). To get a sense of file complexity - I've added methods for raw segments, and total segments. These get included in the csv. For now this just add the ability to dump performance. I might backport it to some older releases locally to get an idea of performance changes over time, but I'm not going to try and re-release them (that sounds like too much work). ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in src/sqlfluff/core/linter/linting_result.py] (definition of LintingResult.persist_timing_records:) def persist_timing_records(self, filename): """Persist the timing records as a csv to external analysis.""" [end of new definitions in src/sqlfluff/core/linter/linting_result.py] [start of new definitions in src/sqlfluff/core/parser/segments/base.py] (definition of BaseSegment.count_segments:) def count_segments(self, raw_only=False): """Returns the number of segments in this segment.""" [end of new definitions in src/sqlfluff/core/parser/segments/base.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
ada7967cd2fb98de054323dd8aad19e84b427c67
softlayer__softlayer-python-1766
1,766
softlayer/softlayer-python
null
00e6a0677efb00ce3cd0562939fb7e98e00b2f99
2022-10-06T19:34:06Z
diff --git a/SoftLayer/CLI/core.py b/SoftLayer/CLI/core.py index 5425882da..b3a1fead0 100644 --- a/SoftLayer/CLI/core.py +++ b/SoftLayer/CLI/core.py @@ -34,7 +34,7 @@ } PROG_NAME = "slcli (SoftLayer Command-line)" -VALID_FORMATS = ['table', 'raw', 'json', 'jsonraw'] +VALID_FORMATS = ['table', 'raw', 'json', 'jsonraw', 'csv'] DEFAULT_FORMAT = 'raw' if sys.stdout.isatty(): diff --git a/SoftLayer/CLI/formatting.py b/SoftLayer/CLI/formatting.py index 02781fcf5..b4df8417d 100644 --- a/SoftLayer/CLI/formatting.py +++ b/SoftLayer/CLI/formatting.py @@ -6,8 +6,11 @@ """ # pylint: disable=E0202, consider-merging-isinstance, arguments-differ, keyword-arg-before-vararg import collections +import csv +import io import json import os +import sys import click from rich import box @@ -29,6 +32,8 @@ def format_output(data, fmt='table'): # pylint: disable=R0911,R0912 return json.dumps(data, indent=4, cls=CLIJSONEncoder) elif fmt == 'jsonraw': return json.dumps(data, cls=CLIJSONEncoder) + if fmt == 'csv': + return csv_output_format(data) if isinstance(data, str) or isinstance(data, rTable): return data @@ -440,3 +445,49 @@ def _format_list_objects(result): table.add_row(values) return table + + +def csv_output_format(data, delimiter=','): + """Formating a table to csv format and show it.""" + data = clean_table(data, delimiter) + write_csv_format(sys.stdout, data, delimiter) + return '' + + +def clean_table(data, delimiter): + """Delete Null fields by '-' and fix nested table in table""" + new_data_row = [] + for row in data.rows: + new_value = [] + for value in row: + if str(value) == 'NULL': + value = '-' + + if str(type(value)) == "<class 'SoftLayer.CLI.formatting.Table'>": + string_io = io.StringIO() + write_csv_format(string_io, value, delimiter) + + nested_table_converted = string_io.getvalue() + nested_table_converted = nested_table_converted.replace('\r', '').split('\n') + nested_table_converted.pop() + + title_nested_table = new_value.pop() + for item in nested_table_converted: + new_value.append(title_nested_table) + new_value.append(item) + new_data_row.append(new_value) + new_value = [] + else: + new_value.append(value) + + if len(new_value) != 0: + new_data_row.append(new_value) + data.rows = new_data_row + return data + + +def write_csv_format(support_output, data, delimiter): + """Write csv format to supported output""" + writer = csv.writer(support_output, delimiter=delimiter) + writer.writerow(data.columns) + writer.writerows(data.rows)
diff --git a/tests/CLI/modules/account_tests.py b/tests/CLI/modules/account_tests.py index 7e0792c07..b02b73032 100644 --- a/tests/CLI/modules/account_tests.py +++ b/tests/CLI/modules/account_tests.py @@ -66,6 +66,14 @@ def test_invoice_detail_details(self): self.assert_no_fail(result) self.assert_called_with('SoftLayer_Billing_Invoice', 'getInvoiceTopLevelItems', identifier='1234') + def test_invoice_detail_csv_output_format(self): + result = self.run_command(["--format", "csv", 'account', 'invoice-detail', '1234']) + result_output = result.output.replace('\r', '').split('\n') + self.assert_no_fail(result) + self.assertEqual(result_output[0], 'Item Id,Category,Description,Single,Monthly,Create Date,Location') + self.assertEqual(result_output[1], '724951323,Private (only) Secondary VLAN IP Addresses,64 Portable Private' + ' IP Addresses (bleg.beh.com),$0.00,$0.00,2018-04-04,fra02') + # slcli account invoices def test_invoices(self): result = self.run_command(['account', 'invoices']) diff --git a/tests/CLI/modules/vs/vs_tests.py b/tests/CLI/modules/vs/vs_tests.py index 46a0b994c..cb3b074be 100644 --- a/tests/CLI/modules/vs/vs_tests.py +++ b/tests/CLI/modules/vs/vs_tests.py @@ -313,6 +313,23 @@ def test_detail_vs_ptr_error(self): output = json.loads(result.output) self.assertEqual(output.get('ptr', None), None) + def test_vs_detail_csv_output_format_with_nested_tables(self): + result = self.run_command(["--format", "csv", 'vs', 'detail', '100']) + result_output = result.output.replace('\r', '').split('\n') + self.assert_no_fail(result) + self.assertEqual(result_output[0], 'name,value') + self.assertEqual(result_output[1], 'id,100') + self.assertEqual(result_output[16], 'drives,"Type,Name,Drive,Capacity"') + self.assertEqual(result_output[17], 'drives,"System,Disk,0,100 GB"') + self.assertEqual(result_output[18], 'drives,"Swap,Disk,1,2 GB"') + self.assertEqual(result_output[30], 'vlans,"type,number,id"') + self.assertEqual(result_output[31], 'vlans,"PUBLIC,23,1"') + self.assertEqual(result_output[32], 'Bandwidth,"Type,In GB,Out GB,Allotment"') + self.assertEqual(result_output[33], 'Bandwidth,"Public,.448,.52157,250"') + self.assertEqual(result_output[34], 'Bandwidth,"Private,.03842,.01822,N/A"') + self.assertEqual(result_output[35], 'security_groups,"interface,id,name"') + self.assertEqual(result_output[36], 'security_groups,"PRIVATE,128321,allow_all"') + def test_create_options(self): result = self.run_command(['vs', 'create-options', '--vsi-type', 'TRANSIENT_CLOUD_SERVER']) self.assert_no_fail(result)
[ { "components": [ { "doc": "Formating a table to csv format and show it.", "lines": [ 450, 454 ], "name": "csv_output_format", "signature": "def csv_output_format(data, delimiter=','):", "type": "function" }, { "doc": "Delete Null fields by '-' and fix nested table in table", "lines": [ 457, 486 ], "name": "clean_table", "signature": "def clean_table(data, delimiter):", "type": "function" }, { "doc": "Write csv format to supported output", "lines": [ 489, 493 ], "name": "write_csv_format", "signature": "def write_csv_format(support_output, data, delimiter):", "type": "function" } ], "file": "SoftLayer/CLI/formatting.py" } ]
[ "tests/CLI/modules/account_tests.py::AccountCLITests::test_invoice_detail_csv_output_format", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_vs_detail_csv_output_format_with_nested_tables" ]
[ "tests/CLI/modules/account_tests.py::AccountCLITests::test_acccount_bandwidth_pool_detail", "tests/CLI/modules/account_tests.py::AccountCLITests::test_acccount_licenses", "tests/CLI/modules/account_tests.py::AccountCLITests::test_acccount_order", "tests/CLI/modules/account_tests.py::AccountCLITests::test_account_billing_items", "tests/CLI/modules/account_tests.py::AccountCLITests::test_account_cancel_item", "tests/CLI/modules/account_tests.py::AccountCLITests::test_account_get_billing_item_detail", "tests/CLI/modules/account_tests.py::AccountCLITests::test_account_summary", "tests/CLI/modules/account_tests.py::AccountCLITests::test_bandwidth_pools", "tests/CLI/modules/account_tests.py::AccountCLITests::test_event_ack_all", "tests/CLI/modules/account_tests.py::AccountCLITests::test_event_detail", "tests/CLI/modules/account_tests.py::AccountCLITests::test_event_details_ack", "tests/CLI/modules/account_tests.py::AccountCLITests::test_event_jsonraw_output", "tests/CLI/modules/account_tests.py::AccountCLITests::test_events", "tests/CLI/modules/account_tests.py::AccountCLITests::test_invoice_detail", "tests/CLI/modules/account_tests.py::AccountCLITests::test_invoice_detail_details", "tests/CLI/modules/account_tests.py::AccountCLITests::test_invoices", "tests/CLI/modules/account_tests.py::AccountCLITests::test_invoices_all", "tests/CLI/modules/account_tests.py::AccountCLITests::test_invoices_closed", "tests/CLI/modules/account_tests.py::AccountCLITests::test_invoices_limited", "tests/CLI/modules/account_tests.py::AccountCLITests::test_single_invoice", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_add_notification", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_authorize_portable_storage_vs", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_authorize_storage_vs", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_authorize_storage_vs_no_confirm", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_authorize_volume_and_portable_storage_vs", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_authorize_vs_empty", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_billing", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_cancel", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_cancel_no_confirm", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_create_options", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_create_options_prices", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_create_options_prices_location", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_credentail", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_detail_drives_swap", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_detail_drives_system", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_detail_vs", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_detail_vs_dedicated_host_not_found", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_detail_vs_empty_allotment", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_detail_vs_empty_billing", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_detail_vs_empty_tag", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_detail_vs_no_dedicated_host_hostname", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_detail_vs_ptr_error", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_detail_vs_security_group", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_dns_sync_both", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_dns_sync_edit_a", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_dns_sync_edit_ptr", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_dns_sync_misc_exception", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_dns_sync_v6", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_edit", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_going_ready", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_last_transaction_empty", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_list_vs", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_list_vsi", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_monitoring_vs", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_not_ready", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_notifications", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_pause_vs", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_pause_vs_no_confirm", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_power_off_vs_hard", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_power_off_vs_no_confirm", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_power_on_vs", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_power_vs_off_soft", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_ready", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_reboot_vs_default", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_reboot_vs_hard", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_reboot_vs_no_confirm", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_reboot_vs_soft", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_reload", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_reload_no_confirm", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_rescue_vs", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_rescue_vs_no_confirm", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_resume_vs", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_upgrade", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_upgrade_aborted", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_upgrade_disk", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_upgrade_disk_error", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_upgrade_no_options", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_upgrade_private_no_cpu", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_upgrade_with_add_disk", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_upgrade_with_cpu_memory_and_flavor", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_upgrade_with_flavor", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_usage_metric_data_empty", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_usage_no_confirm", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_usage_vs", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_usage_vs_cpu", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_usage_vs_cpu_lower_case", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_usage_vs_memory", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_user_access", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_vs_capture", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_vs_migrate_all", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_vs_migrate_all_empty", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_vs_migrate_dedicated", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_vs_migrate_exception", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_vs_migrate_guest", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_vs_migrate_list", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_vs_migrate_list_empty", "tests/CLI/modules/vs/vs_tests.py::VirtTests::test_vs_storage" ]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> Added csv output format Issue: #1320 ``` softlayer-python/ () $ slcli --format csv vs list id,hostname,domain,deviceStatus.name,datacenter,primary_ip,backend_ip,createDate,action 1002,adns,vmware.chechu.com,Running,dal10,48.110,122.174,2020-04-06T05:28:15-06:00,- 1323,easerverh,easerverd.cloud,Running,dal13,227.82,211.196,2022-08-11T10:52:46-06:00,- 1204,fotest,test.local,Running,dal05,148.28,12.198,2021-05-19T12:29:55-06:00,- 1278,lab-web,test.com,Running,dal05,148.27,12.203,2022-02-08T08:31:46-06:00,- 1278,lab-web,test.com,Running,dal05,148.26,12.220,2022-02-08T08:33:12-06:00,- 1023,reserved,example.com,Stopped,dal13,-,-,2020-05-12T14:10:22-06:00,- 1096,techsupport,SoftLayer-Internal-Development-Community.cloud,Running,sao01,169.57.227.67,10.151.109.245,2020-09-25T09:34:12-06:00,- ``` Note: Possible upgrade options Add option to download the output as a file .csv Add option to change the deliminator, now by default ',' ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in SoftLayer/CLI/formatting.py] (definition of csv_output_format:) def csv_output_format(data, delimiter=','): """Formating a table to csv format and show it.""" (definition of clean_table:) def clean_table(data, delimiter): """Delete Null fields by '-' and fix nested table in table""" (definition of write_csv_format:) def write_csv_format(support_output, data, delimiter): """Write csv format to supported output""" [end of new definitions in SoftLayer/CLI/formatting.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
bd1ecce1ec4313b9ceefd3cfea52d1b9274fef9d
conan-io__conan-12243
12,243
conan-io/conan
null
6f8f9c5d179ce71877a89826d5275e83e9958f7a
2022-10-04T21:25:40Z
diff --git a/conan/api/subapi/install.py b/conan/api/subapi/install.py index 18b37a2b3ab..30e79be593b 100644 --- a/conan/api/subapi/install.py +++ b/conan/api/subapi/install.py @@ -49,7 +49,7 @@ def install_consumer(self, deps_graph, generators=None, source_folder=None, outp if deploy: base_folder = conanfile.folders.base_build mkdir(base_folder) - _do_deploys(self.conan_api, deps_graph, deploy, base_folder) + do_deploys(self.conan_api, deps_graph, deploy, base_folder) conanfile.generators = list(set(conanfile.generators).union(generators or [])) app = ConanApp(self.conan_api.cache_folder) @@ -87,17 +87,16 @@ def _load(path): raise ConanException(f"Cannot find deployer '{d}'") -def _do_deploys(conan_api, graph, deploy, deploy_folder): +def do_deploys(conan_api, graph, deploy, deploy_folder): # Handle the deploys cache = ClientCache(conan_api.cache_folder) for d in deploy or []: deployer = _find_deployer(d, cache.deployers_path) # IMPORTANT: Use always kwargs to not break if it changes in the future - conanfile = graph.root.conanfile - deployer(conanfile=conanfile, output_folder=deploy_folder) + deployer(graph=graph, output_folder=deploy_folder) -def full_deploy(conanfile, output_folder): +def full_deploy(graph, output_folder): """ Deploys to output_folder + host/dep/0.1/Release/x86_64 subfolder """ @@ -106,6 +105,7 @@ def full_deploy(conanfile, output_folder): import os import shutil + conanfile = graph.root.conanfile conanfile.output.info(f"Conan built-in full deployer to {output_folder}") for dep in conanfile.dependencies.values(): if dep.package_folder is None: @@ -123,7 +123,7 @@ def full_deploy(conanfile, output_folder): dep.set_deploy_folder(new_folder) -def direct_deploy(conanfile, output_folder): +def direct_deploy(graph, output_folder): """ Deploys to output_folder a single package, """ @@ -132,6 +132,7 @@ def direct_deploy(conanfile, output_folder): import os import shutil + conanfile = graph.root.conanfile conanfile.output.info(f"Conan built-in pkg deployer to {output_folder}") # If the argument is --requires, the current conanfile is a virtual one with 1 single # dependency, the "reference" package. If the argument is a local path, then all direct diff --git a/conan/cli/commands/graph.py b/conan/cli/commands/graph.py index f67f03dc8d8..7356ac8e96d 100644 --- a/conan/cli/commands/graph.py +++ b/conan/cli/commands/graph.py @@ -2,6 +2,7 @@ import os from conan.api.output import ConanOutput, cli_out_write +from conan.api.subapi.install import do_deploys from conan.cli.command import conan_command, COMMAND_GROUPS, conan_subcommand, \ Extender from conan.cli.commands import make_abs_path @@ -86,6 +87,8 @@ def graph_info(conan_api, parser, subparser, *args): help="Show only the specified fields") subparser.add_argument("--package-filter", nargs=1, action=Extender, help='Print information only for packages that match the patterns') + subparser.add_argument("--deploy", action=Extender, + help='Deploy using the provided deployer to the output folder') args = parser.parse_args(*args) # parameter validation @@ -102,6 +105,8 @@ def graph_info(conan_api, parser, subparser, *args): print_graph_info(deps_graph, args.filter, args.package_filter) save_lockfile_out(args, deps_graph, lockfile, os.getcwd()) + if args.deploy: + base_folder = os.getcwd() + do_deploys(conan_api, deps_graph, args.deploy, base_folder) return deps_graph, os.path.join(conan_api.cache_folder, "templates") -
diff --git a/conans/test/functional/command/test_install_deploy.py b/conans/test/functional/command/test_install_deploy.py index d004cc0f5de..7800b06e807 100644 --- a/conans/test/functional/command/test_install_deploy.py +++ b/conans/test/functional/command/test_install_deploy.py @@ -21,7 +21,8 @@ def test_install_deploy(): import os, shutil # USE **KWARGS to be robust against changes - def deploy(conanfile, output_folder, **kwargs): + def deploy(graph, output_folder, **kwargs): + conanfile = graph.root.conanfile for r, d in conanfile.dependencies.items(): new_folder = os.path.join(output_folder, d.ref.name) shutil.copytree(d.package_folder, new_folder) @@ -51,7 +52,8 @@ def test_copy_files_deploy(): deploy = textwrap.dedent(""" import os, shutil - def deploy(conanfile, output_folder, **kwargs): + def deploy(graph, output_folder, **kwargs): + conanfile = graph.root.conanfile for r, d in conanfile.dependencies.items(): bindir = os.path.join(d.package_folder, "bin") for f in os.listdir(bindir): @@ -73,15 +75,18 @@ def test_multi_deploy(): """ c = TestClient() deploy1 = textwrap.dedent(""" - def deploy(conanfile, output_folder, **kwargs): + def deploy(graph, output_folder, **kwargs): + conanfile = graph.root.conanfile conanfile.output.info("deploy1!!") """) deploy2 = textwrap.dedent(""" - def deploy(conanfile, output_folder, **kwargs): + def deploy(graph, output_folder, **kwargs): + conanfile = graph.root.conanfile conanfile.output.info("sub/deploy2!!") """) deploy_cache = textwrap.dedent(""" - def deploy(conanfile, output_folder, **kwargs): + def deploy(graph, output_folder, **kwargs): + conanfile = graph.root.conanfile conanfile.output.info("deploy cache!!") """) save(os.path.join(c.cache_folder, "extensions", "deploy", "deploy_cache.py"), deploy_cache) diff --git a/conans/test/integration/command/info/info_test.py b/conans/test/integration/command/info/info_test.py index 2ced3f0f00d..3238f71d094 100644 --- a/conans/test/integration/command/info/info_test.py +++ b/conans/test/integration/command/info/info_test.py @@ -227,3 +227,34 @@ def build_requirements(self): client.run("graph info . " + args) assert "AttributeError: 'HelloConan' object has no attribute 'tested_reference_str'"\ not in client.out + + +class TestDeployers: + + def test_custom_deploy(self): + c = TestClient() + conanfile = GenConanfile("pkg", "0.1").with_class_attribute("license = 'MIT'") + c.save({"conanfile.py": conanfile}) + c.run("create .") + collectlicenses = textwrap.dedent(r""" + from conan.tools.files import save + + def deploy(graph, output_folder, **kwargs): + contents = [] + conanfile = graph.root.conanfile + for pkg in graph.nodes: + d = pkg.conanfile + contents.append("LICENSE {}: {}!".format(d.ref, d.license)) + contents = "\n".join(contents) + conanfile.output.info(contents) + save(conanfile, "licenses.txt", contents) + """) + c.save({"conanfile.py": GenConanfile().with_requires("pkg/0.1") + .with_class_attribute("license='GPL'"), + "collectlicenses.py": collectlicenses}) + c.run("graph info . --deploy=collectlicenses") + assert "conanfile.py: LICENSE : GPL!" in c.out + assert "LICENSE pkg/0.1: MIT!" in c.out + contents = c.load("licenses.txt") + assert "LICENSE pkg/0.1: MIT!" in contents + assert "LICENSE : GPL!" in contents
[ { "components": [ { "doc": "", "lines": [ 90, 96 ], "name": "do_deploys", "signature": "def do_deploys(conan_api, graph, deploy, deploy_folder):", "type": "function" } ], "file": "conan/api/subapi/install.py" } ]
[ "conans/test/functional/command/test_install_deploy.py::test_copy_files_deploy", "conans/test/functional/command/test_install_deploy.py::test_multi_deploy", "conans/test/integration/command/info/info_test.py::TestDeployers::test_custom_deploy" ]
[ "conans/test/functional/command/test_install_deploy.py::test_builtin_deploy", "conans/test/functional/command/test_install_deploy.py::test_deploy_reference", "conans/test/functional/command/test_install_deploy.py::test_deploy_overwrite", "conans/test/functional/command/test_install_deploy.py::test_deploy_editable", "conans/test/functional/command/test_install_deploy.py::test_deploy_single_package", "conans/test/integration/command/info/info_test.py::TestBasicCliOutput::test_info_settings", "conans/test/integration/command/info/info_test.py::TestConanfilePath::test_cwd", "conans/test/integration/command/info/info_test.py::TestConanfilePath::test_wrong_path_parameter", "conans/test/integration/command/info/info_test.py::TestFilters::test_filter_fields", "conans/test/integration/command/info/info_test.py::TestJsonOutput::test_json_not_filtered", "conans/test/integration/command/info/info_test.py::TestJsonOutput::test_json_info_outputs", "conans/test/integration/command/info/info_test.py::TestAdvancedCliOutput::test_python_requires", "conans/test/integration/command/info/info_test.py::TestAdvancedCliOutput::test_build_id_info", "conans/test/integration/command/info/info_test.py::TestEditables::test_info_paths", "conans/test/integration/command/info/info_test.py::TestInfoRevisions::test_info_command_showing_revision", "conans/test/integration/command/info/info_test.py::TestInfoTestPackage::test_tested_reference_str" ]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> Add --deploy to graph-info How to do some quick ``graph info``, and extract custom information from the graph, in an extensible way? - Formatters at the moment are very built-in, and seems difficult to change it - ``--deploy`` only applies to ``install``, so it is necessary to install the binaries, which can be slow - There are no more global custom generators, only as ``python_requires`` - It could be possible to fork the ``graph_info`` command, but seems a bit too much to just do something equivalent to the deployers On the other hand, I don't love the ``deploy`` name, but I don't want to create yet another name for something that is mostly identical ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in conan/api/subapi/install.py] (definition of do_deploys:) def do_deploys(conan_api, graph, deploy, deploy_folder): [end of new definitions in conan/api/subapi/install.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
4a5b19a75db9225316c8cb022a2dfb9705a2af34
pvlib__pvlib-python-1562
1,562
pvlib/pvlib-python
0.8
eefc35ccecfa92b4eebd19f96f5044f79e6b0bcf
2022-09-30T00:13:00Z
diff --git a/docs/sphinx/source/reference/pv_modeling.rst b/docs/sphinx/source/reference/pv_modeling.rst index 31c380c1bb..0f33cf8c70 100644 --- a/docs/sphinx/source/reference/pv_modeling.rst +++ b/docs/sphinx/source/reference/pv_modeling.rst @@ -28,6 +28,8 @@ Incident angle modifiers iam.interp iam.marion_diffuse iam.marion_integrate + iam.schlick + iam.schlick_diffuse PV temperature models --------------------- diff --git a/docs/sphinx/source/whatsnew.rst b/docs/sphinx/source/whatsnew.rst index 4830371985..464e59f121 100644 --- a/docs/sphinx/source/whatsnew.rst +++ b/docs/sphinx/source/whatsnew.rst @@ -6,6 +6,7 @@ What's New These are new features and improvements of note in each release. +.. include:: whatsnew/v0.9.4.rst .. include:: whatsnew/v0.9.3.rst .. include:: whatsnew/v0.9.2.rst .. include:: whatsnew/v0.9.1.rst diff --git a/docs/sphinx/source/whatsnew/v0.9.4.rst b/docs/sphinx/source/whatsnew/v0.9.4.rst index 8a67c201f0..93d056e5a7 100644 --- a/docs/sphinx/source/whatsnew/v0.9.4.rst +++ b/docs/sphinx/source/whatsnew/v0.9.4.rst @@ -1,7 +1,7 @@ .. _whatsnew_0940: -v0.9.4 (TBD) ------------------------- +v0.9.4 (anticipated December 2022) +---------------------------------- Deprecations ~~~~~~~~~~~~ @@ -10,6 +10,9 @@ Deprecations Enhancements ~~~~~~~~~~~~ * Multiple code style issues fixed that were reported by LGTM analysis. (:issue:`1275`, :pull:`1559`) +* Added a direct IAM model :py:func:`pvlib.iam.schlick` which can be used with + :py:func:`~pvlib.iam.marion_diffuse`, and a diffuse IAM model + :py:func:`pvlib.iam.schlick_diffuse` (:pull:`1562`, :issue:`1564`) * Added a function to calculate one of GHI, DHI, and DNI from values of the other two. :py:func:`~pvlib.irradiance.complete_irradiance` (:issue:`1565`, :pull:`1567`) @@ -46,5 +49,9 @@ Contributors * Christian Orner (:ghuser:`chrisorner`) * Saurabh Aneja (:ghuser:`spaneja`) * Marcus Boumans (:ghuser:`bowie2211`) +* Yu Xie (:ghuser:`xieyupku`) +* Anton Driesse (:ghuser:`adriesse`) +* Cliff Hansen (:ghuser:`cwhanse`) +* Kevin Anderson (:ghuser:`kanderso-nrel`) * Karel De Brabandere (:ghuser:`kdebrab`) * Naman Priyadarshi (:ghuser:`Naman-Priyadarshi`) diff --git a/pvlib/iam.py b/pvlib/iam.py index a8592f4036..6e60b6f97d 100644 --- a/pvlib/iam.py +++ b/pvlib/iam.py @@ -541,7 +541,7 @@ def marion_diffuse(model, surface_tilt, **kwargs): ---------- model : str The IAM function to evaluate across solid angle. Must be one of - `'ashrae', 'physical', 'martin_ruiz', 'sapm'`. + `'ashrae', 'physical', 'martin_ruiz', 'sapm', 'schlick'`. surface_tilt : numeric Surface tilt angles in decimal degrees. @@ -592,6 +592,7 @@ def marion_diffuse(model, surface_tilt, **kwargs): 'ashrae': ashrae, 'sapm': sapm, 'martin_ruiz': martin_ruiz, + 'schlick': schlick, } try: @@ -748,3 +749,123 @@ def marion_integrate(function, surface_tilt, region, num=None): Fd = pd.Series(Fd, surface_tilt.index) return Fd + + +def schlick(aoi): + """ + Determine incidence angle modifier (IAM) for direct irradiance using the + Schlick approximation to the Fresnel equations. + + The Schlick approximation was proposed in [1]_ as a computationally + efficient alternative to computing the Fresnel factor in computer + graphics contexts. This implementation is a normalized form of the + equation in [1]_ so that it can be used as a PV IAM model. + Unlike other IAM models, this model has no ability to describe + different reflection profiles. + + In PV contexts, the Schlick approximation has been used as an analytically + integrable alternative to the Fresnel equations for estimating IAM + for diffuse irradiance [2]_. + + Parameters + ---------- + aoi : numeric + The angle of incidence (AOI) between the module normal vector and the + sun-beam vector. Angles of nan will result in nan. [degrees] + + Returns + ------- + iam : numeric + The incident angle modifier. + + References + ---------- + .. [1] Schlick, C. An inexpensive BRDF model for physically-based + rendering. Computer graphics forum 13 (1994). + + .. [2] Xie, Y., M. Sengupta, A. Habte, A. Andreas, "The 'Fresnel Equations' + for Diffuse radiation on Inclined photovoltaic Surfaces (FEDIS)", + Renewable and Sustainable Energy Reviews, vol. 161, 112362. June 2022. + :doi:`10.1016/j.rser.2022.112362` + + See Also + -------- + pvlib.iam.schlick_diffuse + """ + iam = 1 - (1 - cosd(aoi)) ** 5 + iam = np.where(np.abs(aoi) >= 90.0, 0.0, iam) + + # preserve input type + if np.isscalar(aoi): + iam = iam.item() + elif isinstance(aoi, pd.Series): + iam = pd.Series(iam, aoi.index) + + return iam + + +def schlick_diffuse(surface_tilt): + """ + Determine the incidence angle modifiers (IAM) for diffuse sky and + ground-reflected irradiance on a tilted surface using the Schlick + incident angle model. + + The diffuse iam values are calculated using an analytical integration + of the Schlick equation [1]_ over the portion of an isotropic sky and + isotropic foreground that is visible from the tilted surface [2]_. + + Parameters + ---------- + surface_tilt : numeric + Surface tilt angle measured from horizontal (e.g. surface facing + up = 0, surface facing horizon = 90). [degrees] + + Returns + ------- + iam_sky : numeric + The incident angle modifier for sky diffuse. + + iam_ground : numeric + The incident angle modifier for ground-reflected diffuse. + + References + ---------- + .. [1] Schlick, C. An inexpensive BRDF model for physically-based + rendering. Computer graphics forum 13 (1994). + + .. [2] Xie, Y., M. Sengupta, A. Habte, A. Andreas, "The 'Fresnel Equations' + for Diffuse radiation on Inclined photovoltaic Surfaces (FEDIS)", + Renewable and Sustainable Energy Reviews, vol. 161, 112362. June 2022. + :doi:`10.1016/j.rser.2022.112362` + + See Also + -------- + pvlib.iam.schlick + """ + # these calculations are as in [2]_, but with the refractive index + # weighting coefficient w set to 1.0 (so it is omitted) + + # relative transmittance of sky diffuse radiation by PV cover: + cosB = cosd(surface_tilt) + sinB = sind(surface_tilt) + cuk = (2 / (np.pi * (1 + cosB))) * ( + (30/7)*np.pi - (160/21)*np.radians(surface_tilt) - (10/3)*np.pi*cosB + + (160/21)*cosB*sinB - (5/3)*np.pi*cosB*sinB**2 + (20/7)*cosB*sinB**3 + - (5/16)*np.pi*cosB*sinB**4 + (16/105)*cosB*sinB**5 + ) # Eq 4 in [2] + + # relative transmittance of ground-reflected radiation by PV cover: + with np.errstate(divide='ignore', invalid='ignore'): # Eq 6 in [2] + cug = 40 / (21 * (1 - cosB)) - (1 + cosB) / (1 - cosB) * cuk + + cug = np.where(surface_tilt < 1e-6, 0, cug) + + # respect input types: + if np.isscalar(surface_tilt): + cuk = cuk.item() + cug = cug.item() + elif isinstance(surface_tilt, pd.Series): + cuk = pd.Series(cuk, surface_tilt.index) + cug = pd.Series(cug, surface_tilt.index) + + return cuk, cug
diff --git a/pvlib/tests/test_iam.py b/pvlib/tests/test_iam.py index 4310ee837a..df4d9ee877 100644 --- a/pvlib/tests/test_iam.py +++ b/pvlib/tests/test_iam.py @@ -322,3 +322,48 @@ def test_marion_integrate_invalid(): with pytest.raises(ValueError): _iam.marion_integrate(_iam.ashrae, 0, 'bad', 180) + + +def test_schlick(): + idx = pd.date_range('2019-01-01', freq='h', periods=9) + aoi = pd.Series([-180, -135, -90, -45, 0, 45, 90, 135, 180], idx) + expected = pd.Series([0, 0, 0, 0.99784451, 1.0, 0.99784451, 0, 0, 0], idx) + + # scalars + for aoi_scalar, expected_scalar in zip(aoi, expected): + actual = _iam.schlick(aoi_scalar) + assert_allclose(expected_scalar, actual) + + # numpy arrays + actual = _iam.schlick(aoi.values) + assert_allclose(expected.values, actual) + + # pandas Series + actual = _iam.schlick(aoi) + assert_series_equal(expected, actual) + + +def test_schlick_diffuse(): + surface_tilt = np.array([0, 20, 70, 90]) + # expected values calculated with marion_integrate and schlick + expected_sky = np.array([0.95238092, 0.96249934, 0.96228167, 0.95238094]) + expected_ground = np.array([0, 0.62693858, 0.93218737, 0.95238094]) + + # numpy arrays + actual_sky, actual_ground = _iam.schlick_diffuse(surface_tilt) + assert_allclose(expected_sky, actual_sky) + assert_allclose(expected_ground, actual_ground, rtol=1e-6) + + # scalars + for i in range(len(surface_tilt)): + actual_sky, actual_ground = _iam.schlick_diffuse(surface_tilt[i]) + assert_allclose(expected_sky[i], actual_sky) + assert_allclose(expected_ground[i], actual_ground, rtol=1e-6) + + # pandas Series + idx = pd.date_range('2019-01-01', freq='h', periods=len(surface_tilt)) + actual_sky, actual_ground = _iam.schlick_diffuse(pd.Series(surface_tilt, + idx)) + assert_series_equal(pd.Series(expected_sky, idx), actual_sky) + assert_series_equal(pd.Series(expected_ground, idx), actual_ground, + rtol=1e-6)
diff --git a/docs/sphinx/source/reference/pv_modeling.rst b/docs/sphinx/source/reference/pv_modeling.rst index 31c380c1bb..0f33cf8c70 100644 --- a/docs/sphinx/source/reference/pv_modeling.rst +++ b/docs/sphinx/source/reference/pv_modeling.rst @@ -28,6 +28,8 @@ Incident angle modifiers iam.interp iam.marion_diffuse iam.marion_integrate + iam.schlick + iam.schlick_diffuse PV temperature models --------------------- diff --git a/docs/sphinx/source/whatsnew.rst b/docs/sphinx/source/whatsnew.rst index 4830371985..464e59f121 100644 --- a/docs/sphinx/source/whatsnew.rst +++ b/docs/sphinx/source/whatsnew.rst @@ -6,6 +6,7 @@ What's New These are new features and improvements of note in each release. +.. include:: whatsnew/v0.9.4.rst .. include:: whatsnew/v0.9.3.rst .. include:: whatsnew/v0.9.2.rst .. include:: whatsnew/v0.9.1.rst diff --git a/docs/sphinx/source/whatsnew/v0.9.4.rst b/docs/sphinx/source/whatsnew/v0.9.4.rst index 8a67c201f0..93d056e5a7 100644 --- a/docs/sphinx/source/whatsnew/v0.9.4.rst +++ b/docs/sphinx/source/whatsnew/v0.9.4.rst @@ -1,7 +1,7 @@ .. _whatsnew_0940: -v0.9.4 (TBD) ------------------------- +v0.9.4 (anticipated December 2022) +---------------------------------- Deprecations ~~~~~~~~~~~~ @@ -10,6 +10,9 @@ Deprecations Enhancements ~~~~~~~~~~~~ * Multiple code style issues fixed that were reported by LGTM analysis. (:issue:`1275`, :pull:`1559`) +* Added a direct IAM model :py:func:`pvlib.iam.schlick` which can be used with + :py:func:`~pvlib.iam.marion_diffuse`, and a diffuse IAM model + :py:func:`pvlib.iam.schlick_diffuse` (:pull:`1562`, :issue:`1564`) * Added a function to calculate one of GHI, DHI, and DNI from values of the other two. :py:func:`~pvlib.irradiance.complete_irradiance` (:issue:`1565`, :pull:`1567`) @@ -46,5 +49,9 @@ Contributors * Christian Orner (:ghuser:`chrisorner`) * Saurabh Aneja (:ghuser:`spaneja`) * Marcus Boumans (:ghuser:`bowie2211`) +* Yu Xie (:ghuser:`xieyupku`) +* Anton Driesse (:ghuser:`adriesse`) +* Cliff Hansen (:ghuser:`cwhanse`) +* Kevin Anderson (:ghuser:`kanderso-nrel`) * Karel De Brabandere (:ghuser:`kdebrab`) * Naman Priyadarshi (:ghuser:`Naman-Priyadarshi`)
[ { "components": [ { "doc": "Determine incidence angle modifier (IAM) for direct irradiance using the\nSchlick approximation to the Fresnel equations.\n\nThe Schlick approximation was proposed in [1]_ as a computationally\nefficient alternative to computing the Fresnel factor in computer\ngraphics contexts. This implementation is a normalized form of the\nequation in [1]_ so that it can be used as a PV IAM model.\nUnlike other IAM models, this model has no ability to describe\ndifferent reflection profiles.\n\nIn PV contexts, the Schlick approximation has been used as an analytically\nintegrable alternative to the Fresnel equations for estimating IAM\nfor diffuse irradiance [2]_.\n\nParameters\n----------\naoi : numeric\n The angle of incidence (AOI) between the module normal vector and the\n sun-beam vector. Angles of nan will result in nan. [degrees]\n\nReturns\n-------\niam : numeric\n The incident angle modifier.\n\nReferences\n----------\n.. [1] Schlick, C. An inexpensive BRDF model for physically-based\n rendering. Computer graphics forum 13 (1994).\n\n.. [2] Xie, Y., M. Sengupta, A. Habte, A. Andreas, \"The 'Fresnel Equations'\n for Diffuse radiation on Inclined photovoltaic Surfaces (FEDIS)\",\n Renewable and Sustainable Energy Reviews, vol. 161, 112362. June 2022.\n :doi:`10.1016/j.rser.2022.112362`\n\nSee Also\n--------\npvlib.iam.schlick_diffuse", "lines": [ 754, 804 ], "name": "schlick", "signature": "def schlick(aoi):", "type": "function" }, { "doc": "Determine the incidence angle modifiers (IAM) for diffuse sky and\nground-reflected irradiance on a tilted surface using the Schlick\nincident angle model.\n\nThe diffuse iam values are calculated using an analytical integration\nof the Schlick equation [1]_ over the portion of an isotropic sky and\nisotropic foreground that is visible from the tilted surface [2]_.\n\nParameters\n----------\nsurface_tilt : numeric\n Surface tilt angle measured from horizontal (e.g. surface facing\n up = 0, surface facing horizon = 90). [degrees]\n\nReturns\n-------\niam_sky : numeric\n The incident angle modifier for sky diffuse.\n\niam_ground : numeric\n The incident angle modifier for ground-reflected diffuse.\n\nReferences\n----------\n.. [1] Schlick, C. An inexpensive BRDF model for physically-based\n rendering. Computer graphics forum 13 (1994).\n\n.. [2] Xie, Y., M. Sengupta, A. Habte, A. Andreas, \"The 'Fresnel Equations'\n for Diffuse radiation on Inclined photovoltaic Surfaces (FEDIS)\",\n Renewable and Sustainable Energy Reviews, vol. 161, 112362. June 2022.\n :doi:`10.1016/j.rser.2022.112362`\n\nSee Also\n--------\npvlib.iam.schlick", "lines": [ 807, 871 ], "name": "schlick_diffuse", "signature": "def schlick_diffuse(surface_tilt):", "type": "function" } ], "file": "pvlib/iam.py" } ]
[ "pvlib/tests/test_iam.py::test_schlick", "pvlib/tests/test_iam.py::test_schlick_diffuse" ]
[ "pvlib/tests/test_iam.py::test_ashrae", "pvlib/tests/test_iam.py::test_ashrae_scalar", "pvlib/tests/test_iam.py::test_physical", "pvlib/tests/test_iam.py::test_physical_scalar", "pvlib/tests/test_iam.py::test_martin_ruiz", "pvlib/tests/test_iam.py::test_martin_ruiz_exception", "pvlib/tests/test_iam.py::test_martin_ruiz_diffuse", "pvlib/tests/test_iam.py::test_iam_interp", "pvlib/tests/test_iam.py::test_sapm[45-0.9975036250000002]", "pvlib/tests/test_iam.py::test_sapm[aoi1-expected1]", "pvlib/tests/test_iam.py::test_sapm[aoi2-expected2]", "pvlib/tests/test_iam.py::test_sapm_limits", "pvlib/tests/test_iam.py::test_marion_diffuse_model", "pvlib/tests/test_iam.py::test_marion_diffuse_kwargs", "pvlib/tests/test_iam.py::test_marion_diffuse_invalid", "pvlib/tests/test_iam.py::test_marion_integrate_scalar[sky-180-0.9596085829811408]", "pvlib/tests/test_iam.py::test_marion_integrate_scalar[horizon-1800-0.8329070417832541]", "pvlib/tests/test_iam.py::test_marion_integrate_scalar[ground-180-0.719823559106309]", "pvlib/tests/test_iam.py::test_marion_integrate_list[sky-180-expected0]", "pvlib/tests/test_iam.py::test_marion_integrate_list[horizon-1800-expected1]", "pvlib/tests/test_iam.py::test_marion_integrate_list[ground-180-expected2]", "pvlib/tests/test_iam.py::test_marion_integrate_series[sky-180-expected0]", "pvlib/tests/test_iam.py::test_marion_integrate_series[horizon-1800-expected1]", "pvlib/tests/test_iam.py::test_marion_integrate_series[ground-180-expected2]", "pvlib/tests/test_iam.py::test_marion_integrate_ground_flat", "pvlib/tests/test_iam.py::test_marion_integrate_invalid" ]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> Implement iam.schlick, iam.schlick_diffuse - [x] Closes #1564 - [x] I am familiar with the [contributing guidelines](https://pvlib-python.readthedocs.io/en/latest/contributing.html) - [x] Tests added - [x] Updates entries in [`docs/sphinx/source/reference`](https://github.com/pvlib/pvlib-python/blob/master/docs/sphinx/source/reference) for API changes. - [x] Adds description and name entries in the appropriate "what's new" file in [`docs/sphinx/source/whatsnew`](https://github.com/pvlib/pvlib-python/tree/master/docs/sphinx/source/whatsnew) for all changes. Includes link to the GitHub Issue with `` :issue:`num` `` or this Pull Request with `` :pull:`num` ``. Includes contributor name and/or GitHub username (link with `` :ghuser:`user` ``). - [x] New code is fully documented. Includes [numpydoc](https://numpydoc.readthedocs.io/en/latest/format.html) compliant docstrings, examples, and comments where necessary. - [x] Pull request is nearly complete and ready for detailed review. - [x] Maintainer: Appropriate GitHub Labels (including `remote-data`) and Milestone are assigned to the Pull Request and linked Issue. Yu Xie from NREL presented a new IAM model at the recent PVPMC meeting ([slides](https://pvpmc.sandia.gov/download/8412/)) and wanted to contribute it to pvlib. This one is a little unusual in that it calculates the IAM factor as a relative quantity, taking the indices of refraction of both the PV surface and the accompanying pyranometer into account. ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in pvlib/iam.py] (definition of schlick:) def schlick(aoi): """Determine incidence angle modifier (IAM) for direct irradiance using the Schlick approximation to the Fresnel equations. The Schlick approximation was proposed in [1]_ as a computationally efficient alternative to computing the Fresnel factor in computer graphics contexts. This implementation is a normalized form of the equation in [1]_ so that it can be used as a PV IAM model. Unlike other IAM models, this model has no ability to describe different reflection profiles. In PV contexts, the Schlick approximation has been used as an analytically integrable alternative to the Fresnel equations for estimating IAM for diffuse irradiance [2]_. Parameters ---------- aoi : numeric The angle of incidence (AOI) between the module normal vector and the sun-beam vector. Angles of nan will result in nan. [degrees] Returns ------- iam : numeric The incident angle modifier. References ---------- .. [1] Schlick, C. An inexpensive BRDF model for physically-based rendering. Computer graphics forum 13 (1994). .. [2] Xie, Y., M. Sengupta, A. Habte, A. Andreas, "The 'Fresnel Equations' for Diffuse radiation on Inclined photovoltaic Surfaces (FEDIS)", Renewable and Sustainable Energy Reviews, vol. 161, 112362. June 2022. :doi:`10.1016/j.rser.2022.112362` See Also -------- pvlib.iam.schlick_diffuse""" (definition of schlick_diffuse:) def schlick_diffuse(surface_tilt): """Determine the incidence angle modifiers (IAM) for diffuse sky and ground-reflected irradiance on a tilted surface using the Schlick incident angle model. The diffuse iam values are calculated using an analytical integration of the Schlick equation [1]_ over the portion of an isotropic sky and isotropic foreground that is visible from the tilted surface [2]_. Parameters ---------- surface_tilt : numeric Surface tilt angle measured from horizontal (e.g. surface facing up = 0, surface facing horizon = 90). [degrees] Returns ------- iam_sky : numeric The incident angle modifier for sky diffuse. iam_ground : numeric The incident angle modifier for ground-reflected diffuse. References ---------- .. [1] Schlick, C. An inexpensive BRDF model for physically-based rendering. Computer graphics forum 13 (1994). .. [2] Xie, Y., M. Sengupta, A. Habte, A. Andreas, "The 'Fresnel Equations' for Diffuse radiation on Inclined photovoltaic Surfaces (FEDIS)", Renewable and Sustainable Energy Reviews, vol. 161, 112362. June 2022. :doi:`10.1016/j.rser.2022.112362` See Also -------- pvlib.iam.schlick""" [end of new definitions in pvlib/iam.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
Here is the discussion in the issues of the pull request. <issues> Add iam function based on Schlick 1994 **Is your feature request related to a problem? Please describe.** Equation 15 in Schlick 1994 gives an efficient approximation equation for surface reflectance as a function of incidence angle that could be used as the basis for an *iam* function. Equation 4 in Xie 2022 gives an analytical integration of the Schlick equation over the portion of an isotropic sky that is visible from a tilted surface. Equation 6 in Xie 2022 gives an analytical integration of the Schlick equation over the portion of an isotropic ground that is visible from a tilted surface. **Describe the solution you'd like** A new function called ```schlick``` in the ```iam``` module. The equation would be: ``` iam = 1 - (1 - cos(aoi)) ** 5 ``` This equation has no parameters for fitting to iam measurements or to represent different types of PV module glass. A second new function called ```schlick_diffuse``` in the ```iam``` module (similar to the function ```martin_ruiz_diffuse```) which implements Equations 4 and 6 from Xie 2022 (excluding the empirical weighting factor *w*, or in other words, with *w=1*). **References** Schlick, C. An inexpensive BRDF model for physically-based rendering. Computer graphics forum 13 (1994). Xie, Y. et al. The 'Fresnel Equations' for Diffuse radiation on Inclined photovoltaic Surfaces (FEDIS). J.RSER (2022) ---------- -------------------- </issues>
311781d2380997044da0e484dc90aa146a74ca44
sympy__sympy-24070
24,070
sympy/sympy
1.12
007d962672034698a5d152de9086e63c3becfa74
2022-09-19T22:37:41Z
diff --git a/.mailmap b/.mailmap index 6f0e24a24cb0..6b04fe9fdadb 100644 --- a/.mailmap +++ b/.mailmap @@ -1017,6 +1017,7 @@ Peter Enenkel <peter.enenkel+git@gmail.com> <peter.enenkel+github@gmail.com> Peter Schmidt <peter@peterjs.com> Peter Stangl <peter.stangl@ph.tum.de> Petr Kungurtsev <corwinat@gmail.com> Corwinpro <corwinat@gmail.com> +Phil LeMaitre <phil_lemaitre@live.ca> <112662371+AntiPhoton47@users.noreply.github.com> Phil Ruffwind <rf@rufflewind.com> Philippe Bouafia <philippe.bouafia@ensea.fr> Phillip Berndt <phillip.berndt@googlemail.com> diff --git a/sympy/physics/wigner.py b/sympy/physics/wigner.py index edf71a530c48..ef404b98acee 100644 --- a/sympy/physics/wigner.py +++ b/sympy/physics/wigner.py @@ -26,6 +26,10 @@ .. [Liberatodebrito82] 'FORTRAN program for the integral of three spherical harmonics', A. Liberato de Brito, Comput. Phys. Commun., Volume 25, pp. 81-85 (1982) +.. [Homeier96] 'Some Properties of the Coupling Coefficients of Real + Spherical Harmonics and Their Relation to Gaunt Coefficients', + H. H. H. Homeier and E. O. Steinborn J. Mol. Struct., Volume 368, + pp. 31-37 (1996) Credits and Copyright ===================== @@ -43,6 +47,8 @@ - Oscar Gerardo Lazo Arjona (2017-06-18): added Wigner D matrices +- Phil Adam LeMaitre (2022-09-19): added real Gaunt coefficient + Copyright (C) 2008 Jens Rasch <jyr2000@gmail.com> """ @@ -54,12 +60,14 @@ from sympy.core.symbol import Dummy from sympy.core.sympify import sympify from sympy.functions.combinatorial.factorials import (binomial, factorial) +from sympy.functions.elementary.complexes import re from sympy.functions.elementary.exponential import exp from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (cos, sin) from sympy.functions.special.spherical_harmonics import Ynm from sympy.matrices.dense import zeros from sympy.matrices.immutable import ImmutableMatrix +from sympy.utilities.misc import as_int # This list of precomputed factorials is needed to massively # accelerate future calculations of the various coefficients @@ -699,40 +707,32 @@ def gaunt(l_1, l_2, l_3, m_1, m_2, m_3, prec=None): Jens Rasch (2009-03-24): initial version for Sage. """ - if int(l_1) != l_1 or int(l_2) != l_2 or int(l_3) != l_3: - raise ValueError("l values must be integer") - if int(m_1) != m_1 or int(m_2) != m_2 or int(m_3) != m_3: - raise ValueError("m values must be integer") - - sumL = l_1 + l_2 + l_3 - bigL = sumL // 2 - a1 = l_1 + l_2 - l_3 - if a1 < 0: - return S.Zero - a2 = l_1 - l_2 + l_3 - if a2 < 0: + l_1, l_2, l_3, m_1, m_2, m_3 = [ + as_int(i) for i in (l_1, l_2, l_3, m_1, m_2, m_3)] + + if l_1 + l_2 - l_3 < 0: return S.Zero - a3 = -l_1 + l_2 + l_3 - if a3 < 0: + if l_1 - l_2 + l_3 < 0: return S.Zero - if sumL % 2: + if -l_1 + l_2 + l_3 < 0: return S.Zero if (m_1 + m_2 + m_3) != 0: return S.Zero if (abs(m_1) > l_1) or (abs(m_2) > l_2) or (abs(m_3) > l_3): return S.Zero + bigL, remL = divmod(l_1 + l_2 + l_3, 2) + if remL % 2: + return S.Zero imin = max(-l_3 + l_1 + m_2, -l_3 + l_2 - m_1, 0) imax = min(l_2 + m_2, l_1 - m_1, l_1 + l_2 - l_3) - maxfact = max(l_1 + l_2 + l_3 + 1, imax + 1) - _calc_factlist(maxfact) + _calc_factlist(max(l_1 + l_2 + l_3 + 1, imax + 1)) - argsqrt = (2 * l_1 + 1) * (2 * l_2 + 1) * (2 * l_3 + 1) * \ + ressqrt = sqrt((2 * l_1 + 1) * (2 * l_2 + 1) * (2 * l_3 + 1) * \ _Factlist[l_1 - m_1] * _Factlist[l_1 + m_1] * _Factlist[l_2 - m_2] * \ _Factlist[l_2 + m_2] * _Factlist[l_3 - m_3] * _Factlist[l_3 + m_3] / \ - (4*pi) - ressqrt = sqrt(argsqrt) + (4*pi)) prefac = Integer(_Factlist[bigL] * _Factlist[l_2 - l_1 + l_3] * _Factlist[l_1 - l_2 + l_3] * _Factlist[l_1 + l_2 - l_3])/ \ @@ -753,6 +753,160 @@ def gaunt(l_1, l_2, l_3, m_1, m_2, m_3, prec=None): return res +def real_gaunt(l_1, l_2, l_3, m_1, m_2, m_3, prec=None): + r""" + Calculate the real Gaunt coefficient. + + Explanation + =========== + + The real Gaunt coefficient is defined as the integral over three + real spherical harmonics: + + .. math:: + \begin{aligned} + \operatorname{RealGaunt}(l_1,l_2,l_3,m_1,m_2,m_3) + &=\int Z^{m_1}_{l_1}(\Omega) + Z^{m_2}_{l_2}(\Omega) Z^{m_3}_{l_3}(\Omega) \,d\Omega \\ + \end{aligned} + + Alternatively, it can be defined in terms of the standard Gaunt + coefficient by relating the real spherical harmonics to the standard + spherical harmonics via a unitary transformation `U`, i.e. + `Z^{m}_{l}(\Omega)=\sum_{m'}U^{m}_{m'}Y^{m'}_{l}(\Omega)` [Homeier96]_. + The real Gaunt coefficient is then defined as + + .. math:: + \begin{aligned} + \operatorname{RealGaunt}(l_1,l_2,l_3,m_1,m_2,m_3) + &=\int Z^{m_1}_{l_1}(\Omega) + Z^{m_2}_{l_2}(\Omega) Z^{m_3}_{l_3}(\Omega) \,d\Omega \\ + &=\sum_{m'_1 m'_2 m'_3} U^{m_1}_{m'_1}U^{m_2}_{m'_2}U^{m_3}_{m'_3} + \operatorname{Gaunt}(l_1,l_2,l_3,m'_1,m'_2,m'_3) + \end{aligned} + + The unitary matrix `U` has components + + .. math:: + \begin{aligned} + U^m_{m'} = \delta_{|m||m'|}*(\delta_{m'0}\delta_{m0} + \frac{1}{\sqrt{2}}\big[\Theta(m) + \big(\delta_{m'm}+(-1)^{m'}\delta_{m'-m}\big)+i\Theta(-m)\big((-1)^{-m} + \delta_{m'-m}-\delta_{m'm}*(-1)^{m'-m}\big)\big]) + \end{aligned} + + where `\delta_{ij}` is the Kronecker delta symbol and `\Theta` is a step + function defined as + + .. math:: + \begin{aligned} + \Theta(x) = \begin{cases} 1 \,\text{for}\, x > 0 \\ 0 \,\text{for}\, x \leq 0 \end{cases} + \end{aligned} + + Parameters + ========== + + l_1, l_2, l_3, m_1, m_2, m_3 : + Integer. + + prec - precision, default: ``None``. + Providing a precision can + drastically speed up the calculation. + + Returns + ======= + + Rational number times the square root of a rational number. + + Examples + ======== + + >>> from sympy.physics.wigner import real_gaunt + >>> real_gaunt(2,2,4,-1,-1,0) + -2/(7*sqrt(pi)) + >>> real_gaunt(10,10,20,-9,-9,0).n(64) + -0.00002480019791932209313156167... + + It is an error to use non-integer values for `l` and `m`:: + real_gaunt(2.8,0.5,1.3,0,0,0) + Traceback (most recent call last): + ... + ValueError: l values must be integer + real_gaunt(2,2,4,0.7,1,-3.4) + Traceback (most recent call last): + ... + ValueError: m values must be integer + + Notes + ===== + + The real Gaunt coefficient inherits from the standard Gaunt coefficient, + the invariance under any permutation of the pairs `(l_i, m_i)` and the + requirement that the sum of the `l_i` be even to yield a non-zero value. + It also obeys the following symmetry rules: + + - zero for `l_1`, `l_2`, `l_3` not fulfiling the condition + `l_1 \in \{l_{\text{max}}, l_{\text{max}}-2, \ldots, l_{\text{min}}\}`, + where `l_{\text{max}} = l_2+l_3`, + + .. math:: + \begin{aligned} + l_{\text{min}} = \begin{cases} \kappa(l_2, l_3, m_2, m_3) & \text{if}\, + \kappa(l_2, l_3, m_2, m_3) + l_{\text{max}}\, \text{is even} \\ + \kappa(l_2, l_3, m_2, m_3)+1 & \text{if}\, \kappa(l_2, l_3, m_2, m_3) + + l_{\text{max}}\, \text{is odd}\end{cases} + \end{aligned} + + and `\kappa(l_2, l_3, m_2, m_3) = \max{\big(|l_2-l_3|, \min{\big(|m_2+m_3|, + |m_2-m_3|\big)}\big)}` + + - zero for an odd number of negative `m_i` + + Algorithms + ========== + + This function uses the algorithms of [Homeier96]_ and [Rasch03]_ to + calculate the value of the real Gaunt coefficient exactly. Note that + the formula used in [Rasch03]_ contains alternating sums over large + factorials and is therefore unsuitable for finite precision arithmetic + and only useful for a computer algebra system [Rasch03]_. However, this + function can in principle use any algorithm that computes the Gaunt + coefficient, so it is suitable for finite precision arithmetic in so far + as the algorithm which computes the Gaunt coefficient is. + """ + l_1, l_2, l_3, m_1, m_2, m_3 = [ + as_int(i) for i in (l_1, l_2, l_3, m_1, m_2, m_3)] + + # check for quick exits + if sum(1 for i in (m_1, m_2, m_3) if i < 0) % 2: + return S.Zero # odd number of negative m + if (l_1 + l_2 + l_3) % 2: + return S.Zero # sum of l is odd + lmax = l_2 + l_3 + lmin = max(abs(l_2 - l_3), min(abs(m_2 + m_3), abs(m_2 - m_3))) + if (lmin + lmax) % 2: + lmin += 1 + if lmin not in range(lmax, lmin - 2, -2): + return S.Zero + + kron_del = lambda i, j: 1 if i == j else 0 + s = lambda e: -1 if e % 2 else 1 # (-1)**e to give +/-1, avoiding float when e<0 + A = lambda a, b: (-kron_del(a, b)*s(a-b) + kron_del(a, -b)* + s(b)) if b < 0 else 0 + B = lambda a, b: (kron_del(a, b) + kron_del(a, -b)*s(a)) if b > 0 else 0 + C = lambda a, b: kron_del(abs(a), abs(b))*(kron_del(a, 0)*kron_del(b, 0) + + (B(a, b) + I*A(a, b))/sqrt(2)) + ugnt = 0 + for i in range(-l_1, l_1+1): + U1 = C(i, m_1) + for j in range(-l_2, l_2+1): + U2 = C(j, m_2) + U3 = C(-i-j, m_3) + ugnt = ugnt + re(U1*U2*U3)*gaunt(l_1, l_2, l_3, i, j, -i-j) + + if prec is not None: + ugnt = ugnt.n(prec) + return ugnt + class Wigner3j(Function):
diff --git a/sympy/physics/tests/test_clebsch_gordan.py b/sympy/physics/tests/test_clebsch_gordan.py index 2e77bf2f7afd..d6a41f1b6b4f 100644 --- a/sympy/physics/tests/test_clebsch_gordan.py +++ b/sympy/physics/tests/test_clebsch_gordan.py @@ -1,4 +1,4 @@ -from sympy.core.numbers import (I, pi) +from sympy.core.numbers import (I, pi, Rational) from sympy.core.singleton import S from sympy.core.symbol import symbols from sympy.functions.elementary.exponential import exp @@ -7,8 +7,8 @@ from sympy.functions.special.spherical_harmonics import Ynm from sympy.matrices.dense import Matrix from sympy.physics.wigner import (clebsch_gordan, wigner_9j, wigner_6j, gaunt, - racah, dot_rot_grad_Ynm, wigner_3j, wigner_d_small, wigner_d) -from sympy.core.numbers import Rational + real_gaunt, racah, dot_rot_grad_Ynm, wigner_3j, wigner_d_small, wigner_d) +from sympy.testing.pytest import raises # for test cases, refer : https://en.wikipedia.org/wiki/Table_of_Clebsch%E2%80%93Gordan_coefficients @@ -18,223 +18,41 @@ def test_clebsch_gordan_docs(): assert clebsch_gordan(Rational(3, 2), S.Half, 1, Rational(-1, 2), S.Half, 0) == -sqrt(2)/2 -def test_clebsch_gordan1(): - j_1 = S.Half - j_2 = S.Half - m = 1 - j = 1 - m_1 = S.Half - m_2 = S.Half - assert clebsch_gordan(j_1, j_2, j, m_1, m_2, m) == 1 - - j_1 = S.Half - j_2 = S.Half - m = -1 - j = 1 - m_1 = Rational(-1, 2) - m_2 = Rational(-1, 2) - assert clebsch_gordan(j_1, j_2, j, m_1, m_2, m) == 1 - - j_1 = S.Half - j_2 = S.Half - m = 0 - j = 1 - m_1 = S.Half - m_2 = S.Half - assert clebsch_gordan(j_1, j_2, j, m_1, m_2, m) == 0 - - j_1 = S.Half - j_2 = S.Half - m = 0 - j = 1 - m_1 = S.Half - m_2 = Rational(-1, 2) - assert clebsch_gordan(j_1, j_2, j, m_1, m_2, m) == sqrt(2)/2 - - j_1 = S.Half - j_2 = S.Half - m = 0 - j = 0 - m_1 = S.Half - m_2 = Rational(-1, 2) - assert clebsch_gordan(j_1, j_2, j, m_1, m_2, m) == sqrt(2)/2 - - j_1 = S.Half - j_2 = S.Half - m = 0 - j = 1 - m_1 = Rational(-1, 2) - m_2 = S.Half - assert clebsch_gordan(j_1, j_2, j, m_1, m_2, m) == sqrt(2)/2 - - j_1 = S.Half - j_2 = S.Half - m = 0 - j = 0 - m_1 = Rational(-1, 2) - m_2 = S.Half - assert clebsch_gordan(j_1, j_2, j, m_1, m_2, m) == -sqrt(2)/2 - -def test_clebsch_gordan2(): - j_1 = S.One - j_2 = S.Half - m = Rational(3, 2) - j = Rational(3, 2) - m_1 = 1 - m_2 = S.Half - assert clebsch_gordan(j_1, j_2, j, m_1, m_2, m) == 1 - - j_1 = S.One - j_2 = S.Half - m = S.Half - j = Rational(3, 2) - m_1 = 1 - m_2 = Rational(-1, 2) - assert clebsch_gordan(j_1, j_2, j, m_1, m_2, m) == 1/sqrt(3) - - j_1 = S.One - j_2 = S.Half - m = S.Half - j = S.Half - m_1 = 1 - m_2 = Rational(-1, 2) - assert clebsch_gordan(j_1, j_2, j, m_1, m_2, m) == sqrt(2)/sqrt(3) - - j_1 = S.One - j_2 = S.Half - m = S.Half - j = S.Half - m_1 = 0 - m_2 = S.Half - assert clebsch_gordan(j_1, j_2, j, m_1, m_2, m) == -1/sqrt(3) - - j_1 = S.One - j_2 = S.Half - m = S.Half - j = Rational(3, 2) - m_1 = 0 - m_2 = S.Half - assert clebsch_gordan(j_1, j_2, j, m_1, m_2, m) == sqrt(2)/sqrt(3) - - j_1 = S.One - j_2 = S.One - m = S(2) - j = S(2) - m_1 = 1 - m_2 = 1 - assert clebsch_gordan(j_1, j_2, j, m_1, m_2, m) == 1 - - - j_1 = S.One - j_2 = S.One - m = 1 - j = S(2) - m_1 = 1 - m_2 = 0 - assert clebsch_gordan(j_1, j_2, j, m_1, m_2, m) == 1/sqrt(2) - - - j_1 = S.One - j_2 = S.One - m = 1 - j = S(2) - m_1 = 0 - m_2 = 1 - assert clebsch_gordan(j_1, j_2, j, m_1, m_2, m) == 1/sqrt(2) - - j_1 = S.One - j_2 = S.One - m = 1 - j = 1 - m_1 = 1 - m_2 = 0 - assert clebsch_gordan(j_1, j_2, j, m_1, m_2, m) == 1/sqrt(2) - - j_1 = S.One - j_2 = S.One - m = 1 - j = 1 - m_1 = 0 - m_2 = 1 - assert clebsch_gordan(j_1, j_2, j, m_1, m_2, m) == -1/sqrt(2) - -def test_clebsch_gordan3(): - j_1 = Rational(3, 2) - j_2 = Rational(3, 2) - m = S(3) - j = S(3) - m_1 = Rational(3, 2) - m_2 = Rational(3, 2) - assert clebsch_gordan(j_1, j_2, j, m_1, m_2, m) == 1 - - - j_1 = Rational(3, 2) - j_2 = Rational(3, 2) - m = S(2) - j = S(2) - m_1 = Rational(3, 2) - m_2 = S.Half - assert clebsch_gordan(j_1, j_2, j, m_1, m_2, m) == 1/sqrt(2) - - j_1 = Rational(3, 2) - j_2 = Rational(3, 2) - m = S(2) - j = S(3) - m_1 = Rational(3, 2) - m_2 = S.Half - assert clebsch_gordan(j_1, j_2, j, m_1, m_2, m) == 1/sqrt(2) - -def test_clebsch_gordan4(): - j_1 = S(2) - j_2 = S(2) - m = S(4) - j = S(4) - m_1 = S(2) - m_2 = S(2) - assert clebsch_gordan(j_1, j_2, j, m_1, m_2, m) == 1 - - - j_1 = S(2) - j_2 = S(2) - m = S(3) - j = S(3) - m_1 = S(2) - m_2 = 1 - assert clebsch_gordan(j_1, j_2, j, m_1, m_2, m) == 1/sqrt(2) - - j_1 = S(2) - j_2 = S(2) - m = S(2) - j = S(3) - m_1 = 1 - m_2 = 1 - assert clebsch_gordan(j_1, j_2, j, m_1, m_2, m) == 0 - -def test_clebsch_gordan5(): - j_1 = Rational(5, 2) - j_2 = S.One - m = Rational(7, 2) - j = Rational(7, 2) - m_1 = Rational(5, 2) - m_2 = 1 - assert clebsch_gordan(j_1, j_2, j, m_1, m_2, m) == 1 - - - j_1 = Rational(5, 2) - j_2 = S.One - m = Rational(5, 2) - j = Rational(5, 2) - m_1 = Rational(5, 2) - m_2 = 0 - assert clebsch_gordan(j_1, j_2, j, m_1, m_2, m) == sqrt(5)/sqrt(7) - - j_1 = Rational(5, 2) - j_2 = S.One - m = Rational(3, 2) - j = Rational(3, 2) - m_1 = S.Half - m_2 = 1 - assert clebsch_gordan(j_1, j_2, j, m_1, m_2, m) == 1/sqrt(15) +def test_clebsch_gordan(): + # Argument order: (j_1, j_2, j, m_1, m_2, m) + + h = S.One + k = S.Half + l = Rational(3, 2) + i = Rational(-1, 2) + n = Rational(7, 2) + p = Rational(5, 2) + assert clebsch_gordan(k, k, 1, k, k, 1) == 1 + assert clebsch_gordan(k, k, 1, k, k, 0) == 0 + assert clebsch_gordan(k, k, 1, i, i, -1) == 1 + assert clebsch_gordan(k, k, 1, k, i, 0) == sqrt(2)/2 + assert clebsch_gordan(k, k, 0, k, i, 0) == sqrt(2)/2 + assert clebsch_gordan(k, k, 1, i, k, 0) == sqrt(2)/2 + assert clebsch_gordan(k, k, 0, i, k, 0) == -sqrt(2)/2 + assert clebsch_gordan(h, k, l, 1, k, l) == 1 + assert clebsch_gordan(h, k, l, 1, i, k) == 1/sqrt(3) + assert clebsch_gordan(h, k, k, 1, i, k) == sqrt(2)/sqrt(3) + assert clebsch_gordan(h, k, k, 0, k, k) == -1/sqrt(3) + assert clebsch_gordan(h, k, l, 0, k, k) == sqrt(2)/sqrt(3) + assert clebsch_gordan(h, h, S(2), 1, 1, S(2)) == 1 + assert clebsch_gordan(h, h, S(2), 1, 0, 1) == 1/sqrt(2) + assert clebsch_gordan(h, h, S(2), 0, 1, 1) == 1/sqrt(2) + assert clebsch_gordan(h, h, 1, 1, 0, 1) == 1/sqrt(2) + assert clebsch_gordan(h, h, 1, 0, 1, 1) == -1/sqrt(2) + assert clebsch_gordan(l, l, S(3), l, l, S(3)) == 1 + assert clebsch_gordan(l, l, S(2), l, k, S(2)) == 1/sqrt(2) + assert clebsch_gordan(l, l, S(3), l, k, S(2)) == 1/sqrt(2) + assert clebsch_gordan(S(2), S(2), S(4), S(2), S(2), S(4)) == 1 + assert clebsch_gordan(S(2), S(2), S(3), S(2), 1, S(3)) == 1/sqrt(2) + assert clebsch_gordan(S(2), S(2), S(3), 1, 1, S(2)) == 0 + assert clebsch_gordan(p, h, n, p, 1, n) == 1 + assert clebsch_gordan(p, h, p, p, 0, p) == sqrt(5)/sqrt(7) + assert clebsch_gordan(p, h, l, k, 1, l) == 1/sqrt(15) def test_wigner(): @@ -294,6 +112,40 @@ def gaunt_ref(l1, l2, l3, m1, m2, m3): assert abs(g) < threshold if (l1 + l2 + l3) % 2: assert abs(g) < threshold + assert gaunt(1, 1, 0, 0, 2, -2) is S.Zero + + +def test_realgaunt(): + # All non-zero values corresponding to l values from 0 to 2 + for l in range(3): + for m in range(-l, l+1): + assert real_gaunt(0, l, l, 0, m, m) == 1/(2*sqrt(pi)) + assert real_gaunt(1, 1, 2, 0, 0, 0) == sqrt(5)/(5*sqrt(pi)) + assert real_gaunt(1, 1, 2, 1, 1, 0) == -sqrt(5)/(10*sqrt(pi)) + assert real_gaunt(2, 2, 2, 0, 0, 0) == sqrt(5)/(7*sqrt(pi)) + assert real_gaunt(2, 2, 2, 0, 2, 2) == -sqrt(5)/(7*sqrt(pi)) + assert real_gaunt(2, 2, 2, -2, -2, 0) == -sqrt(5)/(7*sqrt(pi)) + assert real_gaunt(1, 1, 2, -1, 0, -1) == sqrt(15)/(10*sqrt(pi)) + assert real_gaunt(1, 1, 2, 0, 1, 1) == sqrt(15)/(10*sqrt(pi)) + assert real_gaunt(1, 1, 2, 1, 1, 2) == sqrt(15)/(10*sqrt(pi)) + assert real_gaunt(1, 1, 2, -1, 1, -2) == -sqrt(15)/(10*sqrt(pi)) + assert real_gaunt(1, 1, 2, -1, -1, 2) == -sqrt(15)/(10*sqrt(pi)) + assert real_gaunt(2, 2, 2, 0, 1, 1) == sqrt(5)/(14*sqrt(pi)) + assert real_gaunt(2, 2, 2, 1, 1, 2) == sqrt(15)/(14*sqrt(pi)) + assert real_gaunt(2, 2, 2, -1, -1, 2) == -sqrt(15)/(14*sqrt(pi)) + + assert real_gaunt(-2, -2, -2, -2, -2, 0) is S.Zero # m test + assert real_gaunt(-2, 1, 0, 1, 1, 1) is S.Zero # l test + assert real_gaunt(-2, -1, -2, -1, -1, 0) is S.Zero # m and l test + assert real_gaunt(-2, -2, -2, -2, -2, -2) is S.Zero # m and k test + assert real_gaunt(-2, -1, -2, -1, -1, -1) is S.Zero # m, l and k test + + x = symbols('x', integer=True) + v = [0]*6 + for i in range(len(v)): + v[i] = x # non literal ints fail + raises(ValueError, lambda: real_gaunt(*v)) + v[i] = 0 def test_racah():
diff --git a/.mailmap b/.mailmap index 6f0e24a24cb0..6b04fe9fdadb 100644 --- a/.mailmap +++ b/.mailmap @@ -1017,6 +1017,7 @@ Peter Enenkel <peter.enenkel+git@gmail.com> <peter.enenkel+github@gmail.com> Peter Schmidt <peter@peterjs.com> Peter Stangl <peter.stangl@ph.tum.de> Petr Kungurtsev <corwinat@gmail.com> Corwinpro <corwinat@gmail.com> +Phil LeMaitre <phil_lemaitre@live.ca> <112662371+AntiPhoton47@users.noreply.github.com> Phil Ruffwind <rf@rufflewind.com> Philippe Bouafia <philippe.bouafia@ensea.fr> Phillip Berndt <phillip.berndt@googlemail.com>
[ { "components": [ { "doc": "Calculate the real Gaunt coefficient.\n\nExplanation\n===========\n\nThe real Gaunt coefficient is defined as the integral over three\nreal spherical harmonics:\n\n.. math::\n \\begin{aligned}\n \\operatorname{RealGaunt}(l_1,l_2,l_3,m_1,m_2,m_3)\n &=\\int Z^{m_1}_{l_1}(\\Omega)\n Z^{m_2}_{l_2}(\\Omega) Z^{m_3}_{l_3}(\\Omega) \\,d\\Omega \\\\\n \\end{aligned}\n\nAlternatively, it can be defined in terms of the standard Gaunt\ncoefficient by relating the real spherical harmonics to the standard\nspherical harmonics via a unitary transformation `U`, i.e.\n`Z^{m}_{l}(\\Omega)=\\sum_{m'}U^{m}_{m'}Y^{m'}_{l}(\\Omega)` [Homeier96]_.\nThe real Gaunt coefficient is then defined as\n\n.. math::\n \\begin{aligned}\n \\operatorname{RealGaunt}(l_1,l_2,l_3,m_1,m_2,m_3)\n &=\\int Z^{m_1}_{l_1}(\\Omega)\n Z^{m_2}_{l_2}(\\Omega) Z^{m_3}_{l_3}(\\Omega) \\,d\\Omega \\\\\n &=\\sum_{m'_1 m'_2 m'_3} U^{m_1}_{m'_1}U^{m_2}_{m'_2}U^{m_3}_{m'_3}\n \\operatorname{Gaunt}(l_1,l_2,l_3,m'_1,m'_2,m'_3)\n \\end{aligned}\n\nThe unitary matrix `U` has components\n\n.. math::\n \\begin{aligned}\n U^m_{m'} = \\delta_{|m||m'|}*(\\delta_{m'0}\\delta_{m0} + \\frac{1}{\\sqrt{2}}\\big[\\Theta(m)\n \\big(\\delta_{m'm}+(-1)^{m'}\\delta_{m'-m}\\big)+i\\Theta(-m)\\big((-1)^{-m}\n \\delta_{m'-m}-\\delta_{m'm}*(-1)^{m'-m}\\big)\\big])\n \\end{aligned}\n\nwhere `\\delta_{ij}` is the Kronecker delta symbol and `\\Theta` is a step\nfunction defined as\n\n.. math::\n \\begin{aligned}\n \\Theta(x) = \\begin{cases} 1 \\,\\text{for}\\, x > 0 \\\\ 0 \\,\\text{for}\\, x \\leq 0 \\end{cases}\n \\end{aligned}\n\nParameters\n==========\n\nl_1, l_2, l_3, m_1, m_2, m_3 :\n Integer.\n\nprec - precision, default: ``None``.\n Providing a precision can\n drastically speed up the calculation.\n\nReturns\n=======\n\nRational number times the square root of a rational number.\n\nExamples\n========\n\n>>> from sympy.physics.wigner import real_gaunt\n>>> real_gaunt(2,2,4,-1,-1,0)\n-2/(7*sqrt(pi))\n>>> real_gaunt(10,10,20,-9,-9,0).n(64)\n-0.00002480019791932209313156167...\n\nIt is an error to use non-integer values for `l` and `m`::\n real_gaunt(2.8,0.5,1.3,0,0,0)\n Traceback (most recent call last):\n ...\n ValueError: l values must be integer\n real_gaunt(2,2,4,0.7,1,-3.4)\n Traceback (most recent call last):\n ...\n ValueError: m values must be integer\n\nNotes\n=====\n\nThe real Gaunt coefficient inherits from the standard Gaunt coefficient,\nthe invariance under any permutation of the pairs `(l_i, m_i)` and the\nrequirement that the sum of the `l_i` be even to yield a non-zero value.\nIt also obeys the following symmetry rules:\n\n- zero for `l_1`, `l_2`, `l_3` not fulfiling the condition\n `l_1 \\in \\{l_{\\text{max}}, l_{\\text{max}}-2, \\ldots, l_{\\text{min}}\\}`,\n where `l_{\\text{max}} = l_2+l_3`,\n\n .. math::\n \\begin{aligned}\n l_{\\text{min}} = \\begin{cases} \\kappa(l_2, l_3, m_2, m_3) & \\text{if}\\,\n \\kappa(l_2, l_3, m_2, m_3) + l_{\\text{max}}\\, \\text{is even} \\\\\n \\kappa(l_2, l_3, m_2, m_3)+1 & \\text{if}\\, \\kappa(l_2, l_3, m_2, m_3) +\n l_{\\text{max}}\\, \\text{is odd}\\end{cases}\n \\end{aligned}\n\n and `\\kappa(l_2, l_3, m_2, m_3) = \\max{\\big(|l_2-l_3|, \\min{\\big(|m_2+m_3|,\n |m_2-m_3|\\big)}\\big)}`\n\n- zero for an odd number of negative `m_i`\n\nAlgorithms\n==========\n\nThis function uses the algorithms of [Homeier96]_ and [Rasch03]_ to\ncalculate the value of the real Gaunt coefficient exactly. Note that\nthe formula used in [Rasch03]_ contains alternating sums over large\nfactorials and is therefore unsuitable for finite precision arithmetic\nand only useful for a computer algebra system [Rasch03]_. However, this\nfunction can in principle use any algorithm that computes the Gaunt\ncoefficient, so it is suitable for finite precision arithmetic in so far\nas the algorithm which computes the Gaunt coefficient is.", "lines": [ 756, 908 ], "name": "real_gaunt", "signature": "def real_gaunt(l_1, l_2, l_3, m_1, m_2, m_3, prec=None):", "type": "function" } ], "file": "sympy/physics/wigner.py" } ]
[ "test_clebsch_gordan_docs", "test_clebsch_gordan", "test_wigner", "test_gaunt", "test_realgaunt", "test_racah", "test_dot_rota_grad_SH" ]
[]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> Add algorithm to compute real Gaunt coefficient <!-- Your title above should be a short description of what was changed. Do not include the issue number in the title. --> I have coded a symbolic algorithm to compute the integral of three real spherical harmonics based on the outline presented in Homeier and Steinborn (1996). The appropriate import lines, references, and documentation have also been added throughout the entire file. #### References to other Issues or PRs <!-- If this pull request fixes an issue, write "Fixes #NNNN" in that exact format, e.g. "Fixes #1234" (see https://tinyurl.com/auto-closing for more information). Also, please write a comment on that issue linking back to this pull request once it is open. --> I proposed these changes with the help of @smichr in pull request #24035, but I am new to GitHub and didnt merge the changes properly so I am opening a new pull request. #### Brief description of what is fixed or changed An algorithm to compute the real Gaunt coefficient has been added as a function titled real_gaunt, along with the appropriate import lines, references, and documentation scattered throughout the wigner.py file. A test function titled test_realgaunt was added to the testing file within the physics module as well. Lastly, the test functions for the clebsch-gordon function were all condensed down to one. #### Other comments The algorithm uses the already included Gaunt algorithm, but I can find another if this is problematic (due to copyright issues perhaps). Please also let me know if anyone finds any bugs or other conflicting lines. EDIT: Very big thanks to Christopher Smith for suggesting a number of modifications that have made the program more concise and reduced the runtime significantly. #### Release Notes <!-- Write the release notes for this release below between the BEGIN and END statements. The basic format is a bulleted list with the name of the subpackage and the release note for this PR. For example: * solvers * Added a new solver for logarithmic equations. * functions * Fixed a bug with log of integers. or if no release note(s) should be included use: NO ENTRY See https://github.com/sympy/sympy/wiki/Writing-Release-Notes for more information on how to write release notes. The bot will check your release notes automatically to see if they are formatted correctly. --> <!-- BEGIN RELEASE NOTES --> * physics.wigner * Added `real_gaunt` function to compute the integral of 3 real spherical harmonics. <!-- END RELEASE NOTES --> ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in sympy/physics/wigner.py] (definition of real_gaunt:) def real_gaunt(l_1, l_2, l_3, m_1, m_2, m_3, prec=None): """Calculate the real Gaunt coefficient. Explanation =========== The real Gaunt coefficient is defined as the integral over three real spherical harmonics: .. math:: \begin{aligned} \operatorname{RealGaunt}(l_1,l_2,l_3,m_1,m_2,m_3) &=\int Z^{m_1}_{l_1}(\Omega) Z^{m_2}_{l_2}(\Omega) Z^{m_3}_{l_3}(\Omega) \,d\Omega \\ \end{aligned} Alternatively, it can be defined in terms of the standard Gaunt coefficient by relating the real spherical harmonics to the standard spherical harmonics via a unitary transformation `U`, i.e. `Z^{m}_{l}(\Omega)=\sum_{m'}U^{m}_{m'}Y^{m'}_{l}(\Omega)` [Homeier96]_. The real Gaunt coefficient is then defined as .. math:: \begin{aligned} \operatorname{RealGaunt}(l_1,l_2,l_3,m_1,m_2,m_3) &=\int Z^{m_1}_{l_1}(\Omega) Z^{m_2}_{l_2}(\Omega) Z^{m_3}_{l_3}(\Omega) \,d\Omega \\ &=\sum_{m'_1 m'_2 m'_3} U^{m_1}_{m'_1}U^{m_2}_{m'_2}U^{m_3}_{m'_3} \operatorname{Gaunt}(l_1,l_2,l_3,m'_1,m'_2,m'_3) \end{aligned} The unitary matrix `U` has components .. math:: \begin{aligned} U^m_{m'} = \delta_{|m||m'|}*(\delta_{m'0}\delta_{m0} + \frac{1}{\sqrt{2}}\big[\Theta(m) \big(\delta_{m'm}+(-1)^{m'}\delta_{m'-m}\big)+i\Theta(-m)\big((-1)^{-m} \delta_{m'-m}-\delta_{m'm}*(-1)^{m'-m}\big)\big]) \end{aligned} where `\delta_{ij}` is the Kronecker delta symbol and `\Theta` is a step function defined as .. math:: \begin{aligned} \Theta(x) = \begin{cases} 1 \,\text{for}\, x > 0 \\ 0 \,\text{for}\, x \leq 0 \end{cases} \end{aligned} Parameters ========== l_1, l_2, l_3, m_1, m_2, m_3 : Integer. prec - precision, default: ``None``. Providing a precision can drastically speed up the calculation. Returns ======= Rational number times the square root of a rational number. Examples ======== >>> from sympy.physics.wigner import real_gaunt >>> real_gaunt(2,2,4,-1,-1,0) -2/(7*sqrt(pi)) >>> real_gaunt(10,10,20,-9,-9,0).n(64) -0.00002480019791932209313156167... It is an error to use non-integer values for `l` and `m`:: real_gaunt(2.8,0.5,1.3,0,0,0) Traceback (most recent call last): ... ValueError: l values must be integer real_gaunt(2,2,4,0.7,1,-3.4) Traceback (most recent call last): ... ValueError: m values must be integer Notes ===== The real Gaunt coefficient inherits from the standard Gaunt coefficient, the invariance under any permutation of the pairs `(l_i, m_i)` and the requirement that the sum of the `l_i` be even to yield a non-zero value. It also obeys the following symmetry rules: - zero for `l_1`, `l_2`, `l_3` not fulfiling the condition `l_1 \in \{l_{\text{max}}, l_{\text{max}}-2, \ldots, l_{\text{min}}\}`, where `l_{\text{max}} = l_2+l_3`, .. math:: \begin{aligned} l_{\text{min}} = \begin{cases} \kappa(l_2, l_3, m_2, m_3) & \text{if}\, \kappa(l_2, l_3, m_2, m_3) + l_{\text{max}}\, \text{is even} \\ \kappa(l_2, l_3, m_2, m_3)+1 & \text{if}\, \kappa(l_2, l_3, m_2, m_3) + l_{\text{max}}\, \text{is odd}\end{cases} \end{aligned} and `\kappa(l_2, l_3, m_2, m_3) = \max{\big(|l_2-l_3|, \min{\big(|m_2+m_3|, |m_2-m_3|\big)}\big)}` - zero for an odd number of negative `m_i` Algorithms ========== This function uses the algorithms of [Homeier96]_ and [Rasch03]_ to calculate the value of the real Gaunt coefficient exactly. Note that the formula used in [Rasch03]_ contains alternating sums over large factorials and is therefore unsuitable for finite precision arithmetic and only useful for a computer algebra system [Rasch03]_. However, this function can in principle use any algorithm that computes the Gaunt coefficient, so it is suitable for finite precision arithmetic in so far as the algorithm which computes the Gaunt coefficient is.""" [end of new definitions in sympy/physics/wigner.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
22520ed5f4a9b2b6c4b6b314b4748878f1b4b662
astropy__astropy-13676
13,676
astropy/astropy
5.0
a30301e5535be2f558cb948da6b3475df4e36a98
2022-09-15T19:20:47Z
diff --git a/astropy/units/quantity.py b/astropy/units/quantity.py index 7043156e91d7..0512e969291a 100644 --- a/astropy/units/quantity.py +++ b/astropy/units/quantity.py @@ -29,7 +29,7 @@ from .quantity_helper import can_have_arbitrary_unit, check_output, converters_and_unit from .quantity_helper.function_helpers import ( DISPATCHED_FUNCTIONS, FUNCTION_HELPERS, SUBCLASS_SAFE_FUNCTIONS, UNSUPPORTED_FUNCTIONS) -from .structured import StructuredUnit +from .structured import StructuredUnit, _structured_unit_like_dtype from .utils import is_effectively_unity __all__ = ["Quantity", "SpecificTypeQuantity", @@ -481,6 +481,7 @@ def __new__(cls, value, unit=None, dtype=np.inexact, copy=True, order=None, # structured dtype of the value. dtype = unit._recursively_get_dtype(value) + using_default_unit = False if value_unit is None: # If the value has a `unit` attribute and if not None # (for Columns with uninitialized unit), treat it like a quantity. @@ -488,6 +489,7 @@ def __new__(cls, value, unit=None, dtype=np.inexact, copy=True, order=None, if value_unit is None: # Default to dimensionless for no (initialized) unit attribute. if unit is None: + using_default_unit = True unit = cls._default_unit value_unit = unit # signal below that no conversion is needed else: @@ -507,6 +509,11 @@ def __new__(cls, value, unit=None, dtype=np.inexact, copy=True, order=None, value = np.array(value, dtype=dtype, copy=copy, order=order, subok=True, ndmin=ndmin) + # For no-user-input unit, make sure the constructed unit matches the + # structure of the data. + if using_default_unit and value.dtype.names is not None: + unit = value_unit = _structured_unit_like_dtype(value_unit, value.dtype) + # check that array contains numbers or long int objects if (value.dtype.kind in 'OSU' and not (value.dtype.kind == 'O' and diff --git a/astropy/units/structured.py b/astropy/units/structured.py index ead091e4b9db..a28ff6fb873c 100644 --- a/astropy/units/structured.py +++ b/astropy/units/structured.py @@ -3,6 +3,8 @@ This module defines structured units and quantities. """ +from __future__ import annotations # For python < 3.10 + # Standard library import operator @@ -515,3 +517,34 @@ def __ne__(self, other): other = other.item() return self.item() != other + + +def _structured_unit_like_dtype(unit: UnitBase | StructuredUnit, dtype: np.dtype) -> StructuredUnit: + """Make a `StructuredUnit` of one unit, with the structure of a `numpy.dtype`. + + Parameters + ---------- + unit : UnitBase + The unit that will be filled into the structure. + dtype : `numpy.dtype` + The structure for the StructuredUnit. + + Returns + ------- + StructuredUnit + """ + if isinstance(unit, StructuredUnit): + # If unit is structured, it should match the dtype. This function is + # only used in Quantity, which performs this check, so it's fine to + # return as is. + return unit + + # Make a structured unit + units = [] + for name in dtype.names: + subdtype = dtype.fields[name][0] + if subdtype.names is not None: + units.append(_structured_unit_like_dtype(unit, subdtype)) + else: + units.append(unit) + return StructuredUnit(tuple(units), names=dtype.names) diff --git a/docs/changes/units/13676.api.rst b/docs/changes/units/13676.api.rst new file mode 100644 index 000000000000..966372f06cef --- /dev/null +++ b/docs/changes/units/13676.api.rst @@ -0,0 +1,2 @@ +When ``Quantity`` is constructed from a structured array and ``unit`` is +``None``, the default unit is now structured like the input data.
diff --git a/astropy/units/tests/test_structured.py b/astropy/units/tests/test_structured.py index fe4134ac05b2..78ab03a7c022 100644 --- a/astropy/units/tests/test_structured.py +++ b/astropy/units/tests/test_structured.py @@ -12,6 +12,7 @@ from astropy import units as u from astropy.tests.helper import check_pickling_recovery, pickle_protocol from astropy.units import Quantity, StructuredUnit, Unit, UnitBase +from astropy.units.quantity import _structured_unit_like_dtype from astropy.utils.compat import NUMPY_LT_1_21_1 from astropy.utils.masked import Masked @@ -433,6 +434,17 @@ def test_initialization_by_shifting_to_unit(self): assert np.all(q_pv_t.value == self.pv_t) assert np.may_share_memory(q_pv_t, self.pv_t) + def test_initialization_without_unit(self): + q_pv_t = u.Quantity(self.pv_t, unit=None) + + assert np.all(q_pv_t.value == self.pv_t) + + # Test that unit is a structured unit like the dtype + expected_unit = _structured_unit_like_dtype(u.Quantity._default_unit, self.pv_t.dtype) + assert q_pv_t.unit == expected_unit + # A more explicit test + assert q_pv_t.unit == u.StructuredUnit(((u.one, u.one), u.one)) + def test_getitem(self): q_pv_t = Quantity(self.pv_t, self.pv_t_unit) q_pv_t01 = q_pv_t[:2]
diff --git a/docs/changes/units/13676.api.rst b/docs/changes/units/13676.api.rst new file mode 100644 index 000000000000..966372f06cef --- /dev/null +++ b/docs/changes/units/13676.api.rst @@ -0,0 +1,2 @@ +When ``Quantity`` is constructed from a structured array and ``unit`` is +``None``, the default unit is now structured like the input data.
[ { "components": [ { "doc": "Make a `StructuredUnit` of one unit, with the structure of a `numpy.dtype`.\n\nParameters\n----------\nunit : UnitBase\n The unit that will be filled into the structure.\ndtype : `numpy.dtype`\n The structure for the StructuredUnit.\n\nReturns\n-------\nStructuredUnit", "lines": [ 522, 550 ], "name": "_structured_unit_like_dtype", "signature": "def _structured_unit_like_dtype(unit: UnitBase | StructuredUnit, dtype: np.dtype) -> StructuredUnit:", "type": "function" } ], "file": "astropy/units/structured.py" } ]
[ "astropy/units/tests/test_structured.py::TestStructuredUnitBasics::test_initialization_and_keying", "astropy/units/tests/test_structured.py::TestStructuredUnitBasics::test_recursive_initialization", "astropy/units/tests/test_structured.py::TestStructuredUnitBasics::test_extreme_recursive_initialization", "astropy/units/tests/test_structured.py::TestStructuredUnitBasics::test_initialization_names_invalid_list_errors[names0-['p',", "astropy/units/tests/test_structured.py::TestStructuredUnitBasics::test_initialization_names_invalid_list_errors[names1-['pv',", "astropy/units/tests/test_structured.py::TestStructuredUnitBasics::test_initialization_names_invalid_list_errors[names2-['pv',", "astropy/units/tests/test_structured.py::TestStructuredUnitBasics::test_initialization_names_invalid_list_errors[names3-()]", "astropy/units/tests/test_structured.py::TestStructuredUnitBasics::test_initialization_names_invalid_list_errors[names4-None]", "astropy/units/tests/test_structured.py::TestStructuredUnitBasics::test_initialization_names_invalid_list_errors[names5-'']", "astropy/units/tests/test_structured.py::TestStructuredUnitBasics::test_looks_like_unit", "astropy/units/tests/test_structured.py::TestStructuredUnitBasics::test_initialize_with_float_dtype", "astropy/units/tests/test_structured.py::TestStructuredUnitBasics::test_initialize_with_structured_unit_for_names", "astropy/units/tests/test_structured.py::TestStructuredUnitBasics::test_initialize_single_field", "astropy/units/tests/test_structured.py::TestStructuredUnitBasics::test_equality", "astropy/units/tests/test_structured.py::TestStructuredUnitBasics::test_parsing", "astropy/units/tests/test_structured.py::TestStructuredUnitBasics::test_to_string", "astropy/units/tests/test_structured.py::TestStructuredUnitBasics::test_str", "astropy/units/tests/test_structured.py::TestStructuredUnitBasics::test_repr", "astropy/units/tests/test_structured.py::TestStructuredUnitsCopyPickle::test_copy", "astropy/units/tests/test_structured.py::TestStructuredUnitsCopyPickle::test_deepcopy", "astropy/units/tests/test_structured.py::TestStructuredUnitsCopyPickle::test_pickle[0]", "astropy/units/tests/test_structured.py::TestStructuredUnitsCopyPickle::test_pickle[1]", "astropy/units/tests/test_structured.py::TestStructuredUnitsCopyPickle::test_pickle[-1]", "astropy/units/tests/test_structured.py::TestStructuredUnitAsMapping::test_len", "astropy/units/tests/test_structured.py::TestStructuredUnitAsMapping::test_keys", "astropy/units/tests/test_structured.py::TestStructuredUnitAsMapping::test_values", "astropy/units/tests/test_structured.py::TestStructuredUnitAsMapping::test_field_names", "astropy/units/tests/test_structured.py::TestStructuredUnitAsMapping::test_as_iterable[list]", "astropy/units/tests/test_structured.py::TestStructuredUnitAsMapping::test_as_iterable[set]", "astropy/units/tests/test_structured.py::TestStructuredUnitAsMapping::test_as_dict", "astropy/units/tests/test_structured.py::TestStructuredUnitAsMapping::test_contains", "astropy/units/tests/test_structured.py::TestStructuredUnitAsMapping::test_setitem_fails", "astropy/units/tests/test_structured.py::TestStructuredUnitMethods::test_physical_type_id", "astropy/units/tests/test_structured.py::TestStructuredUnitMethods::test_physical_type", "astropy/units/tests/test_structured.py::TestStructuredUnitMethods::test_si", "astropy/units/tests/test_structured.py::TestStructuredUnitMethods::test_cgs", "astropy/units/tests/test_structured.py::TestStructuredUnitMethods::test_decompose", "astropy/units/tests/test_structured.py::TestStructuredUnitMethods::test_is_equivalent", "astropy/units/tests/test_structured.py::TestStructuredUnitMethods::test_conversion", "astropy/units/tests/test_structured.py::TestStructuredUnitArithmatic::test_multiplication", "astropy/units/tests/test_structured.py::TestStructuredUnitArithmatic::test_division", "astropy/units/tests/test_structured.py::TestStructuredQuantity::test_initialization_and_keying", "astropy/units/tests/test_structured.py::TestStructuredQuantity::test_initialization_with_unit_tuples", "astropy/units/tests/test_structured.py::TestStructuredQuantity::test_initialization_with_string", "astropy/units/tests/test_structured.py::TestStructuredQuantity::test_initialization_by_multiplication_with_unit", "astropy/units/tests/test_structured.py::TestStructuredQuantity::test_initialization_by_shifting_to_unit", "astropy/units/tests/test_structured.py::TestStructuredQuantity::test_initialization_without_unit", "astropy/units/tests/test_structured.py::TestStructuredQuantity::test_getitem", "astropy/units/tests/test_structured.py::TestStructuredQuantity::test_value", "astropy/units/tests/test_structured.py::TestStructuredQuantity::test_conversion", "astropy/units/tests/test_structured.py::TestStructuredQuantity::test_conversion_via_lshift", "astropy/units/tests/test_structured.py::TestStructuredQuantity::test_inplace_conversion", "astropy/units/tests/test_structured.py::TestStructuredQuantity::test_si", "astropy/units/tests/test_structured.py::TestStructuredQuantity::test_cgs", "astropy/units/tests/test_structured.py::TestStructuredQuantity::test_equality", "astropy/units/tests/test_structured.py::TestStructuredQuantity::test_setitem", "astropy/units/tests/test_structured.py::TestStructuredQuantityFunctions::test_empty_like", "astropy/units/tests/test_structured.py::TestStructuredQuantityFunctions::test_zeros_ones_like[zeros_like]", "astropy/units/tests/test_structured.py::TestStructuredQuantityFunctions::test_zeros_ones_like[ones_like]", "astropy/units/tests/test_structured.py::TestStructuredQuantityFunctions::test_structured_to_unstructured", "astropy/units/tests/test_structured.py::TestStructuredQuantityFunctions::test_unstructured_to_structured", "astropy/units/tests/test_structured.py::TestStructuredSpecificTypeQuantity::test_init", "astropy/units/tests/test_structured.py::TestStructuredSpecificTypeQuantity::test_error_on_non_equivalent_unit", "astropy/units/tests/test_structured.py::TestStructuredLogUnit::test_unit_initialization", "astropy/units/tests/test_structured.py::TestStructuredLogUnit::test_quantity_initialization", "astropy/units/tests/test_structured.py::TestStructuredLogUnit::test_quantity_si", "astropy/units/tests/test_structured.py::TestStructuredMaskedQuantity::test_init", "astropy/units/tests/test_structured.py::TestStructuredMaskedQuantity::test_slicing", "astropy/units/tests/test_structured.py::TestStructuredMaskedQuantity::test_conversion", "astropy/units/tests/test_structured.py::TestStructuredMaskedQuantity::test_si" ]
[]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> structured unit / quantity stuff Signed-off-by: Nathaniel Starkman (@nstarman) <nstarkman@protonmail.com> Necessary for https://github.com/astropy/astropy/pull/13669 - Quantity now builds a structured unit if ``unit=None`` in the constructor and the value is structured. TODO: - [x] changelog - [x] tests ### Checklist for package maintainer(s) <!-- This section is to be filled by package maintainer(s) who will review this pull request. --> This checklist is meant to remind the package maintainer(s) who will review this pull request of some common things to look for. This list is not exhaustive. - [x] Do the proposed changes actually accomplish desired goals? - [ ] Do the proposed changes follow the [Astropy coding guidelines](https://docs.astropy.org/en/latest/development/codeguide.html)? - [x] Are tests added/updated as required? If so, do they follow the [Astropy testing guidelines](https://docs.astropy.org/en/latest/development/testguide.html)? - [x] Are docs added/updated as required? If so, do they follow the [Astropy documentation guidelines](https://docs.astropy.org/en/latest/development/docguide.html#astropy-documentation-rules-and-guidelines)? - [x] Is rebase and/or squash necessary? If so, please provide the author with appropriate instructions. Also see ["When to rebase and squash commits"](https://docs.astropy.org/en/latest/development/when_to_rebase.html). - [x] Did the CI pass? If no, are the failures related? If you need to run daily and weekly cron jobs as part of the PR, please apply the `Extra CI` label. Codestyle issues can be fixed by the [bot](https://docs.astropy.org/en/latest/development/workflow/development_workflow.html#pre-commit). - [x] Is a change log needed? If yes, did the change log check pass? If no, add the `no-changelog-entry-needed` label. If this is a manual backport, use the `skip-changelog-checks` label unless special changelog handling is necessary. - [x] Is this a big PR that makes a "What's new?" entry worthwhile and if so, is (1) a "what's new" entry included in this PR and (2) the "whatsnew-needed" label applied? - [x] Is a milestone set? Milestone must be set but `astropy-bot` check might be missing; do not let the green checkmark fool you. - [x] At the time of adding the milestone, if the milestone set requires a backport to release branch(es), apply the appropriate `backport-X.Y.x` label(s) *before* merge. ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in astropy/units/structured.py] (definition of _structured_unit_like_dtype:) def _structured_unit_like_dtype(unit: UnitBase | StructuredUnit, dtype: np.dtype) -> StructuredUnit: """Make a `StructuredUnit` of one unit, with the structure of a `numpy.dtype`. Parameters ---------- unit : UnitBase The unit that will be filled into the structure. dtype : `numpy.dtype` The structure for the StructuredUnit. Returns ------- StructuredUnit""" [end of new definitions in astropy/units/structured.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
7cbba866a8c5749b90a5cb4f9877ddfad2d36037
conan-io__conan-12094
12,094
conan-io/conan
null
91c5aaf1115fd3a9c9932c8d804a14d894076c49
2022-09-12T15:01:24Z
diff --git a/conans/model/options.py b/conans/model/options.py index 642c4afe2d1..8c270238059 100644 --- a/conans/model/options.py +++ b/conans/model/options.py @@ -231,6 +231,12 @@ def get_safe(self, attr): return None return getattr(self._package_values, attr) + def rm_safe(self, attr): + try: + delattr(self._package_values, attr) + except ConanException: + pass + def __getitem__(self, item): return self._reqs_options.setdefault(item, PackageOptionValues()) @@ -425,6 +431,12 @@ def loads(text): def get_safe(self, field, default=None): return self._data.get(field, default) + def rm_safe(self, field): + try: + delattr(self, field) + except ConanException: + pass + def validate(self): for child in self._data.values(): child.validate() @@ -584,6 +596,9 @@ def __delattr__(self, field): except ConanException: pass + def rm_safe(self, field): + self._package_options.rm_safe(field) + @property def values(self): result = OptionsValues() diff --git a/conans/model/settings.py b/conans/model/settings.py index 8a7e697aa3b..096483ed38c 100644 --- a/conans/model/settings.py +++ b/conans/model/settings.py @@ -213,6 +213,19 @@ def get_safe(self, name, default=None): return str(tmp) return default + def rm_safe(self, name): + try: + tmp = self + attr_ = name + if "." in name: + fields = name.split(".") + attr_ = fields.pop() + for prop in fields: + tmp = getattr(tmp, prop) + delattr(tmp, attr_) + except ConanException: + pass + def copy(self): """ deepcopy, recursive """
diff --git a/conans/test/integration/settings/remove_subsetting_test.py b/conans/test/integration/settings/remove_subsetting_test.py index 5c8e6d8a275..209838e1b99 100644 --- a/conans/test/integration/settings/remove_subsetting_test.py +++ b/conans/test/integration/settings/remove_subsetting_test.py @@ -1,4 +1,5 @@ import os +import textwrap import unittest from conans.test.utils.tools import TestClient @@ -144,3 +145,57 @@ def build(self): client.run("package .") self.assertIn("ERROR: PACKAGE 'settings.compiler.libcxx' doesn't exist for 'gcc'", client.out) + + +def test_settings_and_options_rm_safe(): + client = TestClient() + conanfile = textwrap.dedent(""" + from conan import ConanFile + class Pkg(ConanFile): + settings = "os", "build_type", "compiler" + options = {"opt1": [True, False], "opt2": [True, False]} + default_options = "opt1=True", "opt2=False" + + def configure(self): + # setting + self.settings.rm_safe("build_type") + # sub-setting + self.settings.rm_safe("compiler.version") + # wrong settings + self.settings.rm_safe("fake_field") + self.settings.rm_safe("fake_field.version") + + def config_options(self): + # option + self.options.rm_safe("opt2") + # wrong option + self.options.rm_safe("opt15") + + def build(self): + try: + self.settings.build_type + except Exception as exc: + self.output.warn(str(exc)) + try: + self.settings.compiler.version + except Exception as exc: + self.output.warn(str(exc)) + try: + self.options.opt2 + except Exception as exc: + self.output.warn(str(exc)) + assert "opt2" not in self.options + """) + client.save({"conanfile.py": conanfile}) + build_folder = os.path.join(client.current_folder, "build") + mkdir(build_folder) + client.current_folder = build_folder + + client.run("install ..") + client.run("build ..") + assert "'settings.build_type' doesn't exist" in client.out + assert "'settings' possible configurations are ['compiler', 'os']" in client.out + assert "'settings.compiler.version' doesn't exist" in client.out + assert "'settings.compiler' possible configurations are [" in client.out + assert "option 'opt2' doesn't exist" in client.out + assert "Possible options are ['opt1']" in client.out
[ { "components": [ { "doc": "", "lines": [ 234, 238 ], "name": "OptionsValues.rm_safe", "signature": "def rm_safe(self, attr):", "type": "function" }, { "doc": "", "lines": [ 434, 438 ], "name": "PackageOptions.rm_safe", "signature": "def rm_safe(self, field):", "type": "function" }, { "doc": "", "lines": [ 599, 600 ], "name": "Options.rm_safe", "signature": "def rm_safe(self, field):", "type": "function" } ], "file": "conans/model/options.py" }, { "components": [ { "doc": "", "lines": [ 216, 227 ], "name": "Settings.rm_safe", "signature": "def rm_safe(self, name):", "type": "function" } ], "file": "conans/model/settings.py" } ]
[ "conans/test/integration/settings/remove_subsetting_test.py::test_settings_and_options_rm_safe" ]
[ "conans/test/integration/settings/remove_subsetting_test.py::RemoveSubsettingTest::test_remove_options", "conans/test/integration/settings/remove_subsetting_test.py::RemoveSubsettingTest::test_remove_runtime", "conans/test/integration/settings/remove_subsetting_test.py::RemoveSubsettingTest::test_remove_setting", "conans/test/integration/settings/remove_subsetting_test.py::RemoveSubsettingTest::test_remove_subsetting", "conans/test/integration/settings/remove_subsetting_test.py::RemoveSubsettingTest::test_remove_subsetting_build" ]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> [feature] `rm_safe` for settings and options Changelog: Feature: Added method `rm_safe` to `settings` and `options`. Docs: https://github.com/conan-io/docs/pull/2764 This feature is trying to avoid this common structure: ```python try: del self.settings.compiler.libcxx except Exception: pass try: del self.settings.compiler.cppstd except Exception: pass ``` Now, it could be: ```python self.settings.rm_safe("compiler.libcxx") self.settings.rm_safe("compiler.cppstd") ``` ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in conans/model/options.py] (definition of OptionsValues.rm_safe:) def rm_safe(self, attr): (definition of PackageOptions.rm_safe:) def rm_safe(self, field): (definition of Options.rm_safe:) def rm_safe(self, field): [end of new definitions in conans/model/options.py] [start of new definitions in conans/model/settings.py] (definition of Settings.rm_safe:) def rm_safe(self, name): [end of new definitions in conans/model/settings.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
4a5b19a75db9225316c8cb022a2dfb9705a2af34
tobymao__sqlglot-415
415
tobymao/sqlglot
null
7f40ddd9b41f3dabdcbc3105cf5f06faacd82d75
2022-09-09T21:28:47Z
diff --git a/sqlglot/expressions.py b/sqlglot/expressions.py index dc0c0ca20d..f6ca8f5403 100644 --- a/sqlglot/expressions.py +++ b/sqlglot/expressions.py @@ -1155,6 +1155,72 @@ def order_by(self, *expressions, append=True, dialect=None, copy=True, **opts): **opts, ) + def sort_by(self, *expressions, append=True, dialect=None, copy=True, **opts): + """ + Set the SORT BY expression. + + Example: + >>> Select().from_("tbl").select("x").sort_by("x DESC").sql() + 'SELECT x FROM tbl SORT BY x DESC' + + Args: + *expressions (str or Expression): the SQL code strings to parse. + If a `Group` instance is passed, this is used as-is. + If another `Expression` instance is passed, it will be wrapped in a `SORT`. + append (bool): if `True`, add to any existing expressions. + Otherwise, this flattens all the `Order` expression into a single expression. + dialect (str): the dialect used to parse the input expression. + copy (bool): if `False`, modify this expression instance in-place. + opts (kwargs): other options to use to parse the input expressions. + + Returns: + Select: the modified expression. + """ + return _apply_child_list_builder( + *expressions, + instance=self, + arg="sort", + append=append, + copy=copy, + prefix="SORT BY", + into=Sort, + dialect=dialect, + **opts, + ) + + def cluster_by(self, *expressions, append=True, dialect=None, copy=True, **opts): + """ + Set the CLUSTER BY expression. + + Example: + >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql() + 'SELECT x FROM tbl CLUSTER BY x DESC' + + Args: + *expressions (str or Expression): the SQL code strings to parse. + If a `Group` instance is passed, this is used as-is. + If another `Expression` instance is passed, it will be wrapped in a `Cluster`. + append (bool): if `True`, add to any existing expressions. + Otherwise, this flattens all the `Order` expression into a single expression. + dialect (str): the dialect used to parse the input expression. + copy (bool): if `False`, modify this expression instance in-place. + opts (kwargs): other options to use to parse the input expressions. + + Returns: + Select: the modified expression. + """ + return _apply_child_list_builder( + *expressions, + instance=self, + arg="cluster", + append=append, + copy=copy, + prefix="CLUSTER BY", + into=Cluster, + dialect=dialect, + **opts, + ) + def limit(self, expression, dialect=None, copy=True, **opts): """ Set the LIMIT expression. diff --git a/sqlglot/parser.py b/sqlglot/parser.py index 1c4e7ba4ee..162384aeda 100644 --- a/sqlglot/parser.py +++ b/sqlglot/parser.py @@ -273,6 +273,8 @@ class Parser: exp.Lateral: lambda self: self._parse_lateral(), exp.Join: lambda self: self._parse_join(), exp.Order: lambda self: self._parse_order(), + exp.Cluster: lambda self: self._parse_sort(TokenType.CLUSTER_BY, exp.Cluster), + exp.Sort: lambda self: self._parse_sort(TokenType.SORT_BY, exp.Sort), exp.Lambda: lambda self: self._parse_lambda(), exp.Limit: lambda self: self._parse_limit(), exp.Offset: lambda self: self._parse_offset(),
diff --git a/tests/test_build.py b/tests/test_build.py index 10c485728a..a4cffde9ea 100644 --- a/tests/test_build.py +++ b/tests/test_build.py @@ -169,10 +169,26 @@ def test_build(self): lambda: select("x").from_("tbl").order_by("y"), "SELECT x FROM tbl ORDER BY y", ), + ( + lambda: select("x").from_("tbl").cluster_by("y"), + "SELECT x FROM tbl CLUSTER BY y", + ), + ( + lambda: select("x").from_("tbl").sort_by("y"), + "SELECT x FROM tbl SORT BY y", + ), ( lambda: select("x").from_("tbl").order_by("x, y DESC"), "SELECT x FROM tbl ORDER BY x, y DESC", ), + ( + lambda: select("x").from_("tbl").cluster_by("x, y DESC"), + "SELECT x FROM tbl CLUSTER BY x, y DESC", + ), + ( + lambda: select("x").from_("tbl").sort_by("x, y DESC"), + "SELECT x FROM tbl SORT BY x, y DESC", + ), ( lambda: select("x", "y", "z", "a") .from_("tbl") @@ -180,6 +196,20 @@ def test_build(self): .order_by("a"), "SELECT x, y, z, a FROM tbl ORDER BY x, y, z, a", ), + ( + lambda: select("x", "y", "z", "a") + .from_("tbl") + .cluster_by("x, y", "z") + .cluster_by("a"), + "SELECT x, y, z, a FROM tbl CLUSTER BY x, y, z, a", + ), + ( + lambda: select("x", "y", "z", "a") + .from_("tbl") + .sort_by("x, y", "z") + .sort_by("a"), + "SELECT x, y, z, a FROM tbl SORT BY x, y, z, a", + ), (lambda: select("x").from_("tbl").limit(10), "SELECT x FROM tbl LIMIT 10"), ( lambda: select("x").from_("tbl").offset(10),
[ { "components": [ { "doc": "Set the SORT BY expression.\n\nExample:\n >>> Select().from_(\"tbl\").select(\"x\").sort_by(\"x DESC\").sql()\n 'SELECT x FROM tbl SORT BY x DESC'\n\nArgs:\n *expressions (str or Expression): the SQL code strings to parse.\n If a `Group` instance is passed, this is used as-is.\n If another `Expression` instance is passed, it will be wrapped in a `SORT`.\n append (bool): if `True`, add to any existing expressions.\n Otherwise, this flattens all the `Order` expression into a single expression.\n dialect (str): the dialect used to parse the input expression.\n copy (bool): if `False`, modify this expression instance in-place.\n opts (kwargs): other options to use to parse the input expressions. \n\nReturns:\n Select: the modified expression.", "lines": [ 1158, 1188 ], "name": "Select.sort_by", "signature": "def sort_by(self, *expressions, append=True, dialect=None, copy=True, **opts):", "type": "function" }, { "doc": "Set the CLUSTER BY expression.\n\nExample:\n >>> Select().from_(\"tbl\").select(\"x\").cluster_by(\"x DESC\").sql()\n 'SELECT x FROM tbl CLUSTER BY x DESC'\n\nArgs:\n *expressions (str or Expression): the SQL code strings to parse.\n If a `Group` instance is passed, this is used as-is.\n If another `Expression` instance is passed, it will be wrapped in a `Cluster`.\n append (bool): if `True`, add to any existing expressions.\n Otherwise, this flattens all the `Order` expression into a single expression.\n dialect (str): the dialect used to parse the input expression.\n copy (bool): if `False`, modify this expression instance in-place.\n opts (kwargs): other options to use to parse the input expressions. \n\nReturns:\n Select: the modified expression.", "lines": [ 1191, 1221 ], "name": "Select.cluster_by", "signature": "def cluster_by(self, *expressions, append=True, dialect=None, copy=True, **opts):", "type": "function" } ], "file": "sqlglot/expressions.py" } ]
[ "tests/test_build.py::TestBuild::test_build" ]
[]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> feat: Add sort_by and cluster_by to expression builder We already have SORT & CLUSTER expression and SORT_BY & CLUSTER_BY tokens, they are currently used in DDLs but they can also be used in expression builder. This PR adds that support. ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in sqlglot/expressions.py] (definition of Select.sort_by:) def sort_by(self, *expressions, append=True, dialect=None, copy=True, **opts): """Set the SORT BY expression. Example: >>> Select().from_("tbl").select("x").sort_by("x DESC").sql() 'SELECT x FROM tbl SORT BY x DESC' Args: *expressions (str or Expression): the SQL code strings to parse. If a `Group` instance is passed, this is used as-is. If another `Expression` instance is passed, it will be wrapped in a `SORT`. append (bool): if `True`, add to any existing expressions. Otherwise, this flattens all the `Order` expression into a single expression. dialect (str): the dialect used to parse the input expression. copy (bool): if `False`, modify this expression instance in-place. opts (kwargs): other options to use to parse the input expressions. Returns: Select: the modified expression.""" (definition of Select.cluster_by:) def cluster_by(self, *expressions, append=True, dialect=None, copy=True, **opts): """Set the CLUSTER BY expression. Example: >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql() 'SELECT x FROM tbl CLUSTER BY x DESC' Args: *expressions (str or Expression): the SQL code strings to parse. If a `Group` instance is passed, this is used as-is. If another `Expression` instance is passed, it will be wrapped in a `Cluster`. append (bool): if `True`, add to any existing expressions. Otherwise, this flattens all the `Order` expression into a single expression. dialect (str): the dialect used to parse the input expression. copy (bool): if `False`, modify this expression instance in-place. opts (kwargs): other options to use to parse the input expressions. Returns: Select: the modified expression.""" [end of new definitions in sqlglot/expressions.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
ceb42fabad60312699e4b15936aeebac00e22e4d
matplotlib__matplotlib-23692
23,692
matplotlib/matplotlib
3.5
3d6c3da884fafae4654df68144391cfe9be6f134
2022-08-20T23:23:12Z
diff --git a/doc/api/axis_api.rst b/doc/api/axis_api.rst index d950d1e253a4..e7da26a11706 100644 --- a/doc/api/axis_api.rst +++ b/doc/api/axis_api.rst @@ -100,6 +100,7 @@ Ticks, tick labels and Offset text Axis.get_offset_text Axis.get_tick_padding + Axis.get_tick_params Axis.get_ticklabels Axis.get_ticklines Axis.get_ticklocs diff --git a/doc/users/next_whats_new/view_current_axis_format.rst b/doc/users/next_whats_new/view_current_axis_format.rst new file mode 100644 index 000000000000..eb7e03600f0e --- /dev/null +++ b/doc/users/next_whats_new/view_current_axis_format.rst @@ -0,0 +1,29 @@ +View current appearance settings for ticks, tick labels, and gridlines +---------------------------------------------------------------------- + +The new `~matplotlib.axis.Axis.get_tick_params` method can be used to +retrieve the appearance settings that will be applied to any +additional ticks, tick labels, and gridlines added to the plot: + +.. code-block:: pycon + + >>> import matplotlib.pyplot as plt + + >>> fig, ax = plt.subplots() + >>> ax.yaxis.set_tick_params(labelsize=30, labelcolor='red', + ... direction='out', which='major') + >>> ax.yaxis.get_tick_params(which='major') + {'direction': 'out', + 'left': True, + 'right': False, + 'labelleft': True, + 'labelright': False, + 'gridOn': False, + 'labelsize': 30, + 'labelcolor': 'red'} + >>> ax.yaxis.get_tick_params(which='minor') + {'left': True, + 'right': False, + 'labelleft': True, + 'labelright': False, + 'gridOn': False} diff --git a/lib/matplotlib/axes/_base.py b/lib/matplotlib/axes/_base.py index 015fd3294589..d3ea2cd0e9ac 100644 --- a/lib/matplotlib/axes/_base.py +++ b/lib/matplotlib/axes/_base.py @@ -3403,7 +3403,8 @@ def tick_params(self, axis='both', **kwargs): Change the appearance of ticks, tick labels, and gridlines. Tick properties that are not explicitly set using the keyword - arguments remain unchanged unless *reset* is True. + arguments remain unchanged unless *reset* is True. For the current + style settings, see `.Axis.get_tick_params`. Parameters ---------- diff --git a/lib/matplotlib/axis.py b/lib/matplotlib/axis.py index af0815d41d9c..ae38dd28676b 100644 --- a/lib/matplotlib/axis.py +++ b/lib/matplotlib/axis.py @@ -916,6 +916,12 @@ def set_tick_params(self, which='major', reset=False, **kwargs): For documentation of keyword arguments, see :meth:`matplotlib.axes.Axes.tick_params`. + + See Also + -------- + .Axis.get_tick_params + View the current style settings for ticks, ticklabels, and + gridlines. """ _api.check_in_list(['major', 'minor', 'both'], which=which) kwtrans = self._translate_tick_params(kwargs) @@ -949,8 +955,62 @@ def set_tick_params(self, which='major', reset=False, **kwargs): self.stale = True + def get_tick_params(self, which='major'): + """ + Get appearance parameters for ticks, ticklabels, and gridlines. + + .. versionadded:: 3.7 + + Parameters + ---------- + which : {'major', 'minor'}, default: 'major' + The group of ticks for which the parameters are retrieved. + + Returns + ------- + dict + Properties for styling tick elements added to the axis. + + Notes + ----- + This method returns the appearance parameters for styling *new* + elements added to this axis and may be different from the values + on current elements if they were modified directly by the user + (e.g., via ``set_*`` methods on individual tick objects). + + Examples + -------- + :: + + >>> ax.yaxis.set_tick_params(labelsize=30, labelcolor='red', + direction='out', which='major') + >>> ax.yaxis.get_tick_params(which='major') + {'direction': 'out', + 'left': True, + 'right': False, + 'labelleft': True, + 'labelright': False, + 'gridOn': False, + 'labelsize': 30, + 'labelcolor': 'red'} + >>> ax.yaxis.get_tick_params(which='minor') + {'left': True, + 'right': False, + 'labelleft': True, + 'labelright': False, + 'gridOn': False} + + + """ + _api.check_in_list(['major', 'minor'], which=which) + if which == 'major': + return self._translate_tick_params( + self._major_tick_kw, reverse=True + ) + return self._translate_tick_params(self._minor_tick_kw, reverse=True) + @staticmethod - def _translate_tick_params(kw): + def _translate_tick_params(kw, reverse=False): """ Translate the kwargs supported by `.Axis.set_tick_params` to kwargs supported by `.Tick._apply_params`. @@ -961,9 +1021,12 @@ def _translate_tick_params(kw): Returns a new dict of translated kwargs. - Note: The input *kwargs* are currently modified, but that's ok for - the only caller. + Note: Use reverse=True to translate from those supported by + `.Tick._apply_params` back to those supported by + `.Axis.set_tick_params`. """ + kw_ = {**kw} + # The following lists may be moved to a more accessible location. allowed_keys = [ 'size', 'width', 'color', 'tickdir', 'pad', @@ -988,19 +1051,27 @@ def _translate_tick_params(kw): 'labelright': 'label2On', 'labeltop': 'label2On', } - kwtrans = {newkey: kw.pop(oldkey) - for oldkey, newkey in keymap.items() if oldkey in kw} - if 'colors' in kw: - c = kw.pop('colors') + if reverse: + kwtrans = { + oldkey: kw_.pop(newkey) + for oldkey, newkey in keymap.items() if newkey in kw_ + } + else: + kwtrans = { + newkey: kw_.pop(oldkey) + for oldkey, newkey in keymap.items() if oldkey in kw_ + } + if 'colors' in kw_: + c = kw_.pop('colors') kwtrans['color'] = c kwtrans['labelcolor'] = c # Maybe move the checking up to the caller of this method. - for key in kw: + for key in kw_: if key not in allowed_keys: raise ValueError( "keyword %s is not recognized; valid keywords are %s" % (key, allowed_keys)) - kwtrans.update(kw) + kwtrans.update(kw_) return kwtrans def set_clip_path(self, clippath, transform=None):
diff --git a/lib/matplotlib/tests/test_axes.py b/lib/matplotlib/tests/test_axes.py index 3699c9df133d..aed45743d66b 100644 --- a/lib/matplotlib/tests/test_axes.py +++ b/lib/matplotlib/tests/test_axes.py @@ -6452,6 +6452,33 @@ def test_pandas_bar_align_center(pd): fig.canvas.draw() +def test_axis_get_tick_params(): + axis = plt.subplot().yaxis + initial_major_style_translated = {**axis.get_tick_params(which='major')} + initial_minor_style_translated = {**axis.get_tick_params(which='minor')} + + translated_major_kw = axis._translate_tick_params( + axis._major_tick_kw, reverse=True + ) + translated_minor_kw = axis._translate_tick_params( + axis._minor_tick_kw, reverse=True + ) + + assert translated_major_kw == initial_major_style_translated + assert translated_minor_kw == initial_minor_style_translated + axis.set_tick_params(labelsize=30, labelcolor='red', + direction='out', which='both') + + new_major_style_translated = {**axis.get_tick_params(which='major')} + new_minor_style_translated = {**axis.get_tick_params(which='minor')} + new_major_style = axis._translate_tick_params(new_major_style_translated) + new_minor_style = axis._translate_tick_params(new_minor_style_translated) + assert initial_major_style_translated != new_major_style_translated + assert axis._major_tick_kw == new_major_style + assert initial_minor_style_translated != new_minor_style_translated + assert axis._minor_tick_kw == new_minor_style + + def test_axis_set_tick_params_labelsize_labelcolor(): # Tests fix for issue 4346 axis_1 = plt.subplot()
diff --git a/doc/api/axis_api.rst b/doc/api/axis_api.rst index d950d1e253a4..e7da26a11706 100644 --- a/doc/api/axis_api.rst +++ b/doc/api/axis_api.rst @@ -100,6 +100,7 @@ Ticks, tick labels and Offset text Axis.get_offset_text Axis.get_tick_padding + Axis.get_tick_params Axis.get_ticklabels Axis.get_ticklines Axis.get_ticklocs diff --git a/doc/users/next_whats_new/view_current_axis_format.rst b/doc/users/next_whats_new/view_current_axis_format.rst new file mode 100644 index 000000000000..eb7e03600f0e --- /dev/null +++ b/doc/users/next_whats_new/view_current_axis_format.rst @@ -0,0 +1,29 @@ +View current appearance settings for ticks, tick labels, and gridlines +---------------------------------------------------------------------- + +The new `~matplotlib.axis.Axis.get_tick_params` method can be used to +retrieve the appearance settings that will be applied to any +additional ticks, tick labels, and gridlines added to the plot: + +.. code-block:: pycon + + >>> import matplotlib.pyplot as plt + + >>> fig, ax = plt.subplots() + >>> ax.yaxis.set_tick_params(labelsize=30, labelcolor='red', + ... direction='out', which='major') + >>> ax.yaxis.get_tick_params(which='major') + {'direction': 'out', + 'left': True, + 'right': False, + 'labelleft': True, + 'labelright': False, + 'gridOn': False, + 'labelsize': 30, + 'labelcolor': 'red'} + >>> ax.yaxis.get_tick_params(which='minor') + {'left': True, + 'right': False, + 'labelleft': True, + 'labelright': False, + 'gridOn': False}
[ { "components": [ { "doc": "Get appearance parameters for ticks, ticklabels, and gridlines.\n\n.. versionadded:: 3.7\n\nParameters\n----------\nwhich : {'major', 'minor'}, default: 'major'\n The group of ticks for which the parameters are retrieved.\n\nReturns\n-------\ndict\n Properties for styling tick elements added to the axis.\n\nNotes\n-----\nThis method returns the appearance parameters for styling *new*\nelements added to this axis and may be different from the values\non current elements if they were modified directly by the user\n(e.g., via ``set_*`` methods on individual tick objects).\n\nExamples\n--------\n::\n\n >>> ax.yaxis.set_tick_params(labelsize=30, labelcolor='red',\n direction='out', which='major')\n >>> ax.yaxis.get_tick_params(which='major')\n {'direction': 'out',\n 'left': True,\n 'right': False,\n 'labelleft': True,\n 'labelright': False,\n 'gridOn': False,\n 'labelsize': 30,\n 'labelcolor': 'red'}\n >>> ax.yaxis.get_tick_params(which='minor')\n {'left': True,\n 'right': False,\n 'labelleft': True,\n 'labelright': False,\n 'gridOn': False}", "lines": [ 958, 1010 ], "name": "Axis.get_tick_params", "signature": "def get_tick_params(self, which='major'):", "type": "function" } ], "file": "lib/matplotlib/axis.py" } ]
[ "lib/matplotlib/tests/test_axes.py::test_axis_get_tick_params" ]
[ "lib/matplotlib/tests/test_axes.py::test_invisible_axes[png]", "lib/matplotlib/tests/test_axes.py::test_get_labels", "lib/matplotlib/tests/test_axes.py::test_repr", "lib/matplotlib/tests/test_axes.py::test_label_loc_vertical[png]", "lib/matplotlib/tests/test_axes.py::test_label_loc_horizontal[png]", "lib/matplotlib/tests/test_axes.py::test_label_loc_rc[png]", "lib/matplotlib/tests/test_axes.py::test_label_shift", "lib/matplotlib/tests/test_axes.py::test_acorr[png]", "lib/matplotlib/tests/test_axes.py::test_spy[png]", "lib/matplotlib/tests/test_axes.py::test_spy_invalid_kwargs", "lib/matplotlib/tests/test_axes.py::test_matshow[png]", "lib/matplotlib/tests/test_axes.py::test_formatter_ticker[png]", "lib/matplotlib/tests/test_axes.py::test_funcformatter_auto_formatter", "lib/matplotlib/tests/test_axes.py::test_strmethodformatter_auto_formatter", "lib/matplotlib/tests/test_axes.py::test_twin_axis_locators_formatters[png]", "lib/matplotlib/tests/test_axes.py::test_twinx_cla", "lib/matplotlib/tests/test_axes.py::test_twin_logscale[png-x]", "lib/matplotlib/tests/test_axes.py::test_twin_logscale[png-y]", "lib/matplotlib/tests/test_axes.py::test_twinx_axis_scales[png]", "lib/matplotlib/tests/test_axes.py::test_twin_inherit_autoscale_setting", "lib/matplotlib/tests/test_axes.py::test_inverted_cla", "lib/matplotlib/tests/test_axes.py::test_subclass_clear_cla", "lib/matplotlib/tests/test_axes.py::test_cla_not_redefined_internally", "lib/matplotlib/tests/test_axes.py::test_minorticks_on_rcParams_both[png]", "lib/matplotlib/tests/test_axes.py::test_autoscale_tiny_range[png]", "lib/matplotlib/tests/test_axes.py::test_autoscale_tight", "lib/matplotlib/tests/test_axes.py::test_autoscale_log_shared", "lib/matplotlib/tests/test_axes.py::test_use_sticky_edges", "lib/matplotlib/tests/test_axes.py::test_sticky_shared_axes[png]", "lib/matplotlib/tests/test_axes.py::test_basic_annotate[png]", "lib/matplotlib/tests/test_axes.py::test_arrow_simple[png]", "lib/matplotlib/tests/test_axes.py::test_arrow_empty", "lib/matplotlib/tests/test_axes.py::test_arrow_in_view", "lib/matplotlib/tests/test_axes.py::test_annotate_default_arrow", "lib/matplotlib/tests/test_axes.py::test_annotate_signature", "lib/matplotlib/tests/test_axes.py::test_fill_units[png]", "lib/matplotlib/tests/test_axes.py::test_plot_format_kwarg_redundant", "lib/matplotlib/tests/test_axes.py::test_errorbar_dashes[png]", "lib/matplotlib/tests/test_axes.py::test_single_point[png]", "lib/matplotlib/tests/test_axes.py::test_single_date[png]", "lib/matplotlib/tests/test_axes.py::test_shaped_data[png]", "lib/matplotlib/tests/test_axes.py::test_structured_data", "lib/matplotlib/tests/test_axes.py::test_aitoff_proj[png]", "lib/matplotlib/tests/test_axes.py::test_axvspan_epoch[png]", "lib/matplotlib/tests/test_axes.py::test_axhspan_epoch[png]", "lib/matplotlib/tests/test_axes.py::test_hexbin_extent[png]", "lib/matplotlib/tests/test_axes.py::test_hexbin_empty[png]", "lib/matplotlib/tests/test_axes.py::test_hexbin_pickable", "lib/matplotlib/tests/test_axes.py::test_hexbin_log[png]", "lib/matplotlib/tests/test_axes.py::test_hexbin_linear[png]", "lib/matplotlib/tests/test_axes.py::test_hexbin_log_clim", "lib/matplotlib/tests/test_axes.py::test_inverted_limits", "lib/matplotlib/tests/test_axes.py::test_nonfinite_limits[png]", "lib/matplotlib/tests/test_axes.py::test_limits_empty_data[png-scatter]", "lib/matplotlib/tests/test_axes.py::test_limits_empty_data[png-plot]", "lib/matplotlib/tests/test_axes.py::test_limits_empty_data[png-fill_between]", "lib/matplotlib/tests/test_axes.py::test_imshow[png]", "lib/matplotlib/tests/test_axes.py::test_imshow_clip[png]", "lib/matplotlib/tests/test_axes.py::test_imshow_norm_vminvmax", "lib/matplotlib/tests/test_axes.py::test_polycollection_joinstyle[png]", "lib/matplotlib/tests/test_axes.py::test_fill_between_input[2d_x_input]", "lib/matplotlib/tests/test_axes.py::test_fill_between_input[2d_y1_input]", "lib/matplotlib/tests/test_axes.py::test_fill_between_input[2d_y2_input]", "lib/matplotlib/tests/test_axes.py::test_fill_betweenx_input[2d_y_input]", "lib/matplotlib/tests/test_axes.py::test_fill_betweenx_input[2d_x1_input]", "lib/matplotlib/tests/test_axes.py::test_fill_betweenx_input[2d_x2_input]", "lib/matplotlib/tests/test_axes.py::test_fill_between_interpolate[png]", "lib/matplotlib/tests/test_axes.py::test_fill_between_interpolate_decreasing[png]", "lib/matplotlib/tests/test_axes.py::test_fill_between_interpolate_nan[png]", "lib/matplotlib/tests/test_axes.py::test_pcolorargs_5205", "lib/matplotlib/tests/test_axes.py::test_pcolormesh[png]", "lib/matplotlib/tests/test_axes.py::test_pcolormesh_alpha[png]", "lib/matplotlib/tests/test_axes.py::test_pcolormesh_datetime_axis[png]", "lib/matplotlib/tests/test_axes.py::test_pcolor_datetime_axis[png]", "lib/matplotlib/tests/test_axes.py::test_pcolorargs", "lib/matplotlib/tests/test_axes.py::test_pcolornearest[png]", "lib/matplotlib/tests/test_axes.py::test_pcolornearestunits[png]", "lib/matplotlib/tests/test_axes.py::test_pcolorflaterror", "lib/matplotlib/tests/test_axes.py::test_pcolorauto[png-False]", "lib/matplotlib/tests/test_axes.py::test_pcolorauto[png-True]", "lib/matplotlib/tests/test_axes.py::test_canonical[png]", "lib/matplotlib/tests/test_axes.py::test_arc_angles[png]", "lib/matplotlib/tests/test_axes.py::test_arc_ellipse[png]", "lib/matplotlib/tests/test_axes.py::test_marker_as_markerstyle", "lib/matplotlib/tests/test_axes.py::test_markevery[png]", "lib/matplotlib/tests/test_axes.py::test_markevery_line[png]", "lib/matplotlib/tests/test_axes.py::test_markevery_linear_scales[png]", "lib/matplotlib/tests/test_axes.py::test_markevery_linear_scales_zoomed[png]", "lib/matplotlib/tests/test_axes.py::test_markevery_log_scales[png]", "lib/matplotlib/tests/test_axes.py::test_markevery_polar[png]", "lib/matplotlib/tests/test_axes.py::test_markevery_linear_scales_nans[png]", "lib/matplotlib/tests/test_axes.py::test_marker_edges[png]", "lib/matplotlib/tests/test_axes.py::test_bar_tick_label_single[png]", "lib/matplotlib/tests/test_axes.py::test_nan_bar_values", "lib/matplotlib/tests/test_axes.py::test_bar_ticklabel_fail", "lib/matplotlib/tests/test_axes.py::test_bar_tick_label_multiple[png]", "lib/matplotlib/tests/test_axes.py::test_bar_tick_label_multiple_old_alignment[png]", "lib/matplotlib/tests/test_axes.py::test_bar_decimal_center[png]", "lib/matplotlib/tests/test_axes.py::test_barh_decimal_center[png]", "lib/matplotlib/tests/test_axes.py::test_bar_decimal_width[png]", "lib/matplotlib/tests/test_axes.py::test_barh_decimal_height[png]", "lib/matplotlib/tests/test_axes.py::test_bar_color_none_alpha", "lib/matplotlib/tests/test_axes.py::test_bar_edgecolor_none_alpha", "lib/matplotlib/tests/test_axes.py::test_barh_tick_label[png]", "lib/matplotlib/tests/test_axes.py::test_bar_timedelta", "lib/matplotlib/tests/test_axes.py::test_boxplot_dates_pandas", "lib/matplotlib/tests/test_axes.py::test_boxplot_capwidths", "lib/matplotlib/tests/test_axes.py::test_pcolor_regression", "lib/matplotlib/tests/test_axes.py::test_bar_pandas", "lib/matplotlib/tests/test_axes.py::test_bar_pandas_indexed", "lib/matplotlib/tests/test_axes.py::test_bar_hatches[png]", "lib/matplotlib/tests/test_axes.py::test_bar_labels[x-1-x-expected_labels0-x]", "lib/matplotlib/tests/test_axes.py::test_bar_labels[x1-width1-label1-expected_labels1-_nolegend_]", "lib/matplotlib/tests/test_axes.py::test_bar_labels[x2-width2-label2-expected_labels2-_nolegend_]", "lib/matplotlib/tests/test_axes.py::test_bar_labels[x3-width3-bars-expected_labels3-bars]", "lib/matplotlib/tests/test_axes.py::test_bar_labels_length", "lib/matplotlib/tests/test_axes.py::test_pandas_minimal_plot", "lib/matplotlib/tests/test_axes.py::test_hist_log[png]", "lib/matplotlib/tests/test_axes.py::test_hist_log_2[png]", "lib/matplotlib/tests/test_axes.py::test_hist_log_barstacked", "lib/matplotlib/tests/test_axes.py::test_hist_bar_empty[png]", "lib/matplotlib/tests/test_axes.py::test_hist_float16", "lib/matplotlib/tests/test_axes.py::test_hist_step_empty[png]", "lib/matplotlib/tests/test_axes.py::test_hist_step_filled[png]", "lib/matplotlib/tests/test_axes.py::test_hist_density[png]", "lib/matplotlib/tests/test_axes.py::test_hist_unequal_bins_density", "lib/matplotlib/tests/test_axes.py::test_hist_datetime_datasets", "lib/matplotlib/tests/test_axes.py::test_hist_datetime_datasets_bins[date2num]", "lib/matplotlib/tests/test_axes.py::test_hist_datetime_datasets_bins[datetime.datetime]", "lib/matplotlib/tests/test_axes.py::test_hist_datetime_datasets_bins[np.datetime64]", "lib/matplotlib/tests/test_axes.py::test_hist_with_empty_input[data0-1]", "lib/matplotlib/tests/test_axes.py::test_hist_with_empty_input[data1-1]", "lib/matplotlib/tests/test_axes.py::test_hist_with_empty_input[data2-2]", "lib/matplotlib/tests/test_axes.py::test_hist_zorder[bar-1]", "lib/matplotlib/tests/test_axes.py::test_hist_zorder[step-2]", "lib/matplotlib/tests/test_axes.py::test_hist_zorder[stepfilled-1]", "lib/matplotlib/tests/test_axes.py::test_stairs[png]", "lib/matplotlib/tests/test_axes.py::test_stairs_fill[png]", "lib/matplotlib/tests/test_axes.py::test_stairs_update[png]", "lib/matplotlib/tests/test_axes.py::test_stairs_baseline_0[png]", "lib/matplotlib/tests/test_axes.py::test_stairs_empty", "lib/matplotlib/tests/test_axes.py::test_stairs_invalid_nan", "lib/matplotlib/tests/test_axes.py::test_stairs_invalid_mismatch", "lib/matplotlib/tests/test_axes.py::test_stairs_invalid_update", "lib/matplotlib/tests/test_axes.py::test_stairs_invalid_update2", "lib/matplotlib/tests/test_axes.py::test_stairs_options[png]", "lib/matplotlib/tests/test_axes.py::test_stairs_datetime[png]", "lib/matplotlib/tests/test_axes.py::test_stairs_edge_handling[png]", "lib/matplotlib/tests/test_axes.py::test_contour_hatching[png]", "lib/matplotlib/tests/test_axes.py::test_contour_colorbar[png]", "lib/matplotlib/tests/test_axes.py::test_hist2d[png]", "lib/matplotlib/tests/test_axes.py::test_hist2d_transpose[png]", "lib/matplotlib/tests/test_axes.py::test_hist2d_density", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_plot[png]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_marker[png]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_2D[png]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_decimal[png]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_color", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_color_warning[kwargs0]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_color_warning[kwargs1]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_color_warning[kwargs2]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_color_warning[kwargs3]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_unfilled", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_unfillable", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_size_arg_size", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_edgecolor_RGB", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_invalid_color[png]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_no_invalid_color[png]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_norm_vminvmax", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_single_point[png]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_different_shapes[png]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[0.5-None]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case1-conversion]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[red-None]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[none-None]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[None-None]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case5-None]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[jaune-conversion]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case7-conversion]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case8-conversion]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case9-None]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case10-None]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case11-shape]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case12-None]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case13-None]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case14-conversion]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case15-None]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case16-shape]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case17-None]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case18-shape]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case19-None]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case20-shape]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case21-None]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case22-shape]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case23-None]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case24-shape]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case25-None]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case26-shape]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case27-conversion]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case28-conversion]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case29-conversion]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_single_color_c[png]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_linewidths", "lib/matplotlib/tests/test_axes.py::test_parse_scatter_color_args[params0-expected_result0]", "lib/matplotlib/tests/test_axes.py::test_parse_scatter_color_args[params1-expected_result1]", "lib/matplotlib/tests/test_axes.py::test_parse_scatter_color_args[params2-expected_result2]", "lib/matplotlib/tests/test_axes.py::test_parse_scatter_color_args[params3-expected_result3]", "lib/matplotlib/tests/test_axes.py::test_parse_scatter_color_args[params4-expected_result4]", "lib/matplotlib/tests/test_axes.py::test_parse_scatter_color_args_edgecolors[kwargs0-None]", "lib/matplotlib/tests/test_axes.py::test_parse_scatter_color_args_edgecolors[kwargs1-None]", "lib/matplotlib/tests/test_axes.py::test_parse_scatter_color_args_edgecolors[kwargs2-r]", "lib/matplotlib/tests/test_axes.py::test_parse_scatter_color_args_edgecolors[kwargs3-expected_edgecolors3]", "lib/matplotlib/tests/test_axes.py::test_parse_scatter_color_args_edgecolors[kwargs4-r]", "lib/matplotlib/tests/test_axes.py::test_parse_scatter_color_args_edgecolors[kwargs5-face]", "lib/matplotlib/tests/test_axes.py::test_parse_scatter_color_args_edgecolors[kwargs6-none]", "lib/matplotlib/tests/test_axes.py::test_parse_scatter_color_args_edgecolors[kwargs7-r]", "lib/matplotlib/tests/test_axes.py::test_parse_scatter_color_args_edgecolors[kwargs8-r]", "lib/matplotlib/tests/test_axes.py::test_parse_scatter_color_args_edgecolors[kwargs9-r]", "lib/matplotlib/tests/test_axes.py::test_parse_scatter_color_args_edgecolors[kwargs10-g]", "lib/matplotlib/tests/test_axes.py::test_parse_scatter_color_args_error", "lib/matplotlib/tests/test_axes.py::test_as_mpl_axes_api", "lib/matplotlib/tests/test_axes.py::test_pyplot_axes", "lib/matplotlib/tests/test_axes.py::test_log_scales", "lib/matplotlib/tests/test_axes.py::test_log_scales_no_data", "lib/matplotlib/tests/test_axes.py::test_log_scales_invalid", "lib/matplotlib/tests/test_axes.py::test_stackplot[png]", "lib/matplotlib/tests/test_axes.py::test_stackplot_baseline[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_baseline[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_rangewhis[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_percentilewhis[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_with_xlabels[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_horizontal[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_with_ylabels[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_patchartist[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_custompatchartist[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_customoutlier[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_showcustommean[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_custombox[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_custommedian[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_customcap[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_customwhisker[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_shownotches[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_nocaps[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_nobox[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_no_flier_stats[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_showmean[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_showmeanasline[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_scalarwidth[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_customwidths[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_custompositions[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_bad_widths", "lib/matplotlib/tests/test_axes.py::test_bxp_bad_positions", "lib/matplotlib/tests/test_axes.py::test_bxp_custom_capwidths[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_custom_capwidth[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_bad_capwidths", "lib/matplotlib/tests/test_axes.py::test_boxplot[png]", "lib/matplotlib/tests/test_axes.py::test_boxplot_custom_capwidths[png]", "lib/matplotlib/tests/test_axes.py::test_boxplot_sym2[png]", "lib/matplotlib/tests/test_axes.py::test_boxplot_sym[png]", "lib/matplotlib/tests/test_axes.py::test_boxplot_autorange_whiskers[png]", "lib/matplotlib/tests/test_axes.py::test_boxplot_rc_parameters[png]", "lib/matplotlib/tests/test_axes.py::test_boxplot_with_CIarray[png]", "lib/matplotlib/tests/test_axes.py::test_boxplot_no_weird_whisker[png]", "lib/matplotlib/tests/test_axes.py::test_boxplot_bad_medians", "lib/matplotlib/tests/test_axes.py::test_boxplot_bad_ci", "lib/matplotlib/tests/test_axes.py::test_boxplot_zorder", "lib/matplotlib/tests/test_axes.py::test_boxplot_marker_behavior", "lib/matplotlib/tests/test_axes.py::test_boxplot_mod_artist_after_plotting[png]", "lib/matplotlib/tests/test_axes.py::test_vert_violinplot_baseline[png]", "lib/matplotlib/tests/test_axes.py::test_vert_violinplot_showmeans[png]", "lib/matplotlib/tests/test_axes.py::test_vert_violinplot_showextrema[png]", "lib/matplotlib/tests/test_axes.py::test_vert_violinplot_showmedians[png]", "lib/matplotlib/tests/test_axes.py::test_vert_violinplot_showall[png]", "lib/matplotlib/tests/test_axes.py::test_vert_violinplot_custompoints_10[png]", "lib/matplotlib/tests/test_axes.py::test_vert_violinplot_custompoints_200[png]", "lib/matplotlib/tests/test_axes.py::test_horiz_violinplot_baseline[png]", "lib/matplotlib/tests/test_axes.py::test_horiz_violinplot_showmedians[png]", "lib/matplotlib/tests/test_axes.py::test_horiz_violinplot_showmeans[png]", "lib/matplotlib/tests/test_axes.py::test_horiz_violinplot_showextrema[png]", "lib/matplotlib/tests/test_axes.py::test_horiz_violinplot_showall[png]", "lib/matplotlib/tests/test_axes.py::test_horiz_violinplot_custompoints_10[png]", "lib/matplotlib/tests/test_axes.py::test_horiz_violinplot_custompoints_200[png]", "lib/matplotlib/tests/test_axes.py::test_violinplot_bad_positions", "lib/matplotlib/tests/test_axes.py::test_violinplot_bad_widths", "lib/matplotlib/tests/test_axes.py::test_violinplot_bad_quantiles", "lib/matplotlib/tests/test_axes.py::test_violinplot_outofrange_quantiles", "lib/matplotlib/tests/test_axes.py::test_violinplot_single_list_quantiles[png]", "lib/matplotlib/tests/test_axes.py::test_violinplot_pandas_series[png]", "lib/matplotlib/tests/test_axes.py::test_manage_xticks", "lib/matplotlib/tests/test_axes.py::test_boxplot_not_single", "lib/matplotlib/tests/test_axes.py::test_tick_space_size_0", "lib/matplotlib/tests/test_axes.py::test_errorbar[png]", "lib/matplotlib/tests/test_axes.py::test_mixed_errorbar_polar_caps[png]", "lib/matplotlib/tests/test_axes.py::test_errorbar_colorcycle", "lib/matplotlib/tests/test_axes.py::test_errorbar_cycle_ecolor[png]", "lib/matplotlib/tests/test_axes.py::test_errorbar_shape", "lib/matplotlib/tests/test_axes.py::test_errorbar_limits[png]", "lib/matplotlib/tests/test_axes.py::test_errorbar_nonefmt", "lib/matplotlib/tests/test_axes.py::test_errorbar_line_specific_kwargs", "lib/matplotlib/tests/test_axes.py::test_errorbar_with_prop_cycle[png]", "lib/matplotlib/tests/test_axes.py::test_errorbar_every_invalid", "lib/matplotlib/tests/test_axes.py::test_xerr_yerr_not_negative", "lib/matplotlib/tests/test_axes.py::test_errorbar_every[png]", "lib/matplotlib/tests/test_axes.py::test_errorbar_linewidth_type[elinewidth0]", "lib/matplotlib/tests/test_axes.py::test_errorbar_linewidth_type[elinewidth1]", "lib/matplotlib/tests/test_axes.py::test_errorbar_linewidth_type[1]", "lib/matplotlib/tests/test_axes.py::test_errorbar_nan[png]", "lib/matplotlib/tests/test_axes.py::test_hist_stacked_stepfilled[png]", "lib/matplotlib/tests/test_axes.py::test_hist_offset[png]", "lib/matplotlib/tests/test_axes.py::test_hist_step[png]", "lib/matplotlib/tests/test_axes.py::test_hist_step_horiz[png]", "lib/matplotlib/tests/test_axes.py::test_hist_stacked_weighted[png]", "lib/matplotlib/tests/test_axes.py::test_stem[png-w/", "lib/matplotlib/tests/test_axes.py::test_stem[png-w/o", "lib/matplotlib/tests/test_axes.py::test_stem_args", "lib/matplotlib/tests/test_axes.py::test_stem_markerfmt", "lib/matplotlib/tests/test_axes.py::test_stem_dates", "lib/matplotlib/tests/test_axes.py::test_stem_orientation[png-w/", "lib/matplotlib/tests/test_axes.py::test_stem_orientation[png-w/o", "lib/matplotlib/tests/test_axes.py::test_hist_stacked_stepfilled_alpha[png]", "lib/matplotlib/tests/test_axes.py::test_hist_stacked_step[png]", "lib/matplotlib/tests/test_axes.py::test_hist_stacked_density[png]", "lib/matplotlib/tests/test_axes.py::test_hist_step_bottom[png]", "lib/matplotlib/tests/test_axes.py::test_hist_stepfilled_geometry", "lib/matplotlib/tests/test_axes.py::test_hist_step_geometry", "lib/matplotlib/tests/test_axes.py::test_hist_stepfilled_bottom_geometry", "lib/matplotlib/tests/test_axes.py::test_hist_step_bottom_geometry", "lib/matplotlib/tests/test_axes.py::test_hist_stacked_stepfilled_geometry", "lib/matplotlib/tests/test_axes.py::test_hist_stacked_step_geometry", "lib/matplotlib/tests/test_axes.py::test_hist_stacked_stepfilled_bottom_geometry", "lib/matplotlib/tests/test_axes.py::test_hist_stacked_step_bottom_geometry", "lib/matplotlib/tests/test_axes.py::test_hist_stacked_bar[png]", "lib/matplotlib/tests/test_axes.py::test_hist_barstacked_bottom_unchanged", "lib/matplotlib/tests/test_axes.py::test_hist_emptydata", "lib/matplotlib/tests/test_axes.py::test_hist_labels", "lib/matplotlib/tests/test_axes.py::test_transparent_markers[png]", "lib/matplotlib/tests/test_axes.py::test_rgba_markers[png]", "lib/matplotlib/tests/test_axes.py::test_mollweide_grid[png]", "lib/matplotlib/tests/test_axes.py::test_mollweide_forward_inverse_closure", "lib/matplotlib/tests/test_axes.py::test_mollweide_inverse_forward_closure", "lib/matplotlib/tests/test_axes.py::test_alpha[png]", "lib/matplotlib/tests/test_axes.py::test_eventplot[png]", "lib/matplotlib/tests/test_axes.py::test_eventplot_defaults[png]", "lib/matplotlib/tests/test_axes.py::test_eventplot_colors[colors0]", "lib/matplotlib/tests/test_axes.py::test_eventplot_colors[colors1]", "lib/matplotlib/tests/test_axes.py::test_eventplot_colors[colors2]", "lib/matplotlib/tests/test_axes.py::test_eventplot_problem_kwargs[png]", "lib/matplotlib/tests/test_axes.py::test_empty_eventplot", "lib/matplotlib/tests/test_axes.py::test_eventplot_orientation[None-data0]", "lib/matplotlib/tests/test_axes.py::test_eventplot_orientation[None-data1]", "lib/matplotlib/tests/test_axes.py::test_eventplot_orientation[None-data2]", "lib/matplotlib/tests/test_axes.py::test_eventplot_orientation[vertical-data0]", "lib/matplotlib/tests/test_axes.py::test_eventplot_orientation[vertical-data1]", "lib/matplotlib/tests/test_axes.py::test_eventplot_orientation[vertical-data2]", "lib/matplotlib/tests/test_axes.py::test_eventplot_orientation[horizontal-data0]", "lib/matplotlib/tests/test_axes.py::test_eventplot_orientation[horizontal-data1]", "lib/matplotlib/tests/test_axes.py::test_eventplot_orientation[horizontal-data2]", "lib/matplotlib/tests/test_axes.py::test_eventplot_units_list[png]", "lib/matplotlib/tests/test_axes.py::test_marker_styles[png]", "lib/matplotlib/tests/test_axes.py::test_markers_fillstyle_rcparams[png]", "lib/matplotlib/tests/test_axes.py::test_vertex_markers[png]", "lib/matplotlib/tests/test_axes.py::test_eb_line_zorder[png]", "lib/matplotlib/tests/test_axes.py::test_axline_loglog[png]", "lib/matplotlib/tests/test_axes.py::test_axline[png]", "lib/matplotlib/tests/test_axes.py::test_axline_transaxes[png]", "lib/matplotlib/tests/test_axes.py::test_axline_transaxes_panzoom[png]", "lib/matplotlib/tests/test_axes.py::test_axline_args", "lib/matplotlib/tests/test_axes.py::test_vlines[png]", "lib/matplotlib/tests/test_axes.py::test_vlines_default", "lib/matplotlib/tests/test_axes.py::test_hlines[png]", "lib/matplotlib/tests/test_axes.py::test_hlines_default", "lib/matplotlib/tests/test_axes.py::test_lines_with_colors[png-data0]", "lib/matplotlib/tests/test_axes.py::test_lines_with_colors[png-data1]", "lib/matplotlib/tests/test_axes.py::test_step_linestyle[png]", "lib/matplotlib/tests/test_axes.py::test_mixed_collection[png]", "lib/matplotlib/tests/test_axes.py::test_subplot_key_hash", "lib/matplotlib/tests/test_axes.py::test_specgram[png]", "lib/matplotlib/tests/test_axes.py::test_specgram_magnitude[png]", "lib/matplotlib/tests/test_axes.py::test_specgram_angle[png]", "lib/matplotlib/tests/test_axes.py::test_specgram_fs_none", "lib/matplotlib/tests/test_axes.py::test_specgram_origin_rcparam[png]", "lib/matplotlib/tests/test_axes.py::test_specgram_origin_kwarg", "lib/matplotlib/tests/test_axes.py::test_psd_csd[png]", "lib/matplotlib/tests/test_axes.py::test_spectrum[png]", "lib/matplotlib/tests/test_axes.py::test_psd_csd_edge_cases", "lib/matplotlib/tests/test_axes.py::test_twin_remove[png]", "lib/matplotlib/tests/test_axes.py::test_twin_spines[png]", "lib/matplotlib/tests/test_axes.py::test_twin_spines_on_top[png]", "lib/matplotlib/tests/test_axes.py::test_rcparam_grid_minor[both-True-True]", "lib/matplotlib/tests/test_axes.py::test_rcparam_grid_minor[major-True-False]", "lib/matplotlib/tests/test_axes.py::test_rcparam_grid_minor[minor-False-True]", "lib/matplotlib/tests/test_axes.py::test_grid", "lib/matplotlib/tests/test_axes.py::test_reset_grid", "lib/matplotlib/tests/test_axes.py::test_reset_ticks[png]", "lib/matplotlib/tests/test_axes.py::test_vline_limit", "lib/matplotlib/tests/test_axes.py::test_axline_minmax[axvline-axhline-args0]", "lib/matplotlib/tests/test_axes.py::test_axline_minmax[axvspan-axhspan-args1]", "lib/matplotlib/tests/test_axes.py::test_empty_shared_subplots", "lib/matplotlib/tests/test_axes.py::test_shared_with_aspect_1", "lib/matplotlib/tests/test_axes.py::test_shared_with_aspect_2", "lib/matplotlib/tests/test_axes.py::test_shared_with_aspect_3", "lib/matplotlib/tests/test_axes.py::test_shared_aspect_error", "lib/matplotlib/tests/test_axes.py::test_axis_errors[TypeError-args0-kwargs0-axis\\\\(\\\\)", "lib/matplotlib/tests/test_axes.py::test_axis_errors[ValueError-args1-kwargs1-Unrecognized", "lib/matplotlib/tests/test_axes.py::test_axis_errors[TypeError-args2-kwargs2-the", "lib/matplotlib/tests/test_axes.py::test_axis_errors[TypeError-args3-kwargs3-axis\\\\(\\\\)", "lib/matplotlib/tests/test_axes.py::test_axis_method_errors", "lib/matplotlib/tests/test_axes.py::test_twin_with_aspect[x]", "lib/matplotlib/tests/test_axes.py::test_twin_with_aspect[y]", "lib/matplotlib/tests/test_axes.py::test_relim_visible_only", "lib/matplotlib/tests/test_axes.py::test_text_labelsize", "lib/matplotlib/tests/test_axes.py::test_pie_default[png]", "lib/matplotlib/tests/test_axes.py::test_pie_linewidth_0[png]", "lib/matplotlib/tests/test_axes.py::test_pie_center_radius[png]", "lib/matplotlib/tests/test_axes.py::test_pie_linewidth_2[png]", "lib/matplotlib/tests/test_axes.py::test_pie_ccw_true[png]", "lib/matplotlib/tests/test_axes.py::test_pie_frame_grid[png]", "lib/matplotlib/tests/test_axes.py::test_pie_rotatelabels_true[png]", "lib/matplotlib/tests/test_axes.py::test_pie_nolabel_but_legend[png]", "lib/matplotlib/tests/test_axes.py::test_pie_textprops", "lib/matplotlib/tests/test_axes.py::test_pie_get_negative_values", "lib/matplotlib/tests/test_axes.py::test_normalize_kwarg_pie", "lib/matplotlib/tests/test_axes.py::test_set_get_ticklabels[png]", "lib/matplotlib/tests/test_axes.py::test_set_ticks_with_labels[png]", "lib/matplotlib/tests/test_axes.py::test_set_noniterable_ticklabels", "lib/matplotlib/tests/test_axes.py::test_subsampled_ticklabels", "lib/matplotlib/tests/test_axes.py::test_mismatched_ticklabels", "lib/matplotlib/tests/test_axes.py::test_empty_ticks_fixed_loc", "lib/matplotlib/tests/test_axes.py::test_retain_tick_visibility[png]", "lib/matplotlib/tests/test_axes.py::test_tick_label_update", "lib/matplotlib/tests/test_axes.py::test_o_marker_path_snap[png]", "lib/matplotlib/tests/test_axes.py::test_margins", "lib/matplotlib/tests/test_axes.py::test_set_margin_updates_limits", "lib/matplotlib/tests/test_axes.py::test_margins_errors[ValueError-args0-kwargs0-margin", "lib/matplotlib/tests/test_axes.py::test_margins_errors[ValueError-args1-kwargs1-margin", "lib/matplotlib/tests/test_axes.py::test_margins_errors[ValueError-args2-kwargs2-margin", "lib/matplotlib/tests/test_axes.py::test_margins_errors[ValueError-args3-kwargs3-margin", "lib/matplotlib/tests/test_axes.py::test_margins_errors[TypeError-args4-kwargs4-Cannot", "lib/matplotlib/tests/test_axes.py::test_margins_errors[TypeError-args5-kwargs5-Cannot", "lib/matplotlib/tests/test_axes.py::test_margins_errors[TypeError-args6-kwargs6-Must", "lib/matplotlib/tests/test_axes.py::test_length_one_hist", "lib/matplotlib/tests/test_axes.py::test_set_xy_bound", "lib/matplotlib/tests/test_axes.py::test_pathological_hexbin", "lib/matplotlib/tests/test_axes.py::test_color_None", "lib/matplotlib/tests/test_axes.py::test_color_alias", "lib/matplotlib/tests/test_axes.py::test_numerical_hist_label", "lib/matplotlib/tests/test_axes.py::test_unicode_hist_label", "lib/matplotlib/tests/test_axes.py::test_move_offsetlabel", "lib/matplotlib/tests/test_axes.py::test_rc_spines[png]", "lib/matplotlib/tests/test_axes.py::test_rc_grid[png]", "lib/matplotlib/tests/test_axes.py::test_rc_tick", "lib/matplotlib/tests/test_axes.py::test_rc_major_minor_tick", "lib/matplotlib/tests/test_axes.py::test_square_plot", "lib/matplotlib/tests/test_axes.py::test_bad_plot_args", "lib/matplotlib/tests/test_axes.py::test_pcolorfast[data0-xy0-AxesImage]", "lib/matplotlib/tests/test_axes.py::test_pcolorfast[data0-xy1-AxesImage]", "lib/matplotlib/tests/test_axes.py::test_pcolorfast[data0-xy2-AxesImage]", "lib/matplotlib/tests/test_axes.py::test_pcolorfast[data0-xy3-PcolorImage]", "lib/matplotlib/tests/test_axes.py::test_pcolorfast[data0-xy4-QuadMesh]", "lib/matplotlib/tests/test_axes.py::test_pcolorfast[data1-xy0-AxesImage]", "lib/matplotlib/tests/test_axes.py::test_pcolorfast[data1-xy1-AxesImage]", "lib/matplotlib/tests/test_axes.py::test_pcolorfast[data1-xy2-AxesImage]", "lib/matplotlib/tests/test_axes.py::test_pcolorfast[data1-xy3-PcolorImage]", "lib/matplotlib/tests/test_axes.py::test_pcolorfast[data1-xy4-QuadMesh]", "lib/matplotlib/tests/test_axes.py::test_shared_scale", "lib/matplotlib/tests/test_axes.py::test_shared_bool", "lib/matplotlib/tests/test_axes.py::test_violin_point_mass", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs0]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs1]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs2]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs3]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs4]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs5]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs6]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs7]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs8]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs9]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs10]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs11]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs12]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs13]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs14]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs15]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs16]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs17]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs18]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs19]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs20]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs21]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs22]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs23]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs24]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs25]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs26]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs27]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs28]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs29]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs30]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs31]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs32]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs33]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs34]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs35]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs36]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs37]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs38]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs39]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs40]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs41]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs42]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs43]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs44]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs45]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs46]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs47]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs48]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs49]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs50]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs51]", "lib/matplotlib/tests/test_axes.py::test_dash_offset[png]", "lib/matplotlib/tests/test_axes.py::test_title_pad", "lib/matplotlib/tests/test_axes.py::test_title_location_roundtrip", "lib/matplotlib/tests/test_axes.py::test_title_location_shared[True]", "lib/matplotlib/tests/test_axes.py::test_title_location_shared[False]", "lib/matplotlib/tests/test_axes.py::test_loglog[png]", "lib/matplotlib/tests/test_axes.py::test_loglog_nonpos[png]", "lib/matplotlib/tests/test_axes.py::test_axes_margins", "lib/matplotlib/tests/test_axes.py::test_remove_shared_axes[gca-x]", "lib/matplotlib/tests/test_axes.py::test_remove_shared_axes[gca-y]", "lib/matplotlib/tests/test_axes.py::test_remove_shared_axes[subplots-x]", "lib/matplotlib/tests/test_axes.py::test_remove_shared_axes[subplots-y]", "lib/matplotlib/tests/test_axes.py::test_remove_shared_axes[subplots_shared-x]", "lib/matplotlib/tests/test_axes.py::test_remove_shared_axes[subplots_shared-y]", "lib/matplotlib/tests/test_axes.py::test_remove_shared_axes[add_axes-x]", "lib/matplotlib/tests/test_axes.py::test_remove_shared_axes[add_axes-y]", "lib/matplotlib/tests/test_axes.py::test_remove_shared_axes_relim", "lib/matplotlib/tests/test_axes.py::test_shared_axes_autoscale", "lib/matplotlib/tests/test_axes.py::test_adjust_numtick_aspect", "lib/matplotlib/tests/test_axes.py::test_auto_numticks", "lib/matplotlib/tests/test_axes.py::test_auto_numticks_log", "lib/matplotlib/tests/test_axes.py::test_broken_barh_empty", "lib/matplotlib/tests/test_axes.py::test_broken_barh_timedelta", "lib/matplotlib/tests/test_axes.py::test_pandas_pcolormesh", "lib/matplotlib/tests/test_axes.py::test_pandas_indexing_dates", "lib/matplotlib/tests/test_axes.py::test_pandas_errorbar_indexing", "lib/matplotlib/tests/test_axes.py::test_pandas_index_shape", "lib/matplotlib/tests/test_axes.py::test_pandas_indexing_hist", "lib/matplotlib/tests/test_axes.py::test_pandas_bar_align_center", "lib/matplotlib/tests/test_axes.py::test_axis_set_tick_params_labelsize_labelcolor", "lib/matplotlib/tests/test_axes.py::test_axes_tick_params_gridlines", "lib/matplotlib/tests/test_axes.py::test_axes_tick_params_ylabelside", "lib/matplotlib/tests/test_axes.py::test_axes_tick_params_xlabelside", "lib/matplotlib/tests/test_axes.py::test_none_kwargs", "lib/matplotlib/tests/test_axes.py::test_bar_uint8", "lib/matplotlib/tests/test_axes.py::test_date_timezone_x[png]", "lib/matplotlib/tests/test_axes.py::test_date_timezone_y[png]", "lib/matplotlib/tests/test_axes.py::test_date_timezone_x_and_y[png]", "lib/matplotlib/tests/test_axes.py::test_axisbelow[png]", "lib/matplotlib/tests/test_axes.py::test_titletwiny", "lib/matplotlib/tests/test_axes.py::test_titlesetpos", "lib/matplotlib/tests/test_axes.py::test_title_xticks_top", "lib/matplotlib/tests/test_axes.py::test_title_xticks_top_both", "lib/matplotlib/tests/test_axes.py::test_title_above_offset[left", "lib/matplotlib/tests/test_axes.py::test_title_above_offset[center", "lib/matplotlib/tests/test_axes.py::test_title_above_offset[both", "lib/matplotlib/tests/test_axes.py::test_title_no_move_off_page", "lib/matplotlib/tests/test_axes.py::test_offset_label_color", "lib/matplotlib/tests/test_axes.py::test_offset_text_visible", "lib/matplotlib/tests/test_axes.py::test_large_offset", "lib/matplotlib/tests/test_axes.py::test_barb_units", "lib/matplotlib/tests/test_axes.py::test_quiver_units", "lib/matplotlib/tests/test_axes.py::test_bar_color_cycle", "lib/matplotlib/tests/test_axes.py::test_tick_param_label_rotation", "lib/matplotlib/tests/test_axes.py::test_fillbetween_cycle", "lib/matplotlib/tests/test_axes.py::test_log_margins", "lib/matplotlib/tests/test_axes.py::test_color_length_mismatch", "lib/matplotlib/tests/test_axes.py::test_eventplot_legend", "lib/matplotlib/tests/test_axes.py::test_bar_broadcast_args", "lib/matplotlib/tests/test_axes.py::test_invalid_axis_limits", "lib/matplotlib/tests/test_axes.py::test_minorticks_on[symlog-symlog]", "lib/matplotlib/tests/test_axes.py::test_minorticks_on[symlog-log]", "lib/matplotlib/tests/test_axes.py::test_minorticks_on[log-symlog]", "lib/matplotlib/tests/test_axes.py::test_minorticks_on[log-log]", "lib/matplotlib/tests/test_axes.py::test_twinx_knows_limits", "lib/matplotlib/tests/test_axes.py::test_zero_linewidth", "lib/matplotlib/tests/test_axes.py::test_empty_errorbar_legend", "lib/matplotlib/tests/test_axes.py::test_plot_decimal[png]", "lib/matplotlib/tests/test_axes.py::test_markerfacecolor_none_alpha[png]", "lib/matplotlib/tests/test_axes.py::test_tick_padding_tightbbox", "lib/matplotlib/tests/test_axes.py::test_inset", "lib/matplotlib/tests/test_axes.py::test_zoom_inset", "lib/matplotlib/tests/test_axes.py::test_inset_polar[png]", "lib/matplotlib/tests/test_axes.py::test_inset_projection", "lib/matplotlib/tests/test_axes.py::test_inset_subclass", "lib/matplotlib/tests/test_axes.py::test_indicate_inset_inverted[False-False]", "lib/matplotlib/tests/test_axes.py::test_indicate_inset_inverted[False-True]", "lib/matplotlib/tests/test_axes.py::test_indicate_inset_inverted[True-False]", "lib/matplotlib/tests/test_axes.py::test_indicate_inset_inverted[True-True]", "lib/matplotlib/tests/test_axes.py::test_set_position", "lib/matplotlib/tests/test_axes.py::test_spines_properbbox_after_zoom", "lib/matplotlib/tests/test_axes.py::test_gettightbbox_ignore_nan", "lib/matplotlib/tests/test_axes.py::test_scatter_series_non_zero_index", "lib/matplotlib/tests/test_axes.py::test_scatter_empty_data", "lib/matplotlib/tests/test_axes.py::test_annotate_across_transforms[png]", "lib/matplotlib/tests/test_axes.py::test_secondary_xy[png]", "lib/matplotlib/tests/test_axes.py::test_secondary_fail", "lib/matplotlib/tests/test_axes.py::test_secondary_resize", "lib/matplotlib/tests/test_axes.py::test_secondary_minorloc", "lib/matplotlib/tests/test_axes.py::test_secondary_formatter", "lib/matplotlib/tests/test_axes.py::test_secondary_repr", "lib/matplotlib/tests/test_axes.py::test_normal_axes", "lib/matplotlib/tests/test_axes.py::test_nodecorator", "lib/matplotlib/tests/test_axes.py::test_displaced_spine", "lib/matplotlib/tests/test_axes.py::test_tickdirs", "lib/matplotlib/tests/test_axes.py::test_minor_accountedfor", "lib/matplotlib/tests/test_axes.py::test_axis_bool_arguments[png]", "lib/matplotlib/tests/test_axes.py::test_axis_extent_arg", "lib/matplotlib/tests/test_axes.py::test_axis_extent_arg2", "lib/matplotlib/tests/test_axes.py::test_hist_auto_bins", "lib/matplotlib/tests/test_axes.py::test_hist_nan_data", "lib/matplotlib/tests/test_axes.py::test_hist_range_and_density", "lib/matplotlib/tests/test_axes.py::test_bar_errbar_zorder", "lib/matplotlib/tests/test_axes.py::test_set_ticks_inverted", "lib/matplotlib/tests/test_axes.py::test_aspect_nonlinear_adjustable_box", "lib/matplotlib/tests/test_axes.py::test_aspect_nonlinear_adjustable_datalim", "lib/matplotlib/tests/test_axes.py::test_box_aspect", "lib/matplotlib/tests/test_axes.py::test_box_aspect_custom_position", "lib/matplotlib/tests/test_axes.py::test_bbox_aspect_axes_init", "lib/matplotlib/tests/test_axes.py::test_set_aspect_negative", "lib/matplotlib/tests/test_axes.py::test_redraw_in_frame", "lib/matplotlib/tests/test_axes.py::test_invisible_axes_events", "lib/matplotlib/tests/test_axes.py::test_xtickcolor_is_not_markercolor", "lib/matplotlib/tests/test_axes.py::test_ytickcolor_is_not_markercolor", "lib/matplotlib/tests/test_axes.py::test_unautoscale[True-x]", "lib/matplotlib/tests/test_axes.py::test_unautoscale[True-y]", "lib/matplotlib/tests/test_axes.py::test_unautoscale[False-x]", "lib/matplotlib/tests/test_axes.py::test_unautoscale[False-y]", "lib/matplotlib/tests/test_axes.py::test_unautoscale[None-x]", "lib/matplotlib/tests/test_axes.py::test_unautoscale[None-y]", "lib/matplotlib/tests/test_axes.py::test_polar_interpolation_steps_variable_r[png]", "lib/matplotlib/tests/test_axes.py::test_autoscale_tiny_sticky", "lib/matplotlib/tests/test_axes.py::test_xtickcolor_is_not_xticklabelcolor", "lib/matplotlib/tests/test_axes.py::test_ytickcolor_is_not_yticklabelcolor", "lib/matplotlib/tests/test_axes.py::test_relative_ticklabel_sizes[xx-small]", "lib/matplotlib/tests/test_axes.py::test_relative_ticklabel_sizes[x-small]", "lib/matplotlib/tests/test_axes.py::test_relative_ticklabel_sizes[small]", "lib/matplotlib/tests/test_axes.py::test_relative_ticklabel_sizes[medium]", "lib/matplotlib/tests/test_axes.py::test_relative_ticklabel_sizes[large]", "lib/matplotlib/tests/test_axes.py::test_relative_ticklabel_sizes[x-large]", "lib/matplotlib/tests/test_axes.py::test_relative_ticklabel_sizes[xx-large]", "lib/matplotlib/tests/test_axes.py::test_relative_ticklabel_sizes[larger]", "lib/matplotlib/tests/test_axes.py::test_relative_ticklabel_sizes[smaller]", "lib/matplotlib/tests/test_axes.py::test_relative_ticklabel_sizes[8]", "lib/matplotlib/tests/test_axes.py::test_relative_ticklabel_sizes[10]", "lib/matplotlib/tests/test_axes.py::test_relative_ticklabel_sizes[12]", "lib/matplotlib/tests/test_axes.py::test_multiplot_autoscale", "lib/matplotlib/tests/test_axes.py::test_sharing_does_not_link_positions", "lib/matplotlib/tests/test_axes.py::test_shared_axes_clear[png]", "lib/matplotlib/tests/test_axes.py::test_shared_axes_retick", "lib/matplotlib/tests/test_axes.py::test_ylabel_ha_with_position[left]", "lib/matplotlib/tests/test_axes.py::test_ylabel_ha_with_position[center]", "lib/matplotlib/tests/test_axes.py::test_ylabel_ha_with_position[right]", "lib/matplotlib/tests/test_axes.py::test_bar_label_location_vertical", "lib/matplotlib/tests/test_axes.py::test_bar_label_location_vertical_yinverted", "lib/matplotlib/tests/test_axes.py::test_bar_label_location_horizontal", "lib/matplotlib/tests/test_axes.py::test_bar_label_location_horizontal_yinverted", "lib/matplotlib/tests/test_axes.py::test_bar_label_location_horizontal_xinverted", "lib/matplotlib/tests/test_axes.py::test_bar_label_location_horizontal_xyinverted", "lib/matplotlib/tests/test_axes.py::test_bar_label_location_center", "lib/matplotlib/tests/test_axes.py::test_bar_label_location_errorbars", "lib/matplotlib/tests/test_axes.py::test_bar_label_fmt[%.2f]", "lib/matplotlib/tests/test_axes.py::test_bar_label_fmt[{:.2f}]", "lib/matplotlib/tests/test_axes.py::test_bar_label_fmt[format]", "lib/matplotlib/tests/test_axes.py::test_bar_label_fmt_error", "lib/matplotlib/tests/test_axes.py::test_bar_label_labels", "lib/matplotlib/tests/test_axes.py::test_bar_label_nan_ydata", "lib/matplotlib/tests/test_axes.py::test_bar_label_nan_ydata_inverted", "lib/matplotlib/tests/test_axes.py::test_nan_barlabels", "lib/matplotlib/tests/test_axes.py::test_patch_bounds", "lib/matplotlib/tests/test_axes.py::test_warn_ignored_scatter_kwargs", "lib/matplotlib/tests/test_axes.py::test_artist_sublists", "lib/matplotlib/tests/test_axes.py::test_empty_line_plots", "lib/matplotlib/tests/test_axes.py::test_plot_format_errors[None-f-'f'", "lib/matplotlib/tests/test_axes.py::test_plot_format_errors[None-o+-'o\\\\+'", "lib/matplotlib/tests/test_axes.py::test_plot_format_errors[None-:--':-'", "lib/matplotlib/tests/test_axes.py::test_plot_format_errors[None-rk-'rk'", "lib/matplotlib/tests/test_axes.py::test_plot_format_errors[None-:o-r-':o-r'", "lib/matplotlib/tests/test_axes.py::test_plot_format_errors[data1-f-'f'", "lib/matplotlib/tests/test_axes.py::test_plot_format_errors[data1-o+-'o\\\\+'", "lib/matplotlib/tests/test_axes.py::test_plot_format_errors[data1-:--':-'", "lib/matplotlib/tests/test_axes.py::test_plot_format_errors[data1-rk-'rk'", "lib/matplotlib/tests/test_axes.py::test_plot_format_errors[data1-:o-r-':o-r'", "lib/matplotlib/tests/test_axes.py::test_plot_format", "lib/matplotlib/tests/test_axes.py::test_automatic_legend", "lib/matplotlib/tests/test_axes.py::test_plot_errors", "lib/matplotlib/tests/test_axes.py::test_clim", "lib/matplotlib/tests/test_axes.py::test_bezier_autoscale", "lib/matplotlib/tests/test_axes.py::test_small_autoscale", "lib/matplotlib/tests/test_axes.py::test_get_xticklabel", "lib/matplotlib/tests/test_axes.py::test_bar_leading_nan", "lib/matplotlib/tests/test_axes.py::test_bar_all_nan[png]", "lib/matplotlib/tests/test_axes.py::test_extent_units[png]" ]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> Add `Axes.get_tick_params()` method. ## PR Summary Addresses https://github.com/matplotlib/matplotlib/issues/23603 - Added `Axis.get_tick_params()` method, which will return `Axis._major_tick_kw` or `Axis._minor_tick_kw` depending on the value of `which` - Added `Axes.get_tick_params()` method, which will return the result of `Axis.get_tick_params()` on the `axis` specified and error out if `both` is passed in ## PR Checklist <!-- Please mark any checkboxes that do not apply to this PR as [N/A]. --> **Tests and Styling** - [x] Has pytest style unit tests (and `pytest` passes). - [X] Is [Flake 8](https://flake8.pycqa.org/en/latest/) compliant (install `flake8-docstrings` and run `flake8 --docstring-convention=all`). **Documentation** - [x] New features are documented, with examples if plot related. - [x] New features have an entry in `doc/users/next_whats_new/` (follow instructions in README.rst there). - [N/A] API changes documented in `doc/api/next_api_changes/` (follow instructions in README.rst there). - [x] Documentation is sphinx and numpydoc compliant (the docs should [build](https://matplotlib.org/devel/documenting_mpl.html#building-the-docs) without error). <!-- Thank you so much for your PR! To help us review your contribution, please consider the following points: - A development guide is available at https://matplotlib.org/devdocs/devel/index.html. - Help with git and github is available at https://matplotlib.org/devel/gitwash/development_workflow.html. - Do not create the PR out of main, but out of a separate branch. - The PR title should summarize the changes, for example "Raise ValueError on non-numeric input to set_xlim". Avoid non-descriptive titles such as "Addresses issue #8576". - The summary should provide at least 1-2 sentences describing the pull request in detail (Why is this change required? What problem does it solve?) and link to any relevant issues. - If you are contributing fixes to docstrings, please pay attention to http://matplotlib.org/devel/documenting_mpl.html#formatting. In particular, note the difference between using single backquotes, double backquotes, and asterisks in the markup. We understand that PRs can sometimes be overwhelming, especially as the reviews start coming in. Please let us know if the reviews are unclear or the recommended next step seems overly demanding, if you would like help in addressing a reviewer's comments, or if you have been waiting too long to hear back on your PR. --> ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in lib/matplotlib/axis.py] (definition of Axis.get_tick_params:) def get_tick_params(self, which='major'): """Get appearance parameters for ticks, ticklabels, and gridlines. .. versionadded:: 3.7 Parameters ---------- which : {'major', 'minor'}, default: 'major' The group of ticks for which the parameters are retrieved. Returns ------- dict Properties for styling tick elements added to the axis. Notes ----- This method returns the appearance parameters for styling *new* elements added to this axis and may be different from the values on current elements if they were modified directly by the user (e.g., via ``set_*`` methods on individual tick objects). Examples -------- :: >>> ax.yaxis.set_tick_params(labelsize=30, labelcolor='red', direction='out', which='major') >>> ax.yaxis.get_tick_params(which='major') {'direction': 'out', 'left': True, 'right': False, 'labelleft': True, 'labelright': False, 'gridOn': False, 'labelsize': 30, 'labelcolor': 'red'} >>> ax.yaxis.get_tick_params(which='minor') {'left': True, 'right': False, 'labelleft': True, 'labelright': False, 'gridOn': False}""" [end of new definitions in lib/matplotlib/axis.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
3d6c3da884fafae4654df68144391cfe9be6f134
conan-io__conan-11908
11,908
conan-io/conan
null
a5525e523d2c6a3636a062134364686059ba8863
2022-08-18T11:25:43Z
diff --git a/conans/client/loader.py b/conans/client/loader.py index d1d89130dd2..804d73b50d1 100644 --- a/conans/client/loader.py +++ b/conans/client/loader.py @@ -2,6 +2,7 @@ import imp import inspect import os +import re import sys import types import uuid @@ -436,13 +437,20 @@ def _parse_conanfile(conan_file_path): old_modules = list(sys.modules.keys()) with chdir(current_dir): old_dont_write_bytecode = sys.dont_write_bytecode - sys.dont_write_bytecode = True - loaded = imp.load_source(module_id, conan_file_path) - sys.dont_write_bytecode = old_dont_write_bytecode - - required_conan_version = getattr(loaded, "required_conan_version", None) - if required_conan_version: - validate_conan_version(required_conan_version) + try: + sys.dont_write_bytecode = True + # FIXME: imp is deprecated in favour of implib + loaded = imp.load_source(module_id, conan_file_path) + sys.dont_write_bytecode = old_dont_write_bytecode + except ImportError: + version_txt = _get_required_conan_version_without_loading(conan_file_path) + if version_txt: + validate_conan_version(version_txt) + raise + + required_conan_version = getattr(loaded, "required_conan_version", None) + if required_conan_version: + validate_conan_version(required_conan_version) # These lines are necessary, otherwise local conanfile imports with same name # collide, but no error, and overwrite other packages imports!! @@ -475,3 +483,20 @@ def _parse_conanfile(conan_file_path): sys.path.pop(0) return loaded, module_id + + +def _get_required_conan_version_without_loading(conan_file_path): + # First, try to detect the required_conan_version in "text" mode + # https://github.com/conan-io/conan/issues/11239 + contents = load(conan_file_path) + + txt_version = None + + try: + found = re.search(r"required_conan_version\s*=\s*(.*)", contents) + if found: + txt_version = found.group(1).replace('"', "") + except: + pass + + return txt_version
diff --git a/conans/test/integration/conanfile/required_conan_version_test.py b/conans/test/integration/conanfile/required_conan_version_test.py index 7f0c11f25c7..f0261c11b03 100644 --- a/conans/test/integration/conanfile/required_conan_version_test.py +++ b/conans/test/integration/conanfile/required_conan_version_test.py @@ -35,3 +35,45 @@ class Lib(ConanFile): client.run("install pkg/1.0@", assert_error=True) self.assertIn("Current Conan version (%s) does not satisfy the defined one (>=100.0)" % __version__, client.out) + + def test_required_conan_version_with_loading_issues(self): + # https://github.com/conan-io/conan/issues/11239 + client = TestClient() + conanfile = textwrap.dedent(""" + from conan import missing_import + + required_conan_version = ">=100.0" + + class Lib(ConanFile): + pass + """) + client.save({"conanfile.py": conanfile}) + client.run("export . pkg/1.0@", assert_error=True) + self.assertIn("Current Conan version (%s) does not satisfy the defined one (>=100.0)" + % __version__, client.out) + + # Assigning required_conan_version without spaces + conanfile = textwrap.dedent(""" + from conan import missing_import + + required_conan_version=">=100.0" + + class Lib(ConanFile): + pass + """) + client.save({"conanfile.py": conanfile}) + client.run("export . pkg/1.0@", assert_error=True) + self.assertIn("Current Conan version (%s) does not satisfy the defined one (>=100.0)" + % __version__, client.out) + + # If the range is correct, everything works, of course + conanfile = textwrap.dedent(""" + from conan import ConanFile + + required_conan_version = ">1.0.0" + + class Lib(ConanFile): + pass + """) + client.save({"conanfile.py": conanfile}) + client.run("export . pkg/1.0@")
[ { "components": [ { "doc": "", "lines": [ 488, 502 ], "name": "_get_required_conan_version_without_loading", "signature": "def _get_required_conan_version_without_loading(conan_file_path):", "type": "function" } ], "file": "conans/client/loader.py" } ]
[ "conans/test/integration/conanfile/required_conan_version_test.py::RequiredConanVersionTest::test_required_conan_version_with_loading_issues" ]
[ "conans/test/integration/conanfile/required_conan_version_test.py::RequiredConanVersionTest::test_required_conan_version" ]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> Read required_conan_version in text mode before loading the recipe Changelog: Feature: Fail sooner and with a meaningful error if the specified required version is not satisfied. Docs: omit Conan will try to read the `required_conan_version` from the recipes without loading the recipe (python interpreter) to be able to check it even if there are imports broken/missing for the user conan current installed version. So Conan can fail sooner and with a meaningful error if the specified required version is not satisfied. Close https://github.com/conan-io/conan/issues/11239 ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in conans/client/loader.py] (definition of _get_required_conan_version_without_loading:) def _get_required_conan_version_without_loading(conan_file_path): [end of new definitions in conans/client/loader.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
4a5b19a75db9225316c8cb022a2dfb9705a2af34
astropy__astropy-13508
13,508
astropy/astropy
5.0
093e96735f6bc4dd87f154c54b6c42667489b602
2022-07-27T18:03:06Z
diff --git a/astropy/time/core.py b/astropy/time/core.py index 3716665aadde..50be00fcfb2a 100644 --- a/astropy/time/core.py +++ b/astropy/time/core.py @@ -1356,6 +1356,82 @@ def sort(self, axis=-1): return self[self._advanced_index(self.argsort(axis), axis, keepdims=True)] + def mean(self, axis=None, dtype=None, out=None, keepdims=False, *, where=True): + """Mean along a given axis. + + This is similar to :meth:`~numpy.ndarray.mean`, but adapted to ensure + that the full precision given by the two doubles ``jd1`` and ``jd2`` is + used, and that corresponding attributes are copied. + + Note that the ``out`` argument is present only for compatibility with + ``np.mean``; since `Time` instances are immutable, it is not possible + to have an actual ``out`` to store the result in. + + Similarly, the ``dtype`` argument is also present for compatibility + only; it has no meaning for `Time`. + + Parameters + ---------- + axis : None or int or tuple of ints, optional + Axis or axes along which the means are computed. The default is to + compute the mean of the flattened array. + dtype : None + Only present for compatibility with :meth:`~numpy.ndarray.mean`, + must be `None`. + out : None + Only present for compatibility with :meth:`~numpy.ndarray.mean`, + must be `None`. + keepdims : bool, optional + If this is set to True, the axes which are reduced are left + in the result as dimensions with size one. With this option, + the result will broadcast correctly against the input array. + where : array_like of bool, optional + Elements to include in the mean. See `~numpy.ufunc.reduce` for + details. + + Returns + ------- + m : Time + A new Time instance containing the mean values + """ + if dtype is not None: + raise ValueError('Cannot set ``dtype`` on `Time` instances') + if out is not None: + raise ValueError("Since `Time` instances are immutable, ``out`` " + "cannot be set to anything but ``None``.") + + where = where & ~self.mask + where_broadcasted = np.broadcast_to(where, self.shape) + + kwargs = dict( + axis=axis, + keepdims=keepdims, + where=where, + ) + + divisor = np.sum(where_broadcasted, axis=axis, keepdims=keepdims) + if np.any(divisor == 0): + raise ValueError( + 'Mean over zero elements is not supported as it would give an undefined time;' + 'see issue https://github.com/astropy/astropy/issues/6509' + ) + + jd1, jd2 = day_frac( + val1=np.sum(np.ma.getdata(self.jd1), **kwargs), + val2=np.sum(np.ma.getdata(self.jd2), **kwargs), + divisor=divisor, + ) + + result = type(self)( + val=jd1, + val2=jd2, + format='jd', + scale=self.scale, + copy=False, + ) + result.format = self.format + return result + @property def cache(self): """ @@ -2275,6 +2351,44 @@ def __add__(self, other): def __radd__(self, other): return self.__add__(other) + def mean(self, axis=None, dtype=None, out=None, keepdims=False, *, where=True): + + scale = self.scale + if scale == 'utc': + self = self.tai + result = super().mean(axis=axis, dtype=dtype, out=out, keepdims=keepdims, where=where) + if scale == 'utc': + result = result.utc + + result.out_subfmt = self.out_subfmt + + location = self.location + if self.location is not None: + if self.location.shape: + + if axis is None: + axis_normalized = tuple(range(self.ndim)) + elif isinstance(axis, int): + axis_normalized = axis, + else: + axis_normalized = axis + + sl = [slice(None)] * self.location.ndim + for a in axis_normalized: + sl[a] = slice(0, 1) + + if np.any(self.location != self.location[tuple(sl)]): + raise ValueError("`location` must be constant over the reduction axes.") + + if not keepdims: + for a in axis_normalized: + sl[a] = 0 + + location = self.location[tuple(sl)] + + result.location = location + return result + def __array_function__(self, function, types, args, kwargs): """ Wrap numpy functions. diff --git a/docs/changes/time/13508.feature.rst b/docs/changes/time/13508.feature.rst new file mode 100644 index 000000000000..d6dffaa3b3db --- /dev/null +++ b/docs/changes/time/13508.feature.rst @@ -0,0 +1,1 @@ +Added the ``astropy.time.Time.mean()`` method which also enables the ``numpy.mean()`` function to be used on instances of ``astropy.time.Time``.
diff --git a/astropy/table/tests/test_info.py b/astropy/table/tests/test_info.py index 9a2977074bb9..6ea33917c75e 100644 --- a/astropy/table/tests/test_info.py +++ b/astropy/table/tests/test_info.py @@ -67,7 +67,7 @@ def test_table_info_stats(table_types): a = np.array([1, 2, 1, 2], dtype='int32') b = np.array([1, 2, 1, 2], dtype='float32') c = np.array(['a', 'c', 'e', 'f'], dtype='|S1') - d = time.Time([1, 2, 1, 2], format='mjd') + d = time.Time([1, 2, 1, 2], format='mjd', scale='tai') t = table_types.Table([a, b, c, d], names=['a', 'b', 'c', 'd']) # option = 'stats' @@ -81,14 +81,14 @@ def test_table_info_stats(table_types): ' a 1.5 0.5 1 2', ' b 1.5 0.5 1 2', ' c -- -- -- --', - ' d -- -- 1.0 2.0'] + ' d 1.5 -- 1.0 2.0'] assert out.getvalue().splitlines() == exp # option = ['attributes', 'stats'] tinfo = t.info(['attributes', 'stats'], out=None) assert tinfo.colnames == ['name', 'dtype', 'shape', 'unit', 'format', 'description', 'class', 'mean', 'std', 'min', 'max', 'n_bad', 'length'] - assert np.all(tinfo['mean'] == ['1.5', '1.5', '--', '--']) + assert np.all(tinfo['mean'] == ['1.5', '1.5', '--', '1.5']) assert np.all(tinfo['std'] == ['0.5', '0.5', '--', '--']) assert np.all(tinfo['min'] == ['1', '1', '--', '1.0']) assert np.all(tinfo['max'] == ['2', '2', '--', '2.0']) @@ -101,7 +101,7 @@ def test_table_info_stats(table_types): ' a 1.5 0.5 1 2', ' b 1.5 0.5 1 2', ' c -- -- -- --', - ' d -- -- 1.0 2.0'] + ' d 1.5 -- 1.0 2.0'] assert out.getvalue().splitlines() == exp # option = ['attributes', custom] diff --git a/astropy/time/tests/test_delta.py b/astropy/time/tests/test_delta.py index 1bc2915d694e..7ce39db9ce1c 100644 --- a/astropy/time/tests/test_delta.py +++ b/astropy/time/tests/test_delta.py @@ -209,6 +209,16 @@ def test_mul_div(self): with pytest.raises(TypeError): self.dt * object() + def test_mean(self): + + def is_consistent(time_delta: TimeDelta): + mean_expected = (np.sum(time_delta.jd1) + np.sum(time_delta.jd2)) / time_delta.size + mean_test = time_delta.mean().jd1 + time_delta.mean().jd2 + return mean_test == mean_expected + + assert is_consistent(self.dt) + assert is_consistent(self.dt_array) + def test_keep_properties(self): # closes #1924 (partially) dt = TimeDelta(1000., format='sec') diff --git a/astropy/time/tests/test_methods.py b/astropy/time/tests/test_methods.py index 8fac951171fc..65bb05722884 100644 --- a/astropy/time/tests/test_methods.py +++ b/astropy/time/tests/test_methods.py @@ -7,7 +7,9 @@ import numpy as np import pytest +import astropy.units as u from astropy.time import Time +from astropy.time.utils import day_frac from astropy.units.quantity_helper.function_helpers import ARRAY_FUNCTION_ENABLED from astropy.utils import iers @@ -479,9 +481,17 @@ def setup_class(cls): 'masked': mjd + frac_masked } + cls.t2 = { + 'not_masked': Time(mjd + frac, format='mjd', scale='utc', + location=(np.arange(len(frac)), np.arange(len(frac)))), + 'masked': Time(mjd + frac_masked, format='mjd', scale='utc', + location=(np.arange(len(frac_masked)), np.arange(len(frac_masked)))), + } + def create_data(self, use_mask): self.t0 = self.__class__.t0[use_mask] self.t1 = self.__class__.t1[use_mask] + self.t2 = self.__class__.t2[use_mask] self.jd = self.__class__.jd[use_mask] @pytest.mark.parametrize('kw, func', itertools.product(kwargs, functions)) @@ -619,6 +629,92 @@ def test_sort(self, use_mask): assert np.all(self.t0.sort(-1)[:, :, 0] == self.t0.min(-1)) assert np.all(self.t0.sort(-1)[:, :, -1] == self.t0.max(-1)) + @pytest.mark.parametrize('axis', [None, 0, 1, 2, (0, 1)]) + @pytest.mark.parametrize('where', [True, np.array([True, False, True, True, False])[..., np.newaxis]]) + @pytest.mark.parametrize('keepdims', [False, True]) + def test_mean(self, use_mask, axis, where, keepdims): + self.create_data(use_mask) + + kwargs = dict(axis=axis, where=where, keepdims=keepdims) + + def is_consistent(time): + + where_expected = where & ~time.mask + where_expected = np.broadcast_to(where_expected, time.shape) + + kw = kwargs.copy() + kw['where'] = where_expected + + divisor = where_expected.sum(axis=axis, keepdims=keepdims) + + if np.any(divisor == 0): + with pytest.raises(ValueError): + time.mean(**kwargs) + + else: + time_mean = time.mean(**kwargs) + time_expected = Time( + *day_frac( + val1=np.ma.getdata(time.tai.jd1).sum(**kw), + val2=np.ma.getdata(time.tai.jd2).sum(**kw), + divisor=divisor + ), + format='jd', + scale='tai', + ) + time_expected._set_scale(time.scale) + assert np.all(time_mean == time_expected) + + is_consistent(self.t0) + is_consistent(self.t1) + + axes_location_not_constant = [None, 2] + if axis in axes_location_not_constant: + with pytest.raises(ValueError): + self.t2.mean(**kwargs) + else: + is_consistent(self.t2) + + def test_mean_precision(self, use_mask): + + scale = 'tai' + epsilon = 1 * u.ns + + t0 = Time('2021-07-27T00:00:00', scale=scale) + t1 = Time('2022-07-27T00:00:00', scale=scale) + t2 = Time('2023-07-27T00:00:00', scale=scale) + + t = Time([t0, t2 + epsilon]) + + if use_mask == 'masked': + t[0] = np.ma.masked + assert t.mean() == (t2 + epsilon) + + else: + assert t.mean() == (t1 + epsilon / 2) + + def test_mean_dtype(self, use_mask): + self.create_data(use_mask) + with pytest.raises(ValueError): + self.t0.mean(dtype=int) + + def test_mean_out(self, use_mask): + self.create_data(use_mask) + with pytest.raises(ValueError): + self.t0.mean(out=Time(np.zeros_like(self.t0.jd1), format='jd')) + + def test_mean_leap_second(self, use_mask): + # Check that leap second is dealt with correctly: for UTC, across a leap + # second bounday, one cannot just average jd, but has to go through TAI. + if use_mask == 'not_masked': + t = Time(['2012-06-30 23:59:60.000', '2012-07-01 00:00:01.000']) + mean_expected = t[0] + (t[1] - t[0]) / 2 + mean_expected_explicit = Time('2012-07-01 00:00:00') + mean_test = t.mean() + assert mean_expected == mean_expected_explicit + assert mean_expected == mean_test + assert mean_test != Time(*day_frac(t.jd1.sum(), t.jd2.sum(), divisor=2), format='jd') + def test_regression(): # For #5225, where a time with a single-element delta_ut1_utc could not
diff --git a/docs/changes/time/13508.feature.rst b/docs/changes/time/13508.feature.rst new file mode 100644 index 000000000000..d6dffaa3b3db --- /dev/null +++ b/docs/changes/time/13508.feature.rst @@ -0,0 +1,1 @@ +Added the ``astropy.time.Time.mean()`` method which also enables the ``numpy.mean()`` function to be used on instances of ``astropy.time.Time``.
[ { "components": [ { "doc": "Mean along a given axis.\n\nThis is similar to :meth:`~numpy.ndarray.mean`, but adapted to ensure\nthat the full precision given by the two doubles ``jd1`` and ``jd2`` is\nused, and that corresponding attributes are copied.\n\nNote that the ``out`` argument is present only for compatibility with\n``np.mean``; since `Time` instances are immutable, it is not possible\nto have an actual ``out`` to store the result in.\n\nSimilarly, the ``dtype`` argument is also present for compatibility\nonly; it has no meaning for `Time`.\n\nParameters\n----------\naxis : None or int or tuple of ints, optional\n Axis or axes along which the means are computed. The default is to\n compute the mean of the flattened array.\ndtype : None\n Only present for compatibility with :meth:`~numpy.ndarray.mean`,\n must be `None`.\nout : None\n Only present for compatibility with :meth:`~numpy.ndarray.mean`,\n must be `None`.\nkeepdims : bool, optional\n If this is set to True, the axes which are reduced are left\n in the result as dimensions with size one. With this option,\n the result will broadcast correctly against the input array.\nwhere : array_like of bool, optional\n Elements to include in the mean. See `~numpy.ufunc.reduce` for\n details.\n\nReturns\n-------\nm : Time\n A new Time instance containing the mean values", "lines": [ 1359, 1433 ], "name": "TimeBase.mean", "signature": "def mean(self, axis=None, dtype=None, out=None, keepdims=False, *, where=True):", "type": "function" }, { "doc": "", "lines": [ 2354, 2390 ], "name": "Time.mean", "signature": "def mean(self, axis=None, dtype=None, out=None, keepdims=False, *, where=True):", "type": "function" } ], "file": "astropy/time/core.py" } ]
[ "astropy/table/tests/test_info.py::test_table_info_stats[unmasked]", "astropy/table/tests/test_info.py::test_table_info_stats[masked]", "astropy/table/tests/test_info.py::test_table_info_stats[subclass]", "astropy/time/tests/test_methods.py::TestArithmetic::test_mean[False-True-None-masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_mean[False-True-None-not_masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_mean[False-True-0-masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_mean[False-True-0-not_masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_mean[False-True-1-masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_mean[False-True-1-not_masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_mean[False-True-2-masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_mean[False-True-2-not_masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_mean[False-True-axis4-masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_mean[False-True-axis4-not_masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_mean[False-where1-None-masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_mean[False-where1-None-not_masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_mean[False-where1-0-masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_mean[False-where1-0-not_masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_mean[False-where1-1-masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_mean[False-where1-1-not_masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_mean[False-where1-2-masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_mean[False-where1-2-not_masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_mean[False-where1-axis4-masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_mean[False-where1-axis4-not_masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_mean[True-True-None-masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_mean[True-True-None-not_masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_mean[True-True-0-masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_mean[True-True-0-not_masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_mean[True-True-1-masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_mean[True-True-1-not_masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_mean[True-True-2-masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_mean[True-True-2-not_masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_mean[True-True-axis4-masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_mean[True-True-axis4-not_masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_mean[True-where1-None-masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_mean[True-where1-None-not_masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_mean[True-where1-0-masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_mean[True-where1-0-not_masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_mean[True-where1-1-masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_mean[True-where1-1-not_masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_mean[True-where1-2-masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_mean[True-where1-2-not_masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_mean[True-where1-axis4-masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_mean[True-where1-axis4-not_masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_mean_precision[masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_mean_precision[not_masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_mean_dtype[masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_mean_dtype[not_masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_mean_out[masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_mean_out[not_masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_mean_leap_second[not_masked]" ]
[ "astropy/table/tests/test_info.py::test_table_info_attributes[unmasked]", "astropy/table/tests/test_info.py::test_table_info_attributes[masked]", "astropy/table/tests/test_info.py::test_table_info_attributes[subclass]", "astropy/table/tests/test_info.py::test_data_info", "astropy/table/tests/test_info.py::test_data_info_subclass", "astropy/table/tests/test_info.py::test_scalar_info", "astropy/table/tests/test_info.py::test_empty_table", "astropy/table/tests/test_info.py::test_class_attribute", "astropy/table/tests/test_info.py::test_ignore_warnings", "astropy/table/tests/test_info.py::test_no_deprecation_warning", "astropy/table/tests/test_info.py::test_lost_parent_error", "astropy/table/tests/test_info.py::test_info_serialize_method", "astropy/table/tests/test_info.py::test_info_serialize_method_exception", "astropy/time/tests/test_delta.py::test_timedelta_setitem", "astropy/time/tests/test_delta.py::test_timedelta_setitem_sec", "astropy/time/tests/test_delta.py::test_timedelta_mask", "astropy/time/tests/test_delta.py::test_python_timedelta_scalar", "astropy/time/tests/test_delta.py::test_python_timedelta_vector", "astropy/time/tests/test_delta.py::test_timedelta_to_datetime", "astropy/time/tests/test_delta.py::test_insert_timedelta", "astropy/time/tests/test_delta.py::test_no_units_warning", "astropy/time/tests/test_methods.py::TestManipulation::test_ravel[masked]", "astropy/time/tests/test_methods.py::TestManipulation::test_ravel[not_masked]", "astropy/time/tests/test_methods.py::TestManipulation::test_flatten[masked]", "astropy/time/tests/test_methods.py::TestManipulation::test_flatten[not_masked]", "astropy/time/tests/test_methods.py::TestManipulation::test_transpose[masked]", "astropy/time/tests/test_methods.py::TestManipulation::test_transpose[not_masked]", "astropy/time/tests/test_methods.py::TestManipulation::test_diagonal[masked]", "astropy/time/tests/test_methods.py::TestManipulation::test_diagonal[not_masked]", "astropy/time/tests/test_methods.py::TestManipulation::test_swapaxes[masked]", "astropy/time/tests/test_methods.py::TestManipulation::test_swapaxes[not_masked]", "astropy/time/tests/test_methods.py::TestManipulation::test_reshape[masked]", "astropy/time/tests/test_methods.py::TestManipulation::test_reshape[not_masked]", "astropy/time/tests/test_methods.py::TestManipulation::test_squeeze[masked]", "astropy/time/tests/test_methods.py::TestManipulation::test_squeeze[not_masked]", "astropy/time/tests/test_methods.py::TestManipulation::test_add_dimension[masked]", "astropy/time/tests/test_methods.py::TestManipulation::test_add_dimension[not_masked]", "astropy/time/tests/test_methods.py::TestManipulation::test_take[masked]", "astropy/time/tests/test_methods.py::TestManipulation::test_take[not_masked]", "astropy/time/tests/test_methods.py::TestManipulation::test_broadcast_via_apply[masked]", "astropy/time/tests/test_methods.py::TestManipulation::test_broadcast_via_apply[not_masked]", "astropy/time/tests/test_methods.py::TestSetShape::test_shape_setting[masked]", "astropy/time/tests/test_methods.py::TestSetShape::test_shape_setting[not_masked]", "astropy/time/tests/test_methods.py::TestShapeFunctions::test_broadcast[masked]", "astropy/time/tests/test_methods.py::TestShapeFunctions::test_broadcast[not_masked]", "astropy/time/tests/test_methods.py::TestShapeFunctions::test_atleast_1d[masked]", "astropy/time/tests/test_methods.py::TestShapeFunctions::test_atleast_1d[not_masked]", "astropy/time/tests/test_methods.py::TestShapeFunctions::test_atleast_2d[masked]", "astropy/time/tests/test_methods.py::TestShapeFunctions::test_atleast_2d[not_masked]", "astropy/time/tests/test_methods.py::TestShapeFunctions::test_atleast_3d[masked]", "astropy/time/tests/test_methods.py::TestShapeFunctions::test_atleast_3d[not_masked]", "astropy/time/tests/test_methods.py::TestShapeFunctions::test_move_axis[masked]", "astropy/time/tests/test_methods.py::TestShapeFunctions::test_move_axis[not_masked]", "astropy/time/tests/test_methods.py::TestShapeFunctions::test_roll_axis[masked]", "astropy/time/tests/test_methods.py::TestShapeFunctions::test_roll_axis[not_masked]", "astropy/time/tests/test_methods.py::TestShapeFunctions::test_fliplr[masked]", "astropy/time/tests/test_methods.py::TestShapeFunctions::test_fliplr[not_masked]", "astropy/time/tests/test_methods.py::TestShapeFunctions::test_rot90[masked]", "astropy/time/tests/test_methods.py::TestShapeFunctions::test_rot90[not_masked]", "astropy/time/tests/test_methods.py::TestShapeFunctions::test_roll[masked]", "astropy/time/tests/test_methods.py::TestShapeFunctions::test_roll[not_masked]", "astropy/time/tests/test_methods.py::TestShapeFunctions::test_delete[masked]", "astropy/time/tests/test_methods.py::TestShapeFunctions::test_delete[not_masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_argfuncs[kw0-min-masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_argfuncs[kw0-min-not_masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_argfuncs[kw1-max-masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_argfuncs[kw1-max-not_masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_argfuncs[kw2-sort-masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_argfuncs[kw2-sort-not_masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_argfuncs[kw3-min-masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_argfuncs[kw3-min-not_masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_argfuncs[kw4-max-masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_argfuncs[kw4-max-not_masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_argfuncs[kw5-sort-masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_argfuncs[kw5-sort-not_masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_argfuncs[kw6-min-masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_argfuncs[kw6-min-not_masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_argfuncs[kw7-max-masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_argfuncs[kw7-max-not_masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_argfuncs[kw8-sort-masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_argfuncs[kw8-sort-not_masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_argfuncs[kw9-min-masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_argfuncs[kw9-min-not_masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_argfuncs[kw10-max-masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_argfuncs[kw10-max-not_masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_argfuncs[kw11-sort-masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_argfuncs[kw11-sort-not_masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_argfuncs[kw12-min-masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_argfuncs[kw12-min-not_masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_argfuncs[kw13-max-masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_argfuncs[kw13-max-not_masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_argfuncs[kw14-sort-masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_argfuncs[kw14-sort-not_masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_funcs[kw0-min-masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_funcs[kw0-min-not_masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_funcs[kw1-max-masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_funcs[kw1-max-not_masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_funcs[kw2-sort-masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_funcs[kw2-sort-not_masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_funcs[kw3-min-masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_funcs[kw3-min-not_masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_funcs[kw4-max-masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_funcs[kw4-max-not_masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_funcs[kw5-sort-masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_funcs[kw5-sort-not_masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_funcs[kw6-min-masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_funcs[kw6-min-not_masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_funcs[kw7-max-masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_funcs[kw7-max-not_masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_funcs[kw8-sort-masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_funcs[kw8-sort-not_masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_funcs[kw9-min-masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_funcs[kw9-min-not_masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_funcs[kw10-max-masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_funcs[kw10-max-not_masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_funcs[kw11-sort-masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_funcs[kw11-sort-not_masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_funcs[kw12-min-masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_funcs[kw12-min-not_masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_funcs[kw13-max-masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_funcs[kw13-max-not_masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_funcs[kw14-sort-masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_funcs[kw14-sort-not_masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_argmin[masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_argmin[not_masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_argmax[masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_argmax[not_masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_argsort[masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_argsort[not_masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_argsort_warning[tai-masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_argsort_warning[tai-not_masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_argsort_warning[tcb-masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_argsort_warning[tcb-not_masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_argsort_warning[tcg-masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_argsort_warning[tcg-not_masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_argsort_warning[tdb-masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_argsort_warning[tdb-not_masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_argsort_warning[tt-masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_argsort_warning[tt-not_masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_argsort_warning[ut1-masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_argsort_warning[ut1-not_masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_argsort_warning[local-masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_argsort_warning[local-not_masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_min[masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_min[not_masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_max[masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_max[not_masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_ptp[masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_ptp[not_masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_sort[masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_sort[not_masked]", "astropy/time/tests/test_methods.py::TestArithmetic::test_mean_leap_second[masked]", "astropy/time/tests/test_methods.py::test_regression" ]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> Enabled `np.mean()` function for instances of `astropy.time.Time`. <!-- This comments are hidden when you submit the pull request, so you do not need to remove them! --> <!-- Please be sure to check out our contributing guidelines, https://github.com/astropy/astropy/blob/main/CONTRIBUTING.md . Please be sure to check out our code of conduct, https://github.com/astropy/astropy/blob/main/CODE_OF_CONDUCT.md . --> <!-- If you are new or need to be re-acquainted with Astropy contributing workflow, please see http://docs.astropy.org/en/latest/development/workflow/development_workflow.html . There is even a practical example at https://docs.astropy.org/en/latest/development/workflow/git_edit_workflow_examples.html#astropy-fix-example . --> <!-- Astropy coding style guidelines can be found here: https://docs.astropy.org/en/latest/development/codeguide.html#coding-style-conventions Our testing infrastructure enforces to follow a subset of the PEP8 to be followed. You can check locally whether your changes have followed these by running the following command: tox -e codestyle --> <!-- Please just have a quick search on GitHub to see if a similar pull request has already been posted. We have old closed pull requests that might provide useful code or ideas that directly tie in with your pull request. --> <!-- We have several automatic features that run when a pull request is open. They can appear daunting but do not worry because maintainers will help you navigate them, if necessary. --> ### Description <!-- Provide a general description of what your pull request does. Complete the following sentence and add relevant details as you see fit. --> <!-- In addition please ensure that the pull request title is descriptive and allows maintainers to infer the applicable subpackage(s). --> <!-- READ THIS FOR MANUAL BACKPORT FROM A MAINTAINER: Apply "skip-basebranch-check" label **before** you open the PR! --> This pull request is to address enabling the `numpy.mean()` array function to instances of `astropy.time.Time` <!-- If the pull request closes any open issues you can add this. If you replace <Issue Number> with a number, GitHub will automatically link it. If this pull request is unrelated to any issues, please remove the following line. --> Fixes #13507 ### Checklist for package maintainer(s) <!-- This section is to be filled by package maintainer(s) who will review this pull request. --> This checklist is meant to remind the package maintainer(s) who will review this pull request of some common things to look for. This list is not exhaustive. - [x] Do the proposed changes actually accomplish desired goals? - [x] Do the proposed changes follow the [Astropy coding guidelines](https://docs.astropy.org/en/latest/development/codeguide.html)? - [x] Are tests added/updated as required? If so, do they follow the [Astropy testing guidelines](https://docs.astropy.org/en/latest/development/testguide.html)? - [x] Are docs added/updated as required? If so, do they follow the [Astropy documentation guidelines](https://docs.astropy.org/en/latest/development/docguide.html#astropy-documentation-rules-and-guidelines)? - [x] Is rebase and/or squash necessary? If so, please provide the author with appropriate instructions. Also see ["When to rebase and squash commits"](https://docs.astropy.org/en/latest/development/when_to_rebase.html). - [x] Did the CI pass? If no, are the failures related? If you need to run daily and weekly cron jobs as part of the PR, please apply the `Extra CI` label. - [x] Is a change log needed? If yes, did the change log check pass? If no, add the `no-changelog-entry-needed` label. If this is a manual backport, use the `skip-changelog-checks` label unless special changelog handling is necessary. - [x] Is this a big PR that makes a "What's new?" entry worthwhile and if so, is (1) a "what's new" entry included in this PR and (2) the "whatsnew-needed" label applied? - [x] Is a milestone set? Milestone must be set but `astropy-bot` check might be missing; do not let the green checkmark fool you. - [x] At the time of adding the milestone, if the milestone set requires a backport to release branch(es), apply the appropriate `backport-X.Y.x` label(s) *before* merge. ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in astropy/time/core.py] (definition of TimeBase.mean:) def mean(self, axis=None, dtype=None, out=None, keepdims=False, *, where=True): """Mean along a given axis. This is similar to :meth:`~numpy.ndarray.mean`, but adapted to ensure that the full precision given by the two doubles ``jd1`` and ``jd2`` is used, and that corresponding attributes are copied. Note that the ``out`` argument is present only for compatibility with ``np.mean``; since `Time` instances are immutable, it is not possible to have an actual ``out`` to store the result in. Similarly, the ``dtype`` argument is also present for compatibility only; it has no meaning for `Time`. Parameters ---------- axis : None or int or tuple of ints, optional Axis or axes along which the means are computed. The default is to compute the mean of the flattened array. dtype : None Only present for compatibility with :meth:`~numpy.ndarray.mean`, must be `None`. out : None Only present for compatibility with :meth:`~numpy.ndarray.mean`, must be `None`. keepdims : bool, optional If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. where : array_like of bool, optional Elements to include in the mean. See `~numpy.ufunc.reduce` for details. Returns ------- m : Time A new Time instance containing the mean values""" (definition of Time.mean:) def mean(self, axis=None, dtype=None, out=None, keepdims=False, *, where=True): [end of new definitions in astropy/time/core.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
Here is the discussion in the issues of the pull request. <issues> Enable `np.mean()` for `astropy.time.Time` ### Description The `__array_function__` dispatch mechanism was recently added to astropy. Can we use this mechanism to activate the `np.mean()` array function for instances of `astropy.time.Time`? If so, what is the most efficient way to implement this, considering the many time formats? ---------- -------------------- </issues>
7cbba866a8c5749b90a5cb4f9877ddfad2d36037
conan-io__conan-11678
11,678
conan-io/conan
null
f4d5c49f0fbba650cf5162107f2135ca48336778
2022-07-20T08:20:27Z
diff --git a/conan/tools/gnu/autotoolstoolchain.py b/conan/tools/gnu/autotoolstoolchain.py index 52ee17a3939..d10f36d3b05 100644 --- a/conan/tools/gnu/autotoolstoolchain.py +++ b/conan/tools/gnu/autotoolstoolchain.py @@ -22,10 +22,10 @@ def __init__(self, conanfile, namespace=None): self.make_args = [] # Flags - self.cxxflags = [] - self.cflags = [] - self.ldflags = [] - self.defines = [] + self.extra_cxxflags = [] + self.extra_cflags = [] + self.extra_ldflags = [] + self.extra_defines = [] # Defines self.gcc_cxx11_abi = self._get_cxx11_abi_define() @@ -122,46 +122,52 @@ def _get_libcxx_flag(self): def _filter_list_empty_fields(v): return list(filter(bool, v)) - def _get_extra_flags(self): - # Now, it's time to get all the flags defined by the user - cxxflags = self._conanfile.conf.get("tools.build:cxxflags", default=[], check_type=list) - cflags = self._conanfile.conf.get("tools.build:cflags", default=[], check_type=list) - sharedlinkflags = self._conanfile.conf.get("tools.build:sharedlinkflags", default=[], check_type=list) - exelinkflags = self._conanfile.conf.get("tools.build:exelinkflags", default=[], check_type=list) - defines = self._conanfile.conf.get("tools.build:defines", default=[], check_type=list) - return { - "cxxflags": cxxflags, - "cflags": cflags, - "defines": defines, - "ldflags": sharedlinkflags + exelinkflags - } - - def environment(self): - env = Environment() - + @property + def cxxflags(self): + fpic = "-fPIC" if self.fpic else None + ret = [self.libcxx, self.cppstd, self.arch_flag, fpic, self.msvc_runtime_flag, + self.sysroot_flag] apple_flags = [self.apple_isysroot_flag, self.apple_arch_flag, self.apple_min_version_flag] + conf_flags = self._conanfile.conf.get("tools.build:cxxflags", default=[], check_type=list) + ret = ret + self.build_type_flags + apple_flags + conf_flags + self.extra_cxxflags + return self._filter_list_empty_fields(ret) + + @property + def cflags(self): fpic = "-fPIC" if self.fpic else None - extra_flags = self._get_extra_flags() + ret = [self.arch_flag, fpic, self.msvc_runtime_flag, self.sysroot_flag] + apple_flags = [self.apple_isysroot_flag, self.apple_arch_flag, self.apple_min_version_flag] + conf_flags = self._conanfile.conf.get("tools.build:cflags", default=[], check_type=list) + ret = ret + self.build_type_flags + apple_flags + conf_flags + self.extra_cflags + return self._filter_list_empty_fields(ret) - self.cxxflags.extend([self.libcxx, self.cppstd, - self.arch_flag, fpic, self.msvc_runtime_flag, self.sysroot_flag] - + self.build_type_flags + apple_flags + extra_flags["cxxflags"]) - self.cflags.extend([self.arch_flag, fpic, self.msvc_runtime_flag, self.sysroot_flag] - + self.build_type_flags + apple_flags + extra_flags["cflags"]) - self.ldflags.extend([self.arch_flag, self.sysroot_flag] + self.build_type_link_flags - + apple_flags + extra_flags["ldflags"]) - self.defines.extend([self.ndebug, self.gcc_cxx11_abi] + extra_flags["defines"]) + @property + def ldflags(self): + ret = [self.arch_flag, self.sysroot_flag] + apple_flags = [self.apple_isysroot_flag, self.apple_arch_flag, self.apple_min_version_flag] + conf_flags = self._conanfile.conf.get("tools.build:sharedlinkflags", default=[], + check_type=list) + conf_flags.extend(self._conanfile.conf.get("tools.build:exelinkflags", default=[], + check_type=list)) + ret = ret + apple_flags + conf_flags + self.build_type_link_flags + self.extra_ldflags + return self._filter_list_empty_fields(ret) + + @property + def defines(self): + conf_flags = self._conanfile.conf.get("tools.build:defines", default=[], check_type=list) + ret = [self.ndebug, self.gcc_cxx11_abi] + conf_flags + self.extra_defines + return self._filter_list_empty_fields(ret) + def environment(self): + env = Environment() if is_msvc(self._conanfile): env.define("CXX", "cl") env.define("CC", "cl") - - env.append("CPPFLAGS", ["-D{}".format(d) for d in self._filter_list_empty_fields(self.defines)]) - env.append("CXXFLAGS", self._filter_list_empty_fields(self.cxxflags)) - env.append("CFLAGS", self._filter_list_empty_fields(self.cflags)) - env.append("LDFLAGS", self._filter_list_empty_fields(self.ldflags)) + env.append("CPPFLAGS", ["-D{}".format(d) for d in self.defines]) + env.append("CXXFLAGS", self.cxxflags) + env.append("CFLAGS", self.cflags) + env.append("LDFLAGS", self.ldflags) env.prepend_path("PKG_CONFIG_PATH", self._conanfile.generators_folder) - return env def vars(self):
diff --git a/conans/test/integration/toolchains/gnu/test_autotoolstoolchain.py b/conans/test/integration/toolchains/gnu/test_autotoolstoolchain.py index 7a20a026036..36ede715b8f 100644 --- a/conans/test/integration/toolchains/gnu/test_autotoolstoolchain.py +++ b/conans/test/integration/toolchains/gnu/test_autotoolstoolchain.py @@ -42,3 +42,28 @@ def test_extra_flags_via_conf(): assert 'export CXXFLAGS="$CXXFLAGS -O3 -s --flag1 --flag2"' in toolchain assert 'export CFLAGS="$CFLAGS -O3 -s --flag3 --flag4"' in toolchain assert 'export LDFLAGS="$LDFLAGS --flag5 --flag6"' in toolchain + + +def test_not_none_values(): + + conanfile = textwrap.dedent(""" + from conan import ConanFile + from conan.tools.gnu import AutotoolsToolchain + + class Foo(ConanFile): + name = "foo" + version = "1.0" + + def generate(self): + tc = AutotoolsToolchain(self) + assert None not in tc.defines + assert None not in tc.cxxflags + assert None not in tc.cflags + assert None not in tc.ldflags + + """) + + client = TestClient() + client.save({"conanfile.py": conanfile}) + client.run("install .") + diff --git a/conans/test/unittests/client/toolchain/autotools/autotools_toolchain_test.py b/conans/test/unittests/client/toolchain/autotools/autotools_toolchain_test.py index a9232a1e622..fb9ba023148 100644 --- a/conans/test/unittests/client/toolchain/autotools/autotools_toolchain_test.py +++ b/conans/test/unittests/client/toolchain/autotools/autotools_toolchain_test.py @@ -364,7 +364,12 @@ def test_custom_defines(): "os.version": "14", "arch": "armv8"}) be = AutotoolsToolchain(conanfile) - be.defines = ["MyDefine1", "MyDefine2"] + be.extra_defines = ["MyDefine1", "MyDefine2"] + + assert "MyDefine1" in be.defines + assert "MyDefine2" in be.defines + assert "NDEBUG" in be.defines + env = be.vars() assert "-DMyDefine1" in env["CPPFLAGS"] assert "-DMyDefine2" in env["CPPFLAGS"] @@ -380,7 +385,14 @@ def test_custom_cxxflags(): "os.version": "14", "arch": "armv8"}) be = AutotoolsToolchain(conanfile) - be.cxxflags = ["MyFlag1", "MyFlag2"] + be.extra_cxxflags = ["MyFlag1", "MyFlag2"] + + assert "MyFlag1" in be.cxxflags + assert "MyFlag2" in be.cxxflags + assert "-mios-version-min=14" in be.cxxflags + assert "MyFlag" not in be.cflags + assert "MyFlag" not in be.ldflags + env = be.vars() assert "MyFlag1" in env["CXXFLAGS"] assert "MyFlag2" in env["CXXFLAGS"] @@ -399,7 +411,14 @@ def test_custom_cflags(): "os.version": "14", "arch": "armv8"}) be = AutotoolsToolchain(conanfile) - be.cflags = ["MyFlag1", "MyFlag2"] + be.extra_cflags = ["MyFlag1", "MyFlag2"] + + assert "MyFlag1" in be.cflags + assert "MyFlag2" in be.cflags + assert "-mios-version-min=14" in be.cflags + assert "MyFlag" not in be.cxxflags + assert "MyFlag" not in be.ldflags + env = be.vars() assert "MyFlag1" in env["CFLAGS"] assert "MyFlag2" in env["CFLAGS"] @@ -418,7 +437,14 @@ def test_custom_ldflags(): "os.version": "14", "arch": "armv8"}) be = AutotoolsToolchain(conanfile) - be.ldflags = ["MyFlag1", "MyFlag2"] + be.extra_ldflags = ["MyFlag1", "MyFlag2"] + + assert "MyFlag1" in be.ldflags + assert "MyFlag2" in be.ldflags + assert "-mios-version-min=14" in be.ldflags + assert "MyFlag" not in be.cxxflags + assert "MyFlag" not in be.cflags + env = be.vars() assert "MyFlag1" in env["LDFLAGS"] assert "MyFlag2" in env["LDFLAGS"]
[ { "components": [ { "doc": "", "lines": [ 126, 133 ], "name": "AutotoolsToolchain.cxxflags", "signature": "def cxxflags(self):", "type": "function" }, { "doc": "", "lines": [ 136, 142 ], "name": "AutotoolsToolchain.cflags", "signature": "def cflags(self):", "type": "function" }, { "doc": "", "lines": [ 145, 153 ], "name": "AutotoolsToolchain.ldflags", "signature": "def ldflags(self):", "type": "function" }, { "doc": "", "lines": [ 156, 159 ], "name": "AutotoolsToolchain.defines", "signature": "def defines(self):", "type": "function" } ], "file": "conan/tools/gnu/autotoolstoolchain.py" } ]
[ "conans/test/unittests/client/toolchain/autotools/autotools_toolchain_test.py::test_custom_defines", "conans/test/unittests/client/toolchain/autotools/autotools_toolchain_test.py::test_custom_cxxflags", "conans/test/unittests/client/toolchain/autotools/autotools_toolchain_test.py::test_custom_cflags", "conans/test/unittests/client/toolchain/autotools/autotools_toolchain_test.py::test_custom_ldflags" ]
[ "conans/test/integration/toolchains/gnu/test_autotoolstoolchain.py::test_extra_flags_via_conf", "conans/test/integration/toolchains/gnu/test_autotoolstoolchain.py::test_not_none_values", "conans/test/unittests/client/toolchain/autotools/autotools_toolchain_test.py::test_modify_environment", "conans/test/unittests/client/toolchain/autotools/autotools_toolchain_test.py::test_target_triple", "conans/test/unittests/client/toolchain/autotools/autotools_toolchain_test.py::test_invalid_target_triple", "conans/test/unittests/client/toolchain/autotools/autotools_toolchain_test.py::test_cppstd", "conans/test/unittests/client/toolchain/autotools/autotools_toolchain_test.py::test_fpic", "conans/test/unittests/client/toolchain/autotools/autotools_toolchain_test.py::test_ndebug", "conans/test/unittests/client/toolchain/autotools/autotools_toolchain_test.py::test_libcxx[config0]", "conans/test/unittests/client/toolchain/autotools/autotools_toolchain_test.py::test_libcxx[config1]", "conans/test/unittests/client/toolchain/autotools/autotools_toolchain_test.py::test_libcxx[config2]", "conans/test/unittests/client/toolchain/autotools/autotools_toolchain_test.py::test_libcxx[config3]", "conans/test/unittests/client/toolchain/autotools/autotools_toolchain_test.py::test_libcxx[config4]", "conans/test/unittests/client/toolchain/autotools/autotools_toolchain_test.py::test_libcxx[config5]", "conans/test/unittests/client/toolchain/autotools/autotools_toolchain_test.py::test_libcxx[config6]", "conans/test/unittests/client/toolchain/autotools/autotools_toolchain_test.py::test_libcxx[config7]", "conans/test/unittests/client/toolchain/autotools/autotools_toolchain_test.py::test_libcxx[config8]", "conans/test/unittests/client/toolchain/autotools/autotools_toolchain_test.py::test_libcxx[config9]", "conans/test/unittests/client/toolchain/autotools/autotools_toolchain_test.py::test_libcxx[config10]", "conans/test/unittests/client/toolchain/autotools/autotools_toolchain_test.py::test_libcxx[config11]", "conans/test/unittests/client/toolchain/autotools/autotools_toolchain_test.py::test_libcxx[config12]", "conans/test/unittests/client/toolchain/autotools/autotools_toolchain_test.py::test_libcxx[config13]", "conans/test/unittests/client/toolchain/autotools/autotools_toolchain_test.py::test_libcxx[config14]", "conans/test/unittests/client/toolchain/autotools/autotools_toolchain_test.py::test_cxx11_abi_define", "conans/test/unittests/client/toolchain/autotools/autotools_toolchain_test.py::test_architecture_flag[config0]", "conans/test/unittests/client/toolchain/autotools/autotools_toolchain_test.py::test_architecture_flag[config1]", "conans/test/unittests/client/toolchain/autotools/autotools_toolchain_test.py::test_build_type_flag[Visual", "conans/test/unittests/client/toolchain/autotools/autotools_toolchain_test.py::test_build_type_flag[msvc]", "conans/test/unittests/client/toolchain/autotools/autotools_toolchain_test.py::test_apple_arch_flag", "conans/test/unittests/client/toolchain/autotools/autotools_toolchain_test.py::test_apple_min_os_flag", "conans/test/unittests/client/toolchain/autotools/autotools_toolchain_test.py::test_apple_isysrootflag", "conans/test/unittests/client/toolchain/autotools/autotools_toolchain_test.py::test_sysrootflag", "conans/test/unittests/client/toolchain/autotools/autotools_toolchain_test.py::test_extra_flags_via_conf" ]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> AutotoolsToolchain: empty None values from self fields + Refactor Changelog: Bugfix: The `AutotoolsToolchain` now clears `None` values from the attributes `.cxxflags`, `.cflags`, `.ldflags` and `.defines`. Changelog: Feature: The `AutotoolsToolchain` attributes `.cxxflags`, `.cflags`, `.ldflags` and `.defines` can be read at any moment, now is not needed to call `.environment()` to get them calculated. In the other hand, if you want to add additional flags the following attributes have to be used: `.extra_cxxflags`, `.extra_cflags`, `.extra_ldflags` and `.extra_defines` Docs: https://github.com/conan-io/docs/pull/2660 ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in conan/tools/gnu/autotoolstoolchain.py] (definition of AutotoolsToolchain.cxxflags:) def cxxflags(self): (definition of AutotoolsToolchain.cflags:) def cflags(self): (definition of AutotoolsToolchain.ldflags:) def ldflags(self): (definition of AutotoolsToolchain.defines:) def defines(self): [end of new definitions in conan/tools/gnu/autotoolstoolchain.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
4a5b19a75db9225316c8cb022a2dfb9705a2af34
conan-io__conan-11675
11,675
conan-io/conan
null
2e7692bfd24210918d8a1e4203e6e79a0bca7878
2022-07-20T07:03:56Z
diff --git a/conans/paths/__init__.py b/conans/paths/__init__.py index 6457f1ad010..5992053360d 100644 --- a/conans/paths/__init__.py +++ b/conans/paths/__init__.py @@ -1,7 +1,7 @@ # coding=utf-8 - import os import platform +from pathlib import Path if platform.system() == "Windows": from conans.util.windows import conan_expand_user @@ -12,7 +12,34 @@ def get_conan_user_home(): - user_home = os.getenv("CONAN_HOME") + + def _find_conanrc_file(): + path = Path(os.getcwd()) + while path.is_dir() and len(path.parts) > 1: # finish at '/' + conanrc_file = path / ".conanrc" + if conanrc_file.is_file(): + return conanrc_file + else: + path = path.parent + + def _user_home_from_conanrc_file(): + try: + conanrc_path = _find_conanrc_file() + + with open(conanrc_path) as conanrc_file: + values = {k: str(v) for k, v in + (line.split('=') for line in conanrc_file.read().splitlines() if + not line.startswith("#"))} + + conan_home = values["conan_home"] + # check if it's a local folder + if conan_home[:2] in ("./", ".\\") or conan_home.startswith(".."): + conan_home = conanrc_path.parent.absolute() / conan_home + return conan_home + except (OSError, KeyError, TypeError): + return None + + user_home = _user_home_from_conanrc_file() or os.getenv("CONAN_HOME") if user_home is None: # the default, in the user home user_home = os.path.join(conan_expand_user("~"), DEFAULT_CONAN_HOME)
diff --git a/conans/test/unittests/paths/user_home_test.py b/conans/test/unittests/paths/user_home_test.py new file mode 100644 index 00000000000..8b9912bac7a --- /dev/null +++ b/conans/test/unittests/paths/user_home_test.py @@ -0,0 +1,83 @@ +import os +import platform +from pathlib import Path + +from conans.paths import get_conan_user_home, DEFAULT_CONAN_HOME +from conans.test.utils.test_files import temp_folder +from conans.util.files import chdir + +if platform.system() == "Windows": + from conans.util.windows import conan_expand_user +else: + conan_expand_user = os.path.expanduser + + +def test_conanrc_abs_path_get_conan_user_home(): + _temp_folder = temp_folder(path_with_spaces=True) + folder_conan_runs = os.path.join(_temp_folder, "folder_where_conan_runs") + os.mkdir(folder_conan_runs) + with open(os.path.join(_temp_folder, ".conanrc"), 'w+') as file: + file.write(f'conan_home={_temp_folder}\n') + with chdir(folder_conan_runs): + conan_home = get_conan_user_home() + assert _temp_folder == conan_home + + +def test_conanrc_local_path_get_conan_user_home(): + _temp_folder = temp_folder(path_with_spaces=True) + subfolder = "subfolder inside temp" + with chdir(_temp_folder): + with open(os.path.join(_temp_folder, ".conanrc"), 'w+') as file: + file.write(f'conan_home=.{os.sep}{subfolder}\n') + conan_home = get_conan_user_home() + assert str(os.path.join(_temp_folder, subfolder)) == conan_home + + +def test_conanrc_local_path_run_conan_subfolder_get_conan_user_home(): + _temp_folder = temp_folder(path_with_spaces=True) + folder_conan_runs = os.path.join(_temp_folder, "folder_where_conan_runs") + os.mkdir(folder_conan_runs) + with open(os.path.join(_temp_folder, ".conanrc"), 'w+') as file: + file.write(f'conan_home=.{os.sep}\n') + with chdir(folder_conan_runs): + conan_home = get_conan_user_home() + assert str(os.path.join(_temp_folder)) == conan_home + + +def test_conanrc_local_outside_folder_path_get_conan_user_home(): + _temp_folder = temp_folder(path_with_spaces=True) + folder1 = os.path.join(_temp_folder, "folder1") + os.mkdir(folder1) + with chdir(folder1): + with open(os.path.join(folder1, ".conanrc"), 'w+') as file: + file.write(f'conan_home=..{os.sep}folder2\n') + conan_home = get_conan_user_home() + this_path = Path(_temp_folder) / "folder1" / f"..{os.sep}folder2" + assert str(this_path) == str(conan_home) + + +def test_conanrc_comments(): + _temp_folder = temp_folder(path_with_spaces=True) + with chdir(_temp_folder): + with open(os.path.join(_temp_folder, ".conanrc"), 'w+') as file: + file.write(f'#commenting something\nconan_home={_temp_folder}\n') + conan_home = get_conan_user_home() + assert _temp_folder == conan_home + + +def test_conanrc_wrong_format(): + _temp_folder = temp_folder(path_with_spaces=True) + with chdir(_temp_folder): + with open(os.path.join(_temp_folder, ".conanrc"), 'w+') as file: + file.write(f'ronan_jome={_temp_folder}\n') + conan_home = get_conan_user_home() + + assert os.path.join(conan_expand_user("~"), DEFAULT_CONAN_HOME) == conan_home + assert _temp_folder not in conan_home + + +def test_conanrc_not_existing(): + _temp_folder = temp_folder(path_with_spaces=True) + with chdir(_temp_folder): + conan_home = get_conan_user_home() + assert os.path.join(conan_expand_user("~"), DEFAULT_CONAN_HOME) == conan_home
[ { "components": [ { "doc": "", "lines": [ 16, 23 ], "name": "get_conan_user_home._find_conanrc_file", "signature": "def _find_conanrc_file():", "type": "function" }, { "doc": "", "lines": [ 25, 40 ], "name": "get_conan_user_home._user_home_from_conanrc_file", "signature": "def _user_home_from_conanrc_file():", "type": "function" } ], "file": "conans/paths/__init__.py" } ]
[ "conans/test/unittests/paths/user_home_test.py::test_conanrc_abs_path_get_conan_user_home", "conans/test/unittests/paths/user_home_test.py::test_conanrc_local_path_get_conan_user_home", "conans/test/unittests/paths/user_home_test.py::test_conanrc_local_path_run_conan_subfolder_get_conan_user_home", "conans/test/unittests/paths/user_home_test.py::test_conanrc_local_outside_folder_path_get_conan_user_home", "conans/test/unittests/paths/user_home_test.py::test_conanrc_comments" ]
[ "conans/test/unittests/paths/user_home_test.py::test_conanrc_wrong_format", "conans/test/unittests/paths/user_home_test.py::test_conanrc_not_existing" ]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> Add conan.conanrc file to setup the conan user home Closes: https://github.com/conan-io/conan/issues/11542 You can create a _.conanrc_ file in the folder where you are running conan (or any parent folder), it can have this content: Set the conan home to an absolute folder ``` # accepts comments conan_home=/absolute/folder ``` Set the conan home to a relative folder inside the current folder ``` # accepts comments conan_home=./relative folder/inside current folder ``` Set the conan home to a relative folder outside the current folder ``` # accepts comments conan_home=../relative folder/outside current folder ``` Set the conan home to a path containing the `~` that will be expanded to the system's user home ``` # accepts comments conan_home=~/use the user home to expand it ``` The _.conanrc_ file is searched for in all parent folders so, if for example, in this structure: ```` . .conanrc ├── project1 └── project2 ```` And you are running from folder `project1` the parent folders are traversed recursively until a _.conanrc_ is found in case it exists. ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in conans/paths/__init__.py] (definition of get_conan_user_home._find_conanrc_file:) def _find_conanrc_file(): (definition of get_conan_user_home._user_home_from_conanrc_file:) def _user_home_from_conanrc_file(): [end of new definitions in conans/paths/__init__.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
4a5b19a75db9225316c8cb022a2dfb9705a2af34
conan-io__conan-11585
11,585
conan-io/conan
null
b20b72beb77c063d8c27c55db37425349e232a26
2022-07-07T14:41:53Z
diff --git a/conans/client/loader.py b/conans/client/loader.py index 4fafe819775..d1d89130dd2 100644 --- a/conans/client/loader.py +++ b/conans/client/loader.py @@ -8,6 +8,8 @@ import yaml +from pathlib import Path + from conan.tools.cmake import cmake_layout from conan.tools.google import bazel_layout from conan.tools.microsoft import vs_layout @@ -73,6 +75,7 @@ def load_basic_module(self, conanfile_path, lock_python_requires=None, user=None self._pyreq_loader.load_py_requires(conanfile, lock_python_requires, self) conanfile.recipe_folder = os.path.dirname(conanfile_path) + conanfile.recipe_path = Path(conanfile.recipe_folder) # If the scm is inherited, create my own instance if hasattr(conanfile, "scm") and "scm" not in conanfile.__class__.__dict__: diff --git a/conans/model/conan_file.py b/conans/model/conan_file.py index ce9a2ba2a8e..69fe57e1a4d 100644 --- a/conans/model/conan_file.py +++ b/conans/model/conan_file.py @@ -1,6 +1,7 @@ import os import platform from contextlib import contextmanager +from pathlib import Path import six from six import string_types @@ -258,6 +259,11 @@ def new_cpp_info(self): def source_folder(self): return self.folders.source_folder + @property + def source_path(self) -> Path: + assert self.source_folder is not None, "`source_folder` is `None`" + return Path(self.source_folder) + @property def export_sources_folder(self): """points to the base source folder when calling source() and to the cache export sources @@ -265,18 +271,38 @@ def export_sources_folder(self): 'no_copy_export_sources' and point to the right location always.""" return self.folders.base_export_sources + @property + def export_sources_path(self) -> Path: + assert self.export_sources_folder is not None, "`export_sources_folder` is `None`" + return Path(self.export_sources_folder) + @property def export_folder(self): return self.folders.base_export + @property + def export_path(self) -> Path: + assert self.export_folder is not None, "`export_folder` is `None`" + return Path(self.export_folder) + @property def build_folder(self): return self.folders.build_folder + @property + def build_path(self) -> Path: + assert self.build_folder is not None, "`build_folder` is `None`" + return Path(self.build_folder) + @property def package_folder(self): return self.folders.base_package + @property + def package_path(self) -> Path: + assert self.package_folder is not None, "`package_folder` is `None`" + return Path(self.package_folder) + @property def install_folder(self): # FIXME: Remove in 2.0, no self.install_folder @@ -287,6 +313,11 @@ def generators_folder(self): # FIXME: Remove in 2.0, no self.install_folder return self.folders.generators_folder if self.folders.generators else self.install_folder + @property + def generators_path(self) -> Path: + assert self.generators_folder is not None, "`generators_folder` is `None`" + return Path(self.generators_folder) + @property def imports_folder(self): return self.folders.imports_folder diff --git a/conans/model/conanfile_interface.py b/conans/model/conanfile_interface.py index 22617a72d28..fd9c8b5d127 100644 --- a/conans/model/conanfile_interface.py +++ b/conans/model/conanfile_interface.py @@ -1,3 +1,4 @@ +from pathlib import Path from conans.client.graph.graph import CONTEXT_BUILD @@ -29,6 +30,11 @@ def __ne__(self, other): def package_folder(self): return self._conanfile.package_folder + @property + def package_path(self) -> Path: + assert self.package_folder is not None, "`package_folder` is `None`" + return Path(self.package_folder) + @property def ref(self): return self._conanfile.ref
diff --git a/conans/test/integration/conanfile/folders_access_test.py b/conans/test/integration/conanfile/folders_access_test.py index 3a6a635f81c..741643aa6ab 100644 --- a/conans/test/integration/conanfile/folders_access_test.py +++ b/conans/test/integration/conanfile/folders_access_test.py @@ -22,6 +22,7 @@ def package_info(self): conanfile = """ import os +from pathlib import Path from conans import ConanFile class AConan(ConanFile): @@ -45,6 +46,8 @@ def assert_in_local_cache(self): def source(self): assert(self.source_folder == os.getcwd()) + assert(isinstance(self.source_path, Path)) + assert(str(self.source_path) == self.source_folder) self.assert_in_local_cache() # Prevented to use them, it's dangerous, because the source is run only for the first @@ -65,6 +68,8 @@ def assert_deps_infos(self): def build(self): assert(self.build_folder == os.getcwd()) + assert(isinstance(self.build_path, Path)) + assert(str(self.build_path) == self.build_folder) self.assert_in_local_cache() self.assert_deps_infos() @@ -77,11 +82,15 @@ def build(self): self.install_folder assert(self.package_folder is not None) + assert(isinstance(self.package_path, Path)) + assert(str(self.package_path) == self.package_folder) self.copy_build_folder = self.build_folder def package(self): assert(self.install_folder is not None) assert(self.build_folder == os.getcwd()) + assert(isinstance(self.build_path, Path)) + assert(str(self.build_path) == self.build_folder) self.assert_in_local_cache() self.assert_deps_infos() @@ -97,6 +106,8 @@ def package(self): def package_info(self): assert(self.package_folder == os.getcwd()) + assert(isinstance(self.package_path, Path)) + assert(str(self.package_path) == self.package_folder) assert(self.in_local_cache == True) assert(self.source_folder is None)
[ { "components": [ { "doc": "", "lines": [ 263, 265 ], "name": "ConanFile.source_path", "signature": "def source_path(self) -> Path:", "type": "function" }, { "doc": "", "lines": [ 275, 277 ], "name": "ConanFile.export_sources_path", "signature": "def export_sources_path(self) -> Path:", "type": "function" }, { "doc": "", "lines": [ 284, 286 ], "name": "ConanFile.export_path", "signature": "def export_path(self) -> Path:", "type": "function" }, { "doc": "", "lines": [ 293, 295 ], "name": "ConanFile.build_path", "signature": "def build_path(self) -> Path:", "type": "function" }, { "doc": "", "lines": [ 302, 304 ], "name": "ConanFile.package_path", "signature": "def package_path(self) -> Path:", "type": "function" }, { "doc": "", "lines": [ 317, 319 ], "name": "ConanFile.generators_path", "signature": "def generators_path(self) -> Path:", "type": "function" } ], "file": "conans/model/conan_file.py" }, { "components": [ { "doc": "", "lines": [ 34, 36 ], "name": "ConanFileInterface.package_path", "signature": "def package_path(self) -> Path:", "type": "function" } ], "file": "conans/model/conanfile_interface.py" } ]
[ "conans/test/integration/conanfile/folders_access_test.py::TestFoldersAccess::test_build_local_command", "conans/test/integration/conanfile/folders_access_test.py::TestFoldersAccess::test_deploy", "conans/test/integration/conanfile/folders_access_test.py::TestFoldersAccess::test_full_install", "conans/test/integration/conanfile/folders_access_test.py::TestFoldersAccess::test_package_local_command", "conans/test/integration/conanfile/folders_access_test.py::TestFoldersAccess::test_source_local_command" ]
[ "conans/test/integration/conanfile/folders_access_test.py::TestFoldersAccess::test_imports_local", "conans/test/integration/conanfile/folders_access_test.py::RecipeFolderTest::test_editable", "conans/test/integration/conanfile/folders_access_test.py::RecipeFolderTest::test_local_flow", "conans/test/integration/conanfile/folders_access_test.py::RecipeFolderTest::test_recipe_folder" ]
This is a feature request which requires a new feature to add in the code repository. <<NEW FEATURE REQUEST>> <request> Feature : provide Path accesssors closes: #11304 Changelog: Feature: Provide Path accessors in Conanfile. Docs: omit - [x] Refer to the issue that supports this Pull Request. - [x] If the issue has missing info, explain the purpose/use case/pain/need that covers this Pull Request. - [x] I've read the [Contributing guide](https://github.com/conan-io/conan/blob/develop/.github/CONTRIBUTING.md). - [x] I've followed the PEP8 style guides for Python code. - [ ] I've opened another PR in the Conan docs repo to the ``develop`` branch, documenting this one. <sup>**Note:** By default this PR will skip the slower tests and will use a limited set of python versions. Check [here](https://github.com/conan-io/conan/blob/develop/.github/PR_INCREASE_TESTING.md) how to increase the testing level by writing some tags in the current PR body text.</sup> ---------- </request> There are several new functions or classes that need to be implemented, using the definitions below: <<NEW DEFINITIONS>> There are several new functions or classes that need to be implemented, using the definitions below: <definitions> [start of new definitions in conans/model/conan_file.py] (definition of ConanFile.source_path:) def source_path(self) -> Path: (definition of ConanFile.export_sources_path:) def export_sources_path(self) -> Path: (definition of ConanFile.export_path:) def export_path(self) -> Path: (definition of ConanFile.build_path:) def build_path(self) -> Path: (definition of ConanFile.package_path:) def package_path(self) -> Path: (definition of ConanFile.generators_path:) def generators_path(self) -> Path: [end of new definitions in conans/model/conan_file.py] [start of new definitions in conans/model/conanfile_interface.py] (definition of ConanFileInterface.package_path:) def package_path(self) -> Path: [end of new definitions in conans/model/conanfile_interface.py] </definitions> Please note that in addition to the newly added components mentioned above, you also need to make other code changes to ensure that the new feature can be executed properly. <<END>>
4a5b19a75db9225316c8cb022a2dfb9705a2af34